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/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
59 #define DEBUG_TYPE "x86-isel"
61 STATISTIC(NumTailCalls, "Number of tail calls");
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64 "x86-experimental-vector-widening-legalization", cl::init(false),
65 cl::desc("Enable an experimental vector type legalization through widening "
66 "rather than promotion."),
69 static cl::opt<int> ReciprocalEstimateRefinementSteps(
70 "x86-recip-refinement-steps", cl::init(1),
71 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
72 "result of the hardware reciprocal estimate instruction."),
75 // Forward declarations.
76 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
79 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
80 SelectionDAG &DAG, SDLoc dl,
81 unsigned vectorWidth) {
82 assert((vectorWidth == 128 || vectorWidth == 256) &&
83 "Unsupported vector width");
84 EVT VT = Vec.getValueType();
85 EVT ElVT = VT.getVectorElementType();
86 unsigned Factor = VT.getSizeInBits()/vectorWidth;
87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88 VT.getVectorNumElements()/Factor);
90 // Extract from UNDEF is UNDEF.
91 if (Vec.getOpcode() == ISD::UNDEF)
92 return DAG.getUNDEF(ResultVT);
94 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
95 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
97 // This is the index of the first element of the vectorWidth-bit chunk
99 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
102 // If the input is a buildvector just emit a smaller one.
103 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
104 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
105 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
108 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
109 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit boundary. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
163 SelectionDAG &DAG, SDLoc dl) {
164 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 // For insertion into the zero index (low half) of a 256-bit vector, it is
167 // more efficient to generate a blend with immediate instead of an insert*128.
168 // We are still creating an INSERT_SUBVECTOR below with an undef node to
169 // extend the subvector to the size of the result vector. Make sure that
170 // we are not recursing on that node by checking for undef here.
171 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
172 Result.getOpcode() != ISD::UNDEF) {
173 EVT ResultVT = Result.getValueType();
174 SDValue ZeroIndex = DAG.getIntPtrConstant(0);
175 SDValue Undef = DAG.getUNDEF(ResultVT);
176 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
179 // The blend instruction, and therefore its mask, depend on the data type.
180 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
181 if (ScalarType.isFloatingPoint()) {
182 // Choose either vblendps (float) or vblendpd (double).
183 unsigned ScalarSize = ScalarType.getSizeInBits();
184 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
185 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
186 SDValue Mask = DAG.getConstant(MaskVal, MVT::i8);
187 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
190 const X86Subtarget &Subtarget =
191 static_cast<const X86Subtarget &>(DAG.getSubtarget());
193 // AVX2 is needed for 256-bit integer blend support.
194 // Integers must be cast to 32-bit because there is only vpblendd;
195 // vpblendw can't be used for this because it has a handicapped mask.
197 // If we don't have AVX2, then cast to float. Using a wrong domain blend
198 // is still more efficient than using the wrong domain vinsertf128 that
199 // will be created by InsertSubVector().
200 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
202 SDValue Mask = DAG.getConstant(0x0f, MVT::i8);
203 Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
204 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
205 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
208 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
211 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
212 SelectionDAG &DAG, SDLoc dl) {
213 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
214 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
217 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
218 /// instructions. This is used because creating CONCAT_VECTOR nodes of
219 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
220 /// large BUILD_VECTORS.
221 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
222 unsigned NumElems, SelectionDAG &DAG,
224 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
225 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
228 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
229 unsigned NumElems, SelectionDAG &DAG,
231 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
232 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
235 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
236 const X86Subtarget &STI)
237 : TargetLowering(TM), Subtarget(&STI) {
238 X86ScalarSSEf64 = Subtarget->hasSSE2();
239 X86ScalarSSEf32 = Subtarget->hasSSE1();
240 TD = getDataLayout();
242 // Set up the TargetLowering object.
243 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
245 // X86 is weird. It always uses i8 for shift amounts and setcc results.
246 setBooleanContents(ZeroOrOneBooleanContent);
247 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
248 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
250 // For 64-bit, since we have so many registers, use the ILP scheduler.
251 // For 32-bit, use the register pressure specific scheduling.
252 // For Atom, always use ILP scheduling.
253 if (Subtarget->isAtom())
254 setSchedulingPreference(Sched::ILP);
255 else if (Subtarget->is64Bit())
256 setSchedulingPreference(Sched::ILP);
258 setSchedulingPreference(Sched::RegPressure);
259 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
260 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
262 // Bypass expensive divides on Atom when compiling with O2.
263 if (TM.getOptLevel() >= CodeGenOpt::Default) {
264 if (Subtarget->hasSlowDivide32())
265 addBypassSlowDiv(32, 8);
266 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
267 addBypassSlowDiv(64, 16);
270 if (Subtarget->isTargetKnownWindowsMSVC()) {
271 // Setup Windows compiler runtime calls.
272 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
273 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
274 setLibcallName(RTLIB::SREM_I64, "_allrem");
275 setLibcallName(RTLIB::UREM_I64, "_aullrem");
276 setLibcallName(RTLIB::MUL_I64, "_allmul");
277 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
280 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
281 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
283 // The _ftol2 runtime function has an unusual calling conv, which
284 // is modeled by a special pseudo-instruction.
285 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
287 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
288 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
291 if (Subtarget->isTargetDarwin()) {
292 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
293 setUseUnderscoreSetJmp(false);
294 setUseUnderscoreLongJmp(false);
295 } else if (Subtarget->isTargetWindowsGNU()) {
296 // MS runtime is weird: it exports _setjmp, but longjmp!
297 setUseUnderscoreSetJmp(true);
298 setUseUnderscoreLongJmp(false);
300 setUseUnderscoreSetJmp(true);
301 setUseUnderscoreLongJmp(true);
304 // Set up the register classes.
305 addRegisterClass(MVT::i8, &X86::GR8RegClass);
306 addRegisterClass(MVT::i16, &X86::GR16RegClass);
307 addRegisterClass(MVT::i32, &X86::GR32RegClass);
308 if (Subtarget->is64Bit())
309 addRegisterClass(MVT::i64, &X86::GR64RegClass);
311 for (MVT VT : MVT::integer_valuetypes())
312 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
314 // We don't accept any truncstore of integer registers.
315 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
316 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
317 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
318 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
319 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
320 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
322 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
324 // SETOEQ and SETUNE require checking two conditions.
325 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
326 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
327 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
328 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
329 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
330 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
332 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
334 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
336 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
338 if (Subtarget->is64Bit()) {
339 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
340 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
341 } else if (!TM.Options.UseSoftFloat) {
342 // We have an algorithm for SSE2->double, and we turn this into a
343 // 64-bit FILD followed by conditional FADD for other targets.
344 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
345 // We have an algorithm for SSE2, and we turn this into a 64-bit
346 // FILD for other targets.
347 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
350 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
352 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
353 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
355 if (!TM.Options.UseSoftFloat) {
356 // SSE has no i16 to fp conversion, only i32
357 if (X86ScalarSSEf32) {
358 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
359 // f32 and f64 cases are Legal, f80 case is not
360 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
363 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
366 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
367 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
370 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
371 // are Legal, f80 is custom lowered.
372 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
373 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
375 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
377 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
378 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
380 if (X86ScalarSSEf32) {
381 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
382 // f32 and f64 cases are Legal, f80 case is not
383 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
385 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
386 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
389 // Handle FP_TO_UINT by promoting the destination to a larger signed
391 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
393 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
395 if (Subtarget->is64Bit()) {
396 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
397 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
398 } else if (!TM.Options.UseSoftFloat) {
399 // Since AVX is a superset of SSE3, only check for SSE here.
400 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
401 // Expand FP_TO_UINT into a select.
402 // FIXME: We would like to use a Custom expander here eventually to do
403 // the optimal thing for SSE vs. the default expansion in the legalizer.
404 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
406 // With SSE3 we can use fisttpll to convert to a signed i64; without
407 // SSE, we're stuck with a fistpll.
408 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
411 if (isTargetFTOL()) {
412 // Use the _ftol2 runtime function, which has a pseudo-instruction
413 // to handle its weird calling convention.
414 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
417 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
418 if (!X86ScalarSSEf64) {
419 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
420 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
423 // Without SSE, i64->f64 goes through memory.
424 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
428 // Scalar integer divide and remainder are lowered to use operations that
429 // produce two results, to match the available instructions. This exposes
430 // the two-result form to trivial CSE, which is able to combine x/y and x%y
431 // into a single instruction.
433 // Scalar integer multiply-high is also lowered to use two-result
434 // operations, to match the available instructions. However, plain multiply
435 // (low) operations are left as Legal, as there are single-result
436 // instructions for this in x86. Using the two-result multiply instructions
437 // when both high and low results are needed must be arranged by dagcombine.
438 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
440 setOperationAction(ISD::MULHS, VT, Expand);
441 setOperationAction(ISD::MULHU, VT, Expand);
442 setOperationAction(ISD::SDIV, VT, Expand);
443 setOperationAction(ISD::UDIV, VT, Expand);
444 setOperationAction(ISD::SREM, VT, Expand);
445 setOperationAction(ISD::UREM, VT, Expand);
447 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
448 setOperationAction(ISD::ADDC, VT, Custom);
449 setOperationAction(ISD::ADDE, VT, Custom);
450 setOperationAction(ISD::SUBC, VT, Custom);
451 setOperationAction(ISD::SUBE, VT, Custom);
454 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
455 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
456 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
458 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
459 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
460 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
461 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
462 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
465 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
466 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
467 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
468 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
469 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
472 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
473 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
474 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
475 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
476 setOperationAction(ISD::FREM , MVT::f32 , Expand);
477 setOperationAction(ISD::FREM , MVT::f64 , Expand);
478 setOperationAction(ISD::FREM , MVT::f80 , Expand);
479 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
481 // Promote the i8 variants and force them on up to i32 which has a shorter
483 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
484 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
485 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
486 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
487 if (Subtarget->hasBMI()) {
488 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
489 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
493 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
494 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
495 if (Subtarget->is64Bit())
496 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
499 if (Subtarget->hasLZCNT()) {
500 // When promoting the i8 variants, force them to i32 for a shorter
502 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
503 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
505 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
506 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
507 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
508 if (Subtarget->is64Bit())
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
511 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
512 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
513 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
515 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
516 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
517 if (Subtarget->is64Bit()) {
518 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
519 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
523 // Special handling for half-precision floating point conversions.
524 // If we don't have F16C support, then lower half float conversions
525 // into library calls.
526 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
527 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
528 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
531 // There's never any support for operations beyond MVT::f32.
532 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
533 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
534 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
535 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
537 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
538 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
539 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
540 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
541 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
542 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
544 if (Subtarget->hasPOPCNT()) {
545 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
547 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
548 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
549 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
550 if (Subtarget->is64Bit())
551 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
554 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
556 if (!Subtarget->hasMOVBE())
557 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
559 // These should be promoted to a larger select which is supported.
560 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
561 // X86 wants to expand cmov itself.
562 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
563 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
564 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
565 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
566 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
567 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
568 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
569 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
570 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
571 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
572 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
573 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
574 if (Subtarget->is64Bit()) {
575 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
576 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
578 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
579 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
580 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
581 // support continuation, user-level threading, and etc.. As a result, no
582 // other SjLj exception interfaces are implemented and please don't build
583 // your own exception handling based on them.
584 // LLVM/Clang supports zero-cost DWARF exception handling.
585 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
586 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
589 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
590 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
591 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
592 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
593 if (Subtarget->is64Bit())
594 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
595 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
596 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
597 if (Subtarget->is64Bit()) {
598 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
599 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
600 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
601 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
602 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
604 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
605 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
606 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
607 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
608 if (Subtarget->is64Bit()) {
609 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
610 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
611 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
614 if (Subtarget->hasSSE1())
615 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
617 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
619 // Expand certain atomics
620 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
622 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
623 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
624 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
627 if (Subtarget->hasCmpxchg16b()) {
628 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
631 // FIXME - use subtarget debug flags
632 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
633 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
634 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
637 if (Subtarget->is64Bit()) {
638 setExceptionPointerRegister(X86::RAX);
639 setExceptionSelectorRegister(X86::RDX);
641 setExceptionPointerRegister(X86::EAX);
642 setExceptionSelectorRegister(X86::EDX);
644 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
645 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
647 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
648 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
650 setOperationAction(ISD::TRAP, MVT::Other, Legal);
651 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
653 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
654 setOperationAction(ISD::VASTART , MVT::Other, Custom);
655 setOperationAction(ISD::VAEND , MVT::Other, Expand);
656 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
657 // TargetInfo::X86_64ABIBuiltinVaList
658 setOperationAction(ISD::VAARG , MVT::Other, Custom);
659 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
661 // TargetInfo::CharPtrBuiltinVaList
662 setOperationAction(ISD::VAARG , MVT::Other, Expand);
663 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
666 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
667 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
669 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
671 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
672 // f32 and f64 use SSE.
673 // Set up the FP register classes.
674 addRegisterClass(MVT::f32, &X86::FR32RegClass);
675 addRegisterClass(MVT::f64, &X86::FR64RegClass);
677 // Use ANDPD to simulate FABS.
678 setOperationAction(ISD::FABS , MVT::f64, Custom);
679 setOperationAction(ISD::FABS , MVT::f32, Custom);
681 // Use XORP to simulate FNEG.
682 setOperationAction(ISD::FNEG , MVT::f64, Custom);
683 setOperationAction(ISD::FNEG , MVT::f32, Custom);
685 // Use ANDPD and ORPD to simulate FCOPYSIGN.
686 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
687 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
689 // Lower this to FGETSIGNx86 plus an AND.
690 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
691 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
693 // We don't support sin/cos/fmod
694 setOperationAction(ISD::FSIN , MVT::f64, Expand);
695 setOperationAction(ISD::FCOS , MVT::f64, Expand);
696 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
697 setOperationAction(ISD::FSIN , MVT::f32, Expand);
698 setOperationAction(ISD::FCOS , MVT::f32, Expand);
699 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
701 // Expand FP immediates into loads from the stack, except for the special
703 addLegalFPImmediate(APFloat(+0.0)); // xorpd
704 addLegalFPImmediate(APFloat(+0.0f)); // xorps
705 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
706 // Use SSE for f32, x87 for f64.
707 // Set up the FP register classes.
708 addRegisterClass(MVT::f32, &X86::FR32RegClass);
709 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
711 // Use ANDPS to simulate FABS.
712 setOperationAction(ISD::FABS , MVT::f32, Custom);
714 // Use XORP to simulate FNEG.
715 setOperationAction(ISD::FNEG , MVT::f32, Custom);
717 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
719 // Use ANDPS and ORPS to simulate FCOPYSIGN.
720 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
721 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
723 // We don't support sin/cos/fmod
724 setOperationAction(ISD::FSIN , MVT::f32, Expand);
725 setOperationAction(ISD::FCOS , MVT::f32, Expand);
726 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
728 // Special cases we handle for FP constants.
729 addLegalFPImmediate(APFloat(+0.0f)); // xorps
730 addLegalFPImmediate(APFloat(+0.0)); // FLD0
731 addLegalFPImmediate(APFloat(+1.0)); // FLD1
732 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
735 if (!TM.Options.UnsafeFPMath) {
736 setOperationAction(ISD::FSIN , MVT::f64, Expand);
737 setOperationAction(ISD::FCOS , MVT::f64, Expand);
738 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
740 } else if (!TM.Options.UseSoftFloat) {
741 // f32 and f64 in x87.
742 // Set up the FP register classes.
743 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
744 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
746 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
747 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
748 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
749 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
751 if (!TM.Options.UnsafeFPMath) {
752 setOperationAction(ISD::FSIN , MVT::f64, Expand);
753 setOperationAction(ISD::FSIN , MVT::f32, Expand);
754 setOperationAction(ISD::FCOS , MVT::f64, Expand);
755 setOperationAction(ISD::FCOS , MVT::f32, Expand);
756 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
757 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
759 addLegalFPImmediate(APFloat(+0.0)); // FLD0
760 addLegalFPImmediate(APFloat(+1.0)); // FLD1
761 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
762 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
763 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
764 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
765 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
766 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
769 // We don't support FMA.
770 setOperationAction(ISD::FMA, MVT::f64, Expand);
771 setOperationAction(ISD::FMA, MVT::f32, Expand);
773 // Long double always uses X87.
774 if (!TM.Options.UseSoftFloat) {
775 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
776 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
777 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
779 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
780 addLegalFPImmediate(TmpFlt); // FLD0
782 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
785 APFloat TmpFlt2(+1.0);
786 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
788 addLegalFPImmediate(TmpFlt2); // FLD1
789 TmpFlt2.changeSign();
790 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
793 if (!TM.Options.UnsafeFPMath) {
794 setOperationAction(ISD::FSIN , MVT::f80, Expand);
795 setOperationAction(ISD::FCOS , MVT::f80, Expand);
796 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
799 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
800 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
801 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
802 setOperationAction(ISD::FRINT, MVT::f80, Expand);
803 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
804 setOperationAction(ISD::FMA, MVT::f80, Expand);
807 // Always use a library call for pow.
808 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
809 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
810 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
812 setOperationAction(ISD::FLOG, MVT::f80, Expand);
813 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
814 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
815 setOperationAction(ISD::FEXP, MVT::f80, Expand);
816 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
817 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
818 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
820 // First set operation action for all vector types to either promote
821 // (for widening) or expand (for scalarization). Then we will selectively
822 // turn on ones that can be effectively codegen'd.
823 for (MVT VT : MVT::vector_valuetypes()) {
824 setOperationAction(ISD::ADD , VT, Expand);
825 setOperationAction(ISD::SUB , VT, Expand);
826 setOperationAction(ISD::FADD, VT, Expand);
827 setOperationAction(ISD::FNEG, VT, Expand);
828 setOperationAction(ISD::FSUB, VT, Expand);
829 setOperationAction(ISD::MUL , VT, Expand);
830 setOperationAction(ISD::FMUL, VT, Expand);
831 setOperationAction(ISD::SDIV, VT, Expand);
832 setOperationAction(ISD::UDIV, VT, Expand);
833 setOperationAction(ISD::FDIV, VT, Expand);
834 setOperationAction(ISD::SREM, VT, Expand);
835 setOperationAction(ISD::UREM, VT, Expand);
836 setOperationAction(ISD::LOAD, VT, Expand);
837 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
839 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
840 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
841 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
842 setOperationAction(ISD::FABS, VT, Expand);
843 setOperationAction(ISD::FSIN, VT, Expand);
844 setOperationAction(ISD::FSINCOS, VT, Expand);
845 setOperationAction(ISD::FCOS, VT, Expand);
846 setOperationAction(ISD::FSINCOS, VT, Expand);
847 setOperationAction(ISD::FREM, VT, Expand);
848 setOperationAction(ISD::FMA, VT, Expand);
849 setOperationAction(ISD::FPOWI, VT, Expand);
850 setOperationAction(ISD::FSQRT, VT, Expand);
851 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
852 setOperationAction(ISD::FFLOOR, VT, Expand);
853 setOperationAction(ISD::FCEIL, VT, Expand);
854 setOperationAction(ISD::FTRUNC, VT, Expand);
855 setOperationAction(ISD::FRINT, VT, Expand);
856 setOperationAction(ISD::FNEARBYINT, VT, Expand);
857 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
858 setOperationAction(ISD::MULHS, VT, Expand);
859 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
860 setOperationAction(ISD::MULHU, VT, Expand);
861 setOperationAction(ISD::SDIVREM, VT, Expand);
862 setOperationAction(ISD::UDIVREM, VT, Expand);
863 setOperationAction(ISD::FPOW, VT, Expand);
864 setOperationAction(ISD::CTPOP, VT, Expand);
865 setOperationAction(ISD::CTTZ, VT, Expand);
866 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
867 setOperationAction(ISD::CTLZ, VT, Expand);
868 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
869 setOperationAction(ISD::SHL, VT, Expand);
870 setOperationAction(ISD::SRA, VT, Expand);
871 setOperationAction(ISD::SRL, VT, Expand);
872 setOperationAction(ISD::ROTL, VT, Expand);
873 setOperationAction(ISD::ROTR, VT, Expand);
874 setOperationAction(ISD::BSWAP, VT, Expand);
875 setOperationAction(ISD::SETCC, VT, Expand);
876 setOperationAction(ISD::FLOG, VT, Expand);
877 setOperationAction(ISD::FLOG2, VT, Expand);
878 setOperationAction(ISD::FLOG10, VT, Expand);
879 setOperationAction(ISD::FEXP, VT, Expand);
880 setOperationAction(ISD::FEXP2, VT, Expand);
881 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
882 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
883 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
884 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
885 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
886 setOperationAction(ISD::TRUNCATE, VT, Expand);
887 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
888 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
889 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
890 setOperationAction(ISD::VSELECT, VT, Expand);
891 setOperationAction(ISD::SELECT_CC, VT, Expand);
892 for (MVT InnerVT : MVT::vector_valuetypes()) {
893 setTruncStoreAction(InnerVT, VT, Expand);
895 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
896 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
898 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
899 // types, we have to deal with them whether we ask for Expansion or not.
900 // Setting Expand causes its own optimisation problems though, so leave
902 if (VT.getVectorElementType() == MVT::i1)
903 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
907 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
908 // with -msoft-float, disable use of MMX as well.
909 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
910 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
911 // No operations on x86mmx supported, everything uses intrinsics.
914 // MMX-sized vectors (other than x86mmx) are expected to be expanded
915 // into smaller operations.
916 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
917 setOperationAction(ISD::MULHS, MMXTy, Expand);
918 setOperationAction(ISD::AND, MMXTy, Expand);
919 setOperationAction(ISD::OR, MMXTy, Expand);
920 setOperationAction(ISD::XOR, MMXTy, Expand);
921 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
922 setOperationAction(ISD::SELECT, MMXTy, Expand);
923 setOperationAction(ISD::BITCAST, MMXTy, Expand);
925 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
928 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
930 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
931 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
932 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
933 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
934 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
935 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
936 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
937 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
938 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
939 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
940 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
942 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
943 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
946 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
947 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
949 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
950 // registers cannot be used even for integer operations.
951 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
952 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
953 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
954 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
956 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
957 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
958 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
959 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
960 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
961 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
962 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
963 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
964 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
965 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
966 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
967 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
968 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
969 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
970 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
971 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
972 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
973 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
974 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
975 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
976 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
977 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
979 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
980 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
981 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
982 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
984 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
985 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
990 // Only provide customized ctpop vector bit twiddling for vector types we
991 // know to perform better than using the popcnt instructions on each vector
992 // element. If popcnt isn't supported, always provide the custom version.
993 if (!Subtarget->hasPOPCNT()) {
994 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
995 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
998 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
999 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1000 MVT VT = (MVT::SimpleValueType)i;
1001 // Do not attempt to custom lower non-power-of-2 vectors
1002 if (!isPowerOf2_32(VT.getVectorNumElements()))
1004 // Do not attempt to custom lower non-128-bit vectors
1005 if (!VT.is128BitVector())
1007 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1008 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1009 setOperationAction(ISD::VSELECT, VT, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1013 // We support custom legalizing of sext and anyext loads for specific
1014 // memory vector types which we can load as a scalar (or sequence of
1015 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1016 // loads these must work with a single scalar load.
1017 for (MVT VT : MVT::integer_vector_valuetypes()) {
1018 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
1019 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
1020 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
1021 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
1022 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1029 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1031 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1033 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1034 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1035 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1036 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1038 if (Subtarget->is64Bit()) {
1039 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1040 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1043 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1044 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1045 MVT VT = (MVT::SimpleValueType)i;
1047 // Do not attempt to promote non-128-bit vectors
1048 if (!VT.is128BitVector())
1051 setOperationAction(ISD::AND, VT, Promote);
1052 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1053 setOperationAction(ISD::OR, VT, Promote);
1054 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1055 setOperationAction(ISD::XOR, VT, Promote);
1056 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1057 setOperationAction(ISD::LOAD, VT, Promote);
1058 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1059 setOperationAction(ISD::SELECT, VT, Promote);
1060 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1063 // Custom lower v2i64 and v2f64 selects.
1064 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1065 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1066 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1067 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1069 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1070 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1072 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1073 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1074 // As there is no 64-bit GPR available, we need build a special custom
1075 // sequence to convert from v2i32 to v2f32.
1076 if (!Subtarget->is64Bit())
1077 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1079 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1080 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1082 for (MVT VT : MVT::fp_vector_valuetypes())
1083 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1085 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1086 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1087 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1090 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1092 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1093 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1094 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1095 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1096 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
1099 // FIXME: Do we need to handle scalar-to-vector here?
1100 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1102 // We directly match byte blends in the backend as they match the VSELECT
1104 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1106 // SSE41 brings specific instructions for doing vector sign extend even in
1107 // cases where we don't have SRA.
1108 for (MVT VT : MVT::integer_vector_valuetypes()) {
1109 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1110 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1111 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1114 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1115 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1116 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1117 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1118 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1119 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1120 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1122 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1123 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1124 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1125 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1126 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1127 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1129 // i8 and i16 vectors are custom because the source register and source
1130 // source memory operand types are not the same width. f32 vectors are
1131 // custom since the immediate controlling the insert encodes additional
1133 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1134 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1135 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1138 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1139 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1140 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1141 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1143 // FIXME: these should be Legal, but that's only for the case where
1144 // the index is constant. For now custom expand to deal with that.
1145 if (Subtarget->is64Bit()) {
1146 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1147 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1151 if (Subtarget->hasSSE2()) {
1152 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1153 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1155 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1156 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1158 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1159 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1161 // In the customized shift lowering, the legal cases in AVX2 will be
1163 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1164 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1166 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1167 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1169 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1172 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1173 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1174 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1175 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1176 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1177 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1178 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1180 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1181 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1182 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1184 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1185 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1186 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1187 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1188 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1189 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1190 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1191 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1192 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1193 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1195 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1197 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1198 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1199 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1200 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1201 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1202 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1203 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1205 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1206 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1208 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1210 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1211 // even though v8i16 is a legal type.
1212 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1213 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1214 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1216 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1217 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1218 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1220 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1221 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1223 for (MVT VT : MVT::fp_vector_valuetypes())
1224 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1226 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1227 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1229 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1230 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1232 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1233 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1235 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1237 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1238 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1240 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1241 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1242 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1244 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1245 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1247 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1248 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1249 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1250 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1251 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1252 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1253 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1254 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1255 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1257 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1258 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1259 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1260 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1261 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1262 setOperationAction(ISD::FMA, MVT::f32, Legal);
1263 setOperationAction(ISD::FMA, MVT::f64, Legal);
1266 if (Subtarget->hasInt256()) {
1267 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1268 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1269 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1270 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1272 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1273 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1274 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1275 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1277 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1278 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1279 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1280 // Don't lower v32i8 because there is no 128-bit byte mul
1282 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1283 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1284 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1285 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1287 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1288 // when we have a 256bit-wide blend with immediate.
1289 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1291 // Only provide customized ctpop vector bit twiddling for vector types we
1292 // know to perform better than using the popcnt instructions on each
1293 // vector element. If popcnt isn't supported, always provide the custom
1295 if (!Subtarget->hasPOPCNT())
1296 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1298 // Custom CTPOP always performs better on natively supported v8i32
1299 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1301 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1302 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1303 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1304 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1305 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1306 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1307 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1309 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1310 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1311 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1312 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1313 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1314 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1316 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1317 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1318 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1319 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1321 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1322 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1323 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1324 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1326 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1327 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1328 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1329 // Don't lower v32i8 because there is no 128-bit byte mul
1332 // In the customized shift lowering, the legal cases in AVX2 will be
1334 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1335 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1337 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1338 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1340 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1342 // Custom lower several nodes for 256-bit types.
1343 for (MVT VT : MVT::vector_valuetypes()) {
1344 if (VT.getScalarSizeInBits() >= 32) {
1345 setOperationAction(ISD::MLOAD, VT, Legal);
1346 setOperationAction(ISD::MSTORE, VT, Legal);
1348 // Extract subvector is special because the value type
1349 // (result) is 128-bit but the source is 256-bit wide.
1350 if (VT.is128BitVector()) {
1351 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1353 // Do not attempt to custom lower other non-256-bit vectors
1354 if (!VT.is256BitVector())
1357 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1358 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1359 setOperationAction(ISD::VSELECT, VT, Custom);
1360 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1361 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1362 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1363 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1364 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1367 if (Subtarget->hasInt256())
1368 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1371 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1372 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1373 MVT VT = (MVT::SimpleValueType)i;
1375 // Do not attempt to promote non-256-bit vectors
1376 if (!VT.is256BitVector())
1379 setOperationAction(ISD::AND, VT, Promote);
1380 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1381 setOperationAction(ISD::OR, VT, Promote);
1382 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1383 setOperationAction(ISD::XOR, VT, Promote);
1384 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1385 setOperationAction(ISD::LOAD, VT, Promote);
1386 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1387 setOperationAction(ISD::SELECT, VT, Promote);
1388 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1392 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1393 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1394 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1395 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1396 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1398 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1399 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1400 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1402 for (MVT VT : MVT::fp_vector_valuetypes())
1403 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1405 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1406 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1407 setOperationAction(ISD::XOR, MVT::i1, Legal);
1408 setOperationAction(ISD::OR, MVT::i1, Legal);
1409 setOperationAction(ISD::AND, MVT::i1, Legal);
1410 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1411 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1412 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1413 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1414 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1416 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1417 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1418 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1419 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1420 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1421 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1423 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1424 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1425 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1426 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1427 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1428 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1429 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1430 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1432 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1433 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1434 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1435 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1436 if (Subtarget->is64Bit()) {
1437 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1438 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1439 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1440 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1442 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1443 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1444 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1445 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1446 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1447 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1448 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1449 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1450 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1451 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1452 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1453 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1454 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1455 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1457 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1458 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1459 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1460 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1461 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1462 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1463 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1464 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1465 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1466 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1467 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1468 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1469 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1471 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1472 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1473 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1474 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1475 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1476 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1477 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1478 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1479 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1480 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1482 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1483 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1484 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1485 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1486 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1488 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1489 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1491 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1493 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1494 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1495 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1496 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1497 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1498 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1499 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1500 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1501 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1503 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1504 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1506 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1507 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1509 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1511 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1512 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1514 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1515 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1517 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1518 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1520 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1521 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1522 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1523 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1524 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1525 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1527 if (Subtarget->hasCDI()) {
1528 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1529 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1532 // Custom lower several nodes.
1533 for (MVT VT : MVT::vector_valuetypes()) {
1534 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1535 // Extract subvector is special because the value type
1536 // (result) is 256/128-bit but the source is 512-bit wide.
1537 if (VT.is128BitVector() || VT.is256BitVector()) {
1538 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1540 if (VT.getVectorElementType() == MVT::i1)
1541 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1543 // Do not attempt to custom lower other non-512-bit vectors
1544 if (!VT.is512BitVector())
1547 if ( EltSize >= 32) {
1548 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1549 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1550 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1551 setOperationAction(ISD::VSELECT, VT, Legal);
1552 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1553 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1554 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1555 setOperationAction(ISD::MLOAD, VT, Legal);
1556 setOperationAction(ISD::MSTORE, VT, Legal);
1559 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1560 MVT VT = (MVT::SimpleValueType)i;
1562 // Do not attempt to promote non-512-bit vectors.
1563 if (!VT.is512BitVector())
1566 setOperationAction(ISD::SELECT, VT, Promote);
1567 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1571 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1572 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1573 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1575 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1576 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1578 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1579 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1580 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1581 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1582 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1583 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1584 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1585 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1586 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1587 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1588 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1589 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1590 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1592 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1593 const MVT VT = (MVT::SimpleValueType)i;
1595 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1597 // Do not attempt to promote non-512-bit vectors.
1598 if (!VT.is512BitVector())
1602 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1603 setOperationAction(ISD::VSELECT, VT, Legal);
1608 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1609 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1610 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1612 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1613 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1614 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1615 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1616 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1617 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1619 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1620 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1621 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1622 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1623 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1624 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1627 // We want to custom lower some of our intrinsics.
1628 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1629 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1630 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1631 if (!Subtarget->is64Bit())
1632 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1634 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1635 // handle type legalization for these operations here.
1637 // FIXME: We really should do custom legalization for addition and
1638 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1639 // than generic legalization for 64-bit multiplication-with-overflow, though.
1640 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1641 // Add/Sub/Mul with overflow operations are custom lowered.
1643 setOperationAction(ISD::SADDO, VT, Custom);
1644 setOperationAction(ISD::UADDO, VT, Custom);
1645 setOperationAction(ISD::SSUBO, VT, Custom);
1646 setOperationAction(ISD::USUBO, VT, Custom);
1647 setOperationAction(ISD::SMULO, VT, Custom);
1648 setOperationAction(ISD::UMULO, VT, Custom);
1652 if (!Subtarget->is64Bit()) {
1653 // These libcalls are not available in 32-bit.
1654 setLibcallName(RTLIB::SHL_I128, nullptr);
1655 setLibcallName(RTLIB::SRL_I128, nullptr);
1656 setLibcallName(RTLIB::SRA_I128, nullptr);
1659 // Combine sin / cos into one node or libcall if possible.
1660 if (Subtarget->hasSinCos()) {
1661 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1662 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1663 if (Subtarget->isTargetDarwin()) {
1664 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1665 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1666 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1667 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1671 if (Subtarget->isTargetWin64()) {
1672 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1673 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1674 setOperationAction(ISD::SREM, MVT::i128, Custom);
1675 setOperationAction(ISD::UREM, MVT::i128, Custom);
1676 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1677 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1680 // We have target-specific dag combine patterns for the following nodes:
1681 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1682 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1683 setTargetDAGCombine(ISD::BITCAST);
1684 setTargetDAGCombine(ISD::VSELECT);
1685 setTargetDAGCombine(ISD::SELECT);
1686 setTargetDAGCombine(ISD::SHL);
1687 setTargetDAGCombine(ISD::SRA);
1688 setTargetDAGCombine(ISD::SRL);
1689 setTargetDAGCombine(ISD::OR);
1690 setTargetDAGCombine(ISD::AND);
1691 setTargetDAGCombine(ISD::ADD);
1692 setTargetDAGCombine(ISD::FADD);
1693 setTargetDAGCombine(ISD::FSUB);
1694 setTargetDAGCombine(ISD::FMA);
1695 setTargetDAGCombine(ISD::SUB);
1696 setTargetDAGCombine(ISD::LOAD);
1697 setTargetDAGCombine(ISD::MLOAD);
1698 setTargetDAGCombine(ISD::STORE);
1699 setTargetDAGCombine(ISD::MSTORE);
1700 setTargetDAGCombine(ISD::ZERO_EXTEND);
1701 setTargetDAGCombine(ISD::ANY_EXTEND);
1702 setTargetDAGCombine(ISD::SIGN_EXTEND);
1703 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1704 setTargetDAGCombine(ISD::TRUNCATE);
1705 setTargetDAGCombine(ISD::SINT_TO_FP);
1706 setTargetDAGCombine(ISD::SETCC);
1707 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1708 setTargetDAGCombine(ISD::BUILD_VECTOR);
1709 setTargetDAGCombine(ISD::MUL);
1710 setTargetDAGCombine(ISD::XOR);
1712 computeRegisterProperties(Subtarget->getRegisterInfo());
1714 // On Darwin, -Os means optimize for size without hurting performance,
1715 // do not reduce the limit.
1716 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1717 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1718 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1719 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1720 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1721 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1722 setPrefLoopAlignment(4); // 2^4 bytes.
1724 // Predictable cmov don't hurt on atom because it's in-order.
1725 PredictableSelectIsExpensive = !Subtarget->isAtom();
1726 EnableExtLdPromotion = true;
1727 setPrefFunctionAlignment(4); // 2^4 bytes.
1729 verifyIntrinsicTables();
1732 // This has so far only been implemented for 64-bit MachO.
1733 bool X86TargetLowering::useLoadStackGuardNode() const {
1734 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1737 TargetLoweringBase::LegalizeTypeAction
1738 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1739 if (ExperimentalVectorWideningLegalization &&
1740 VT.getVectorNumElements() != 1 &&
1741 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1742 return TypeWidenVector;
1744 return TargetLoweringBase::getPreferredVectorAction(VT);
1747 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1749 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1751 const unsigned NumElts = VT.getVectorNumElements();
1752 const EVT EltVT = VT.getVectorElementType();
1753 if (VT.is512BitVector()) {
1754 if (Subtarget->hasAVX512())
1755 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1756 EltVT == MVT::f32 || EltVT == MVT::f64)
1758 case 8: return MVT::v8i1;
1759 case 16: return MVT::v16i1;
1761 if (Subtarget->hasBWI())
1762 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1764 case 32: return MVT::v32i1;
1765 case 64: return MVT::v64i1;
1769 if (VT.is256BitVector() || VT.is128BitVector()) {
1770 if (Subtarget->hasVLX())
1771 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1772 EltVT == MVT::f32 || EltVT == MVT::f64)
1774 case 2: return MVT::v2i1;
1775 case 4: return MVT::v4i1;
1776 case 8: return MVT::v8i1;
1778 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1779 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1781 case 8: return MVT::v8i1;
1782 case 16: return MVT::v16i1;
1783 case 32: return MVT::v32i1;
1787 return VT.changeVectorElementTypeToInteger();
1790 /// Helper for getByValTypeAlignment to determine
1791 /// the desired ByVal argument alignment.
1792 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1795 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1796 if (VTy->getBitWidth() == 128)
1798 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1799 unsigned EltAlign = 0;
1800 getMaxByValAlign(ATy->getElementType(), EltAlign);
1801 if (EltAlign > MaxAlign)
1802 MaxAlign = EltAlign;
1803 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1804 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1805 unsigned EltAlign = 0;
1806 getMaxByValAlign(STy->getElementType(i), EltAlign);
1807 if (EltAlign > MaxAlign)
1808 MaxAlign = EltAlign;
1815 /// Return the desired alignment for ByVal aggregate
1816 /// function arguments in the caller parameter area. For X86, aggregates
1817 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1818 /// are at 4-byte boundaries.
1819 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1820 if (Subtarget->is64Bit()) {
1821 // Max of 8 and alignment of type.
1822 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1829 if (Subtarget->hasSSE1())
1830 getMaxByValAlign(Ty, Align);
1834 /// Returns the target specific optimal type for load
1835 /// and store operations as a result of memset, memcpy, and memmove
1836 /// lowering. If DstAlign is zero that means it's safe to destination
1837 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1838 /// means there isn't a need to check it against alignment requirement,
1839 /// probably because the source does not need to be loaded. If 'IsMemset' is
1840 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1841 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1842 /// source is constant so it does not need to be loaded.
1843 /// It returns EVT::Other if the type should be determined using generic
1844 /// target-independent logic.
1846 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1847 unsigned DstAlign, unsigned SrcAlign,
1848 bool IsMemset, bool ZeroMemset,
1850 MachineFunction &MF) const {
1851 const Function *F = MF.getFunction();
1852 if ((!IsMemset || ZeroMemset) &&
1853 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1855 (Subtarget->isUnalignedMemAccessFast() ||
1856 ((DstAlign == 0 || DstAlign >= 16) &&
1857 (SrcAlign == 0 || SrcAlign >= 16)))) {
1859 if (Subtarget->hasInt256())
1861 if (Subtarget->hasFp256())
1864 if (Subtarget->hasSSE2())
1866 if (Subtarget->hasSSE1())
1868 } else if (!MemcpyStrSrc && Size >= 8 &&
1869 !Subtarget->is64Bit() &&
1870 Subtarget->hasSSE2()) {
1871 // Do not use f64 to lower memcpy if source is string constant. It's
1872 // better to use i32 to avoid the loads.
1876 if (Subtarget->is64Bit() && Size >= 8)
1881 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1883 return X86ScalarSSEf32;
1884 else if (VT == MVT::f64)
1885 return X86ScalarSSEf64;
1890 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1895 *Fast = Subtarget->isUnalignedMemAccessFast();
1899 /// Return the entry encoding for a jump table in the
1900 /// current function. The returned value is a member of the
1901 /// MachineJumpTableInfo::JTEntryKind enum.
1902 unsigned X86TargetLowering::getJumpTableEncoding() const {
1903 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1905 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1906 Subtarget->isPICStyleGOT())
1907 return MachineJumpTableInfo::EK_Custom32;
1909 // Otherwise, use the normal jump table encoding heuristics.
1910 return TargetLowering::getJumpTableEncoding();
1914 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1915 const MachineBasicBlock *MBB,
1916 unsigned uid,MCContext &Ctx) const{
1917 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1918 Subtarget->isPICStyleGOT());
1919 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1921 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1922 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1925 /// Returns relocation base for the given PIC jumptable.
1926 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1927 SelectionDAG &DAG) const {
1928 if (!Subtarget->is64Bit())
1929 // This doesn't have SDLoc associated with it, but is not really the
1930 // same as a Register.
1931 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1935 /// This returns the relocation base for the given PIC jumptable,
1936 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1937 const MCExpr *X86TargetLowering::
1938 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1939 MCContext &Ctx) const {
1940 // X86-64 uses RIP relative addressing based on the jump table label.
1941 if (Subtarget->isPICStyleRIPRel())
1942 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1944 // Otherwise, the reference is relative to the PIC base.
1945 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1948 std::pair<const TargetRegisterClass *, uint8_t>
1949 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1951 const TargetRegisterClass *RRC = nullptr;
1953 switch (VT.SimpleTy) {
1955 return TargetLowering::findRepresentativeClass(TRI, VT);
1956 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1957 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1960 RRC = &X86::VR64RegClass;
1962 case MVT::f32: case MVT::f64:
1963 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1964 case MVT::v4f32: case MVT::v2f64:
1965 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1967 RRC = &X86::VR128RegClass;
1970 return std::make_pair(RRC, Cost);
1973 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1974 unsigned &Offset) const {
1975 if (!Subtarget->isTargetLinux())
1978 if (Subtarget->is64Bit()) {
1979 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1981 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1993 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1994 unsigned DestAS) const {
1995 assert(SrcAS != DestAS && "Expected different address spaces!");
1997 return SrcAS < 256 && DestAS < 256;
2000 //===----------------------------------------------------------------------===//
2001 // Return Value Calling Convention Implementation
2002 //===----------------------------------------------------------------------===//
2004 #include "X86GenCallingConv.inc"
2007 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2008 MachineFunction &MF, bool isVarArg,
2009 const SmallVectorImpl<ISD::OutputArg> &Outs,
2010 LLVMContext &Context) const {
2011 SmallVector<CCValAssign, 16> RVLocs;
2012 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2013 return CCInfo.CheckReturn(Outs, RetCC_X86);
2016 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2017 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2022 X86TargetLowering::LowerReturn(SDValue Chain,
2023 CallingConv::ID CallConv, bool isVarArg,
2024 const SmallVectorImpl<ISD::OutputArg> &Outs,
2025 const SmallVectorImpl<SDValue> &OutVals,
2026 SDLoc dl, SelectionDAG &DAG) const {
2027 MachineFunction &MF = DAG.getMachineFunction();
2028 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2030 SmallVector<CCValAssign, 16> RVLocs;
2031 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2032 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2035 SmallVector<SDValue, 6> RetOps;
2036 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2037 // Operand #1 = Bytes To Pop
2038 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2041 // Copy the result values into the output registers.
2042 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2043 CCValAssign &VA = RVLocs[i];
2044 assert(VA.isRegLoc() && "Can only return in registers!");
2045 SDValue ValToCopy = OutVals[i];
2046 EVT ValVT = ValToCopy.getValueType();
2048 // Promote values to the appropriate types.
2049 if (VA.getLocInfo() == CCValAssign::SExt)
2050 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2051 else if (VA.getLocInfo() == CCValAssign::ZExt)
2052 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2053 else if (VA.getLocInfo() == CCValAssign::AExt)
2054 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2055 else if (VA.getLocInfo() == CCValAssign::BCvt)
2056 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2058 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2059 "Unexpected FP-extend for return value.");
2061 // If this is x86-64, and we disabled SSE, we can't return FP values,
2062 // or SSE or MMX vectors.
2063 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2064 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2065 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2066 report_fatal_error("SSE register return with SSE disabled");
2068 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2069 // llvm-gcc has never done it right and no one has noticed, so this
2070 // should be OK for now.
2071 if (ValVT == MVT::f64 &&
2072 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2073 report_fatal_error("SSE2 register return with SSE2 disabled");
2075 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2076 // the RET instruction and handled by the FP Stackifier.
2077 if (VA.getLocReg() == X86::FP0 ||
2078 VA.getLocReg() == X86::FP1) {
2079 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2080 // change the value to the FP stack register class.
2081 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2082 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2083 RetOps.push_back(ValToCopy);
2084 // Don't emit a copytoreg.
2088 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2089 // which is returned in RAX / RDX.
2090 if (Subtarget->is64Bit()) {
2091 if (ValVT == MVT::x86mmx) {
2092 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2093 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2094 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2096 // If we don't have SSE2 available, convert to v4f32 so the generated
2097 // register is legal.
2098 if (!Subtarget->hasSSE2())
2099 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2104 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2105 Flag = Chain.getValue(1);
2106 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2109 // The x86-64 ABIs require that for returning structs by value we copy
2110 // the sret argument into %rax/%eax (depending on ABI) for the return.
2111 // Win32 requires us to put the sret argument to %eax as well.
2112 // We saved the argument into a virtual register in the entry block,
2113 // so now we copy the value out and into %rax/%eax.
2115 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2116 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2117 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2118 // either case FuncInfo->setSRetReturnReg() will have been called.
2119 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2120 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2121 "No need for an sret register");
2122 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2125 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2126 X86::RAX : X86::EAX;
2127 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2128 Flag = Chain.getValue(1);
2130 // RAX/EAX now acts like a return value.
2131 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2134 RetOps[0] = Chain; // Update chain.
2136 // Add the flag if we have it.
2138 RetOps.push_back(Flag);
2140 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2143 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2144 if (N->getNumValues() != 1)
2146 if (!N->hasNUsesOfValue(1, 0))
2149 SDValue TCChain = Chain;
2150 SDNode *Copy = *N->use_begin();
2151 if (Copy->getOpcode() == ISD::CopyToReg) {
2152 // If the copy has a glue operand, we conservatively assume it isn't safe to
2153 // perform a tail call.
2154 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2156 TCChain = Copy->getOperand(0);
2157 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2160 bool HasRet = false;
2161 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2163 if (UI->getOpcode() != X86ISD::RET_FLAG)
2165 // If we are returning more than one value, we can definitely
2166 // not make a tail call see PR19530
2167 if (UI->getNumOperands() > 4)
2169 if (UI->getNumOperands() == 4 &&
2170 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2183 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2184 ISD::NodeType ExtendKind) const {
2186 // TODO: Is this also valid on 32-bit?
2187 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2188 ReturnMVT = MVT::i8;
2190 ReturnMVT = MVT::i32;
2192 EVT MinVT = getRegisterType(Context, ReturnMVT);
2193 return VT.bitsLT(MinVT) ? MinVT : VT;
2196 /// Lower the result values of a call into the
2197 /// appropriate copies out of appropriate physical registers.
2200 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2201 CallingConv::ID CallConv, bool isVarArg,
2202 const SmallVectorImpl<ISD::InputArg> &Ins,
2203 SDLoc dl, SelectionDAG &DAG,
2204 SmallVectorImpl<SDValue> &InVals) const {
2206 // Assign locations to each value returned by this call.
2207 SmallVector<CCValAssign, 16> RVLocs;
2208 bool Is64Bit = Subtarget->is64Bit();
2209 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2211 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2213 // Copy all of the result registers out of their specified physreg.
2214 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2215 CCValAssign &VA = RVLocs[i];
2216 EVT CopyVT = VA.getValVT();
2218 // If this is x86-64, and we disabled SSE, we can't return FP values
2219 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2220 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2221 report_fatal_error("SSE register return with SSE disabled");
2224 // If we prefer to use the value in xmm registers, copy it out as f80 and
2225 // use a truncate to move it from fp stack reg to xmm reg.
2226 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2227 isScalarFPTypeInSSEReg(VA.getValVT()))
2230 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2231 CopyVT, InFlag).getValue(1);
2232 SDValue Val = Chain.getValue(0);
2234 if (CopyVT != VA.getValVT())
2235 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2236 // This truncation won't change the value.
2237 DAG.getIntPtrConstant(1));
2239 InFlag = Chain.getValue(2);
2240 InVals.push_back(Val);
2246 //===----------------------------------------------------------------------===//
2247 // C & StdCall & Fast Calling Convention implementation
2248 //===----------------------------------------------------------------------===//
2249 // StdCall calling convention seems to be standard for many Windows' API
2250 // routines and around. It differs from C calling convention just a little:
2251 // callee should clean up the stack, not caller. Symbols should be also
2252 // decorated in some fancy way :) It doesn't support any vector arguments.
2253 // For info on fast calling convention see Fast Calling Convention (tail call)
2254 // implementation LowerX86_32FastCCCallTo.
2256 /// CallIsStructReturn - Determines whether a call uses struct return
2258 enum StructReturnType {
2263 static StructReturnType
2264 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2266 return NotStructReturn;
2268 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2269 if (!Flags.isSRet())
2270 return NotStructReturn;
2271 if (Flags.isInReg())
2272 return RegStructReturn;
2273 return StackStructReturn;
2276 /// Determines whether a function uses struct return semantics.
2277 static StructReturnType
2278 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2280 return NotStructReturn;
2282 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2283 if (!Flags.isSRet())
2284 return NotStructReturn;
2285 if (Flags.isInReg())
2286 return RegStructReturn;
2287 return StackStructReturn;
2290 /// Make a copy of an aggregate at address specified by "Src" to address
2291 /// "Dst" with size and alignment information specified by the specific
2292 /// parameter attribute. The copy will be passed as a byval function parameter.
2294 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2295 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2297 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2299 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2300 /*isVolatile*/false, /*AlwaysInline=*/true,
2301 MachinePointerInfo(), MachinePointerInfo());
2304 /// Return true if the calling convention is one that
2305 /// supports tail call optimization.
2306 static bool IsTailCallConvention(CallingConv::ID CC) {
2307 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2308 CC == CallingConv::HiPE);
2311 /// \brief Return true if the calling convention is a C calling convention.
2312 static bool IsCCallConvention(CallingConv::ID CC) {
2313 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2314 CC == CallingConv::X86_64_SysV);
2317 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2318 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2322 CallingConv::ID CalleeCC = CS.getCallingConv();
2323 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2329 /// Return true if the function is being made into
2330 /// a tailcall target by changing its ABI.
2331 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2332 bool GuaranteedTailCallOpt) {
2333 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2337 X86TargetLowering::LowerMemArgument(SDValue Chain,
2338 CallingConv::ID CallConv,
2339 const SmallVectorImpl<ISD::InputArg> &Ins,
2340 SDLoc dl, SelectionDAG &DAG,
2341 const CCValAssign &VA,
2342 MachineFrameInfo *MFI,
2344 // Create the nodes corresponding to a load from this parameter slot.
2345 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2346 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2347 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2348 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2351 // If value is passed by pointer we have address passed instead of the value
2353 if (VA.getLocInfo() == CCValAssign::Indirect)
2354 ValVT = VA.getLocVT();
2356 ValVT = VA.getValVT();
2358 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2359 // changed with more analysis.
2360 // In case of tail call optimization mark all arguments mutable. Since they
2361 // could be overwritten by lowering of arguments in case of a tail call.
2362 if (Flags.isByVal()) {
2363 unsigned Bytes = Flags.getByValSize();
2364 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2365 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2366 return DAG.getFrameIndex(FI, getPointerTy());
2368 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2369 VA.getLocMemOffset(), isImmutable);
2370 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2371 return DAG.getLoad(ValVT, dl, Chain, FIN,
2372 MachinePointerInfo::getFixedStack(FI),
2373 false, false, false, 0);
2377 // FIXME: Get this from tablegen.
2378 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2379 const X86Subtarget *Subtarget) {
2380 assert(Subtarget->is64Bit());
2382 if (Subtarget->isCallingConvWin64(CallConv)) {
2383 static const MCPhysReg GPR64ArgRegsWin64[] = {
2384 X86::RCX, X86::RDX, X86::R8, X86::R9
2386 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2389 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2390 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2392 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2395 // FIXME: Get this from tablegen.
2396 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2397 CallingConv::ID CallConv,
2398 const X86Subtarget *Subtarget) {
2399 assert(Subtarget->is64Bit());
2400 if (Subtarget->isCallingConvWin64(CallConv)) {
2401 // The XMM registers which might contain var arg parameters are shadowed
2402 // in their paired GPR. So we only need to save the GPR to their home
2404 // TODO: __vectorcall will change this.
2408 const Function *Fn = MF.getFunction();
2409 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2410 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2411 "SSE register cannot be used when SSE is disabled!");
2412 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2413 !Subtarget->hasSSE1())
2414 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2418 static const MCPhysReg XMMArgRegs64Bit[] = {
2419 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2420 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2422 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2426 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2427 CallingConv::ID CallConv,
2429 const SmallVectorImpl<ISD::InputArg> &Ins,
2432 SmallVectorImpl<SDValue> &InVals)
2434 MachineFunction &MF = DAG.getMachineFunction();
2435 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2437 const Function* Fn = MF.getFunction();
2438 if (Fn->hasExternalLinkage() &&
2439 Subtarget->isTargetCygMing() &&
2440 Fn->getName() == "main")
2441 FuncInfo->setForceFramePointer(true);
2443 MachineFrameInfo *MFI = MF.getFrameInfo();
2444 bool Is64Bit = Subtarget->is64Bit();
2445 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2447 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2448 "Var args not supported with calling convention fastcc, ghc or hipe");
2450 // Assign locations to all of the incoming arguments.
2451 SmallVector<CCValAssign, 16> ArgLocs;
2452 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2454 // Allocate shadow area for Win64
2456 CCInfo.AllocateStack(32, 8);
2458 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2460 unsigned LastVal = ~0U;
2462 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2463 CCValAssign &VA = ArgLocs[i];
2464 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2466 assert(VA.getValNo() != LastVal &&
2467 "Don't support value assigned to multiple locs yet");
2469 LastVal = VA.getValNo();
2471 if (VA.isRegLoc()) {
2472 EVT RegVT = VA.getLocVT();
2473 const TargetRegisterClass *RC;
2474 if (RegVT == MVT::i32)
2475 RC = &X86::GR32RegClass;
2476 else if (Is64Bit && RegVT == MVT::i64)
2477 RC = &X86::GR64RegClass;
2478 else if (RegVT == MVT::f32)
2479 RC = &X86::FR32RegClass;
2480 else if (RegVT == MVT::f64)
2481 RC = &X86::FR64RegClass;
2482 else if (RegVT.is512BitVector())
2483 RC = &X86::VR512RegClass;
2484 else if (RegVT.is256BitVector())
2485 RC = &X86::VR256RegClass;
2486 else if (RegVT.is128BitVector())
2487 RC = &X86::VR128RegClass;
2488 else if (RegVT == MVT::x86mmx)
2489 RC = &X86::VR64RegClass;
2490 else if (RegVT == MVT::i1)
2491 RC = &X86::VK1RegClass;
2492 else if (RegVT == MVT::v8i1)
2493 RC = &X86::VK8RegClass;
2494 else if (RegVT == MVT::v16i1)
2495 RC = &X86::VK16RegClass;
2496 else if (RegVT == MVT::v32i1)
2497 RC = &X86::VK32RegClass;
2498 else if (RegVT == MVT::v64i1)
2499 RC = &X86::VK64RegClass;
2501 llvm_unreachable("Unknown argument type!");
2503 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2504 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2506 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2507 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2509 if (VA.getLocInfo() == CCValAssign::SExt)
2510 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2511 DAG.getValueType(VA.getValVT()));
2512 else if (VA.getLocInfo() == CCValAssign::ZExt)
2513 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2514 DAG.getValueType(VA.getValVT()));
2515 else if (VA.getLocInfo() == CCValAssign::BCvt)
2516 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2518 if (VA.isExtInLoc()) {
2519 // Handle MMX values passed in XMM regs.
2520 if (RegVT.isVector())
2521 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2523 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2526 assert(VA.isMemLoc());
2527 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2530 // If value is passed via pointer - do a load.
2531 if (VA.getLocInfo() == CCValAssign::Indirect)
2532 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2533 MachinePointerInfo(), false, false, false, 0);
2535 InVals.push_back(ArgValue);
2538 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2539 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2540 // The x86-64 ABIs require that for returning structs by value we copy
2541 // the sret argument into %rax/%eax (depending on ABI) for the return.
2542 // Win32 requires us to put the sret argument to %eax as well.
2543 // Save the argument into a virtual register so that we can access it
2544 // from the return points.
2545 if (Ins[i].Flags.isSRet()) {
2546 unsigned Reg = FuncInfo->getSRetReturnReg();
2548 MVT PtrTy = getPointerTy();
2549 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2550 FuncInfo->setSRetReturnReg(Reg);
2552 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2553 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2559 unsigned StackSize = CCInfo.getNextStackOffset();
2560 // Align stack specially for tail calls.
2561 if (FuncIsMadeTailCallSafe(CallConv,
2562 MF.getTarget().Options.GuaranteedTailCallOpt))
2563 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2565 // If the function takes variable number of arguments, make a frame index for
2566 // the start of the first vararg value... for expansion of llvm.va_start. We
2567 // can skip this if there are no va_start calls.
2568 if (MFI->hasVAStart() &&
2569 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2570 CallConv != CallingConv::X86_ThisCall))) {
2571 FuncInfo->setVarArgsFrameIndex(
2572 MFI->CreateFixedObject(1, StackSize, true));
2575 // Figure out if XMM registers are in use.
2576 assert(!(MF.getTarget().Options.UseSoftFloat &&
2577 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2578 "SSE register cannot be used when SSE is disabled!");
2580 // 64-bit calling conventions support varargs and register parameters, so we
2581 // have to do extra work to spill them in the prologue.
2582 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2583 // Find the first unallocated argument registers.
2584 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2585 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2586 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2587 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2588 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2589 "SSE register cannot be used when SSE is disabled!");
2591 // Gather all the live in physical registers.
2592 SmallVector<SDValue, 6> LiveGPRs;
2593 SmallVector<SDValue, 8> LiveXMMRegs;
2595 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2596 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2598 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2600 if (!ArgXMMs.empty()) {
2601 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2602 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2603 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2604 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2605 LiveXMMRegs.push_back(
2606 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2611 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2612 // Get to the caller-allocated home save location. Add 8 to account
2613 // for the return address.
2614 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2615 FuncInfo->setRegSaveFrameIndex(
2616 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2617 // Fixup to set vararg frame on shadow area (4 x i64).
2619 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2621 // For X86-64, if there are vararg parameters that are passed via
2622 // registers, then we must store them to their spots on the stack so
2623 // they may be loaded by deferencing the result of va_next.
2624 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2625 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2626 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2627 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2630 // Store the integer parameter registers.
2631 SmallVector<SDValue, 8> MemOps;
2632 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2634 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2635 for (SDValue Val : LiveGPRs) {
2636 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2637 DAG.getIntPtrConstant(Offset));
2639 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2640 MachinePointerInfo::getFixedStack(
2641 FuncInfo->getRegSaveFrameIndex(), Offset),
2643 MemOps.push_back(Store);
2647 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2648 // Now store the XMM (fp + vector) parameter registers.
2649 SmallVector<SDValue, 12> SaveXMMOps;
2650 SaveXMMOps.push_back(Chain);
2651 SaveXMMOps.push_back(ALVal);
2652 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2653 FuncInfo->getRegSaveFrameIndex()));
2654 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2655 FuncInfo->getVarArgsFPOffset()));
2656 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2658 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2659 MVT::Other, SaveXMMOps));
2662 if (!MemOps.empty())
2663 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2666 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2667 // Find the largest legal vector type.
2668 MVT VecVT = MVT::Other;
2669 // FIXME: Only some x86_32 calling conventions support AVX512.
2670 if (Subtarget->hasAVX512() &&
2671 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2672 CallConv == CallingConv::Intel_OCL_BI)))
2673 VecVT = MVT::v16f32;
2674 else if (Subtarget->hasAVX())
2676 else if (Subtarget->hasSSE2())
2679 // We forward some GPRs and some vector types.
2680 SmallVector<MVT, 2> RegParmTypes;
2681 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2682 RegParmTypes.push_back(IntVT);
2683 if (VecVT != MVT::Other)
2684 RegParmTypes.push_back(VecVT);
2686 // Compute the set of forwarded registers. The rest are scratch.
2687 SmallVectorImpl<ForwardedRegister> &Forwards =
2688 FuncInfo->getForwardedMustTailRegParms();
2689 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2691 // Conservatively forward AL on x86_64, since it might be used for varargs.
2692 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2693 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2694 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2697 // Copy all forwards from physical to virtual registers.
2698 for (ForwardedRegister &F : Forwards) {
2699 // FIXME: Can we use a less constrained schedule?
2700 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2701 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2702 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2706 // Some CCs need callee pop.
2707 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2708 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2709 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2711 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2712 // If this is an sret function, the return should pop the hidden pointer.
2713 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2714 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2715 argsAreStructReturn(Ins) == StackStructReturn)
2716 FuncInfo->setBytesToPopOnReturn(4);
2720 // RegSaveFrameIndex is X86-64 only.
2721 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2722 if (CallConv == CallingConv::X86_FastCall ||
2723 CallConv == CallingConv::X86_ThisCall)
2724 // fastcc functions can't have varargs.
2725 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2728 FuncInfo->setArgumentStackSize(StackSize);
2734 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2735 SDValue StackPtr, SDValue Arg,
2736 SDLoc dl, SelectionDAG &DAG,
2737 const CCValAssign &VA,
2738 ISD::ArgFlagsTy Flags) const {
2739 unsigned LocMemOffset = VA.getLocMemOffset();
2740 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2741 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2742 if (Flags.isByVal())
2743 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2745 return DAG.getStore(Chain, dl, Arg, PtrOff,
2746 MachinePointerInfo::getStack(LocMemOffset),
2750 /// Emit a load of return address if tail call
2751 /// optimization is performed and it is required.
2753 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2754 SDValue &OutRetAddr, SDValue Chain,
2755 bool IsTailCall, bool Is64Bit,
2756 int FPDiff, SDLoc dl) const {
2757 // Adjust the Return address stack slot.
2758 EVT VT = getPointerTy();
2759 OutRetAddr = getReturnAddressFrameIndex(DAG);
2761 // Load the "old" Return address.
2762 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2763 false, false, false, 0);
2764 return SDValue(OutRetAddr.getNode(), 1);
2767 /// Emit a store of the return address if tail call
2768 /// optimization is performed and it is required (FPDiff!=0).
2769 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2770 SDValue Chain, SDValue RetAddrFrIdx,
2771 EVT PtrVT, unsigned SlotSize,
2772 int FPDiff, SDLoc dl) {
2773 // Store the return address to the appropriate stack slot.
2774 if (!FPDiff) return Chain;
2775 // Calculate the new stack slot for the return address.
2776 int NewReturnAddrFI =
2777 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2779 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2780 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2781 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2787 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2788 SmallVectorImpl<SDValue> &InVals) const {
2789 SelectionDAG &DAG = CLI.DAG;
2791 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2792 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2793 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2794 SDValue Chain = CLI.Chain;
2795 SDValue Callee = CLI.Callee;
2796 CallingConv::ID CallConv = CLI.CallConv;
2797 bool &isTailCall = CLI.IsTailCall;
2798 bool isVarArg = CLI.IsVarArg;
2800 MachineFunction &MF = DAG.getMachineFunction();
2801 bool Is64Bit = Subtarget->is64Bit();
2802 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2803 StructReturnType SR = callIsStructReturn(Outs);
2804 bool IsSibcall = false;
2805 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2807 if (MF.getTarget().Options.DisableTailCalls)
2810 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2812 // Force this to be a tail call. The verifier rules are enough to ensure
2813 // that we can lower this successfully without moving the return address
2816 } else if (isTailCall) {
2817 // Check if it's really possible to do a tail call.
2818 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2819 isVarArg, SR != NotStructReturn,
2820 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2821 Outs, OutVals, Ins, DAG);
2823 // Sibcalls are automatically detected tailcalls which do not require
2825 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2832 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2833 "Var args not supported with calling convention fastcc, ghc or hipe");
2835 // Analyze operands of the call, assigning locations to each operand.
2836 SmallVector<CCValAssign, 16> ArgLocs;
2837 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2839 // Allocate shadow area for Win64
2841 CCInfo.AllocateStack(32, 8);
2843 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2845 // Get a count of how many bytes are to be pushed on the stack.
2846 unsigned NumBytes = CCInfo.getNextStackOffset();
2848 // This is a sibcall. The memory operands are available in caller's
2849 // own caller's stack.
2851 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2852 IsTailCallConvention(CallConv))
2853 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2856 if (isTailCall && !IsSibcall && !IsMustTail) {
2857 // Lower arguments at fp - stackoffset + fpdiff.
2858 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2860 FPDiff = NumBytesCallerPushed - NumBytes;
2862 // Set the delta of movement of the returnaddr stackslot.
2863 // But only set if delta is greater than previous delta.
2864 if (FPDiff < X86Info->getTCReturnAddrDelta())
2865 X86Info->setTCReturnAddrDelta(FPDiff);
2868 unsigned NumBytesToPush = NumBytes;
2869 unsigned NumBytesToPop = NumBytes;
2871 // If we have an inalloca argument, all stack space has already been allocated
2872 // for us and be right at the top of the stack. We don't support multiple
2873 // arguments passed in memory when using inalloca.
2874 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2876 if (!ArgLocs.back().isMemLoc())
2877 report_fatal_error("cannot use inalloca attribute on a register "
2879 if (ArgLocs.back().getLocMemOffset() != 0)
2880 report_fatal_error("any parameter with the inalloca attribute must be "
2881 "the only memory argument");
2885 Chain = DAG.getCALLSEQ_START(
2886 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2888 SDValue RetAddrFrIdx;
2889 // Load return address for tail calls.
2890 if (isTailCall && FPDiff)
2891 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2892 Is64Bit, FPDiff, dl);
2894 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2895 SmallVector<SDValue, 8> MemOpChains;
2898 // Walk the register/memloc assignments, inserting copies/loads. In the case
2899 // of tail call optimization arguments are handle later.
2900 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2901 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2902 // Skip inalloca arguments, they have already been written.
2903 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2904 if (Flags.isInAlloca())
2907 CCValAssign &VA = ArgLocs[i];
2908 EVT RegVT = VA.getLocVT();
2909 SDValue Arg = OutVals[i];
2910 bool isByVal = Flags.isByVal();
2912 // Promote the value if needed.
2913 switch (VA.getLocInfo()) {
2914 default: llvm_unreachable("Unknown loc info!");
2915 case CCValAssign::Full: break;
2916 case CCValAssign::SExt:
2917 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2919 case CCValAssign::ZExt:
2920 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2922 case CCValAssign::AExt:
2923 if (RegVT.is128BitVector()) {
2924 // Special case: passing MMX values in XMM registers.
2925 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2926 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2927 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2929 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2931 case CCValAssign::BCvt:
2932 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2934 case CCValAssign::Indirect: {
2935 // Store the argument.
2936 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2937 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2938 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2939 MachinePointerInfo::getFixedStack(FI),
2946 if (VA.isRegLoc()) {
2947 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2948 if (isVarArg && IsWin64) {
2949 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2950 // shadow reg if callee is a varargs function.
2951 unsigned ShadowReg = 0;
2952 switch (VA.getLocReg()) {
2953 case X86::XMM0: ShadowReg = X86::RCX; break;
2954 case X86::XMM1: ShadowReg = X86::RDX; break;
2955 case X86::XMM2: ShadowReg = X86::R8; break;
2956 case X86::XMM3: ShadowReg = X86::R9; break;
2959 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2961 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2962 assert(VA.isMemLoc());
2963 if (!StackPtr.getNode())
2964 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2966 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2967 dl, DAG, VA, Flags));
2971 if (!MemOpChains.empty())
2972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2974 if (Subtarget->isPICStyleGOT()) {
2975 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2978 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2979 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2981 // If we are tail calling and generating PIC/GOT style code load the
2982 // address of the callee into ECX. The value in ecx is used as target of
2983 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2984 // for tail calls on PIC/GOT architectures. Normally we would just put the
2985 // address of GOT into ebx and then call target@PLT. But for tail calls
2986 // ebx would be restored (since ebx is callee saved) before jumping to the
2989 // Note: The actual moving to ECX is done further down.
2990 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2991 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2992 !G->getGlobal()->hasProtectedVisibility())
2993 Callee = LowerGlobalAddress(Callee, DAG);
2994 else if (isa<ExternalSymbolSDNode>(Callee))
2995 Callee = LowerExternalSymbol(Callee, DAG);
2999 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3000 // From AMD64 ABI document:
3001 // For calls that may call functions that use varargs or stdargs
3002 // (prototype-less calls or calls to functions containing ellipsis (...) in
3003 // the declaration) %al is used as hidden argument to specify the number
3004 // of SSE registers used. The contents of %al do not need to match exactly
3005 // the number of registers, but must be an ubound on the number of SSE
3006 // registers used and is in the range 0 - 8 inclusive.
3008 // Count the number of XMM registers allocated.
3009 static const MCPhysReg XMMArgRegs[] = {
3010 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3011 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3013 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3014 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3015 && "SSE registers cannot be used when SSE is disabled");
3017 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3018 DAG.getConstant(NumXMMRegs, MVT::i8)));
3021 if (isVarArg && IsMustTail) {
3022 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3023 for (const auto &F : Forwards) {
3024 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3025 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3029 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3030 // don't need this because the eligibility check rejects calls that require
3031 // shuffling arguments passed in memory.
3032 if (!IsSibcall && isTailCall) {
3033 // Force all the incoming stack arguments to be loaded from the stack
3034 // before any new outgoing arguments are stored to the stack, because the
3035 // outgoing stack slots may alias the incoming argument stack slots, and
3036 // the alias isn't otherwise explicit. This is slightly more conservative
3037 // than necessary, because it means that each store effectively depends
3038 // on every argument instead of just those arguments it would clobber.
3039 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3041 SmallVector<SDValue, 8> MemOpChains2;
3044 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3045 CCValAssign &VA = ArgLocs[i];
3048 assert(VA.isMemLoc());
3049 SDValue Arg = OutVals[i];
3050 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3051 // Skip inalloca arguments. They don't require any work.
3052 if (Flags.isInAlloca())
3054 // Create frame index.
3055 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3056 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3057 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3058 FIN = DAG.getFrameIndex(FI, getPointerTy());
3060 if (Flags.isByVal()) {
3061 // Copy relative to framepointer.
3062 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3063 if (!StackPtr.getNode())
3064 StackPtr = DAG.getCopyFromReg(Chain, dl,
3065 RegInfo->getStackRegister(),
3067 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3069 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3073 // Store relative to framepointer.
3074 MemOpChains2.push_back(
3075 DAG.getStore(ArgChain, dl, Arg, FIN,
3076 MachinePointerInfo::getFixedStack(FI),
3081 if (!MemOpChains2.empty())
3082 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3084 // Store the return address to the appropriate stack slot.
3085 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3086 getPointerTy(), RegInfo->getSlotSize(),
3090 // Build a sequence of copy-to-reg nodes chained together with token chain
3091 // and flag operands which copy the outgoing args into registers.
3093 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3094 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3095 RegsToPass[i].second, InFlag);
3096 InFlag = Chain.getValue(1);
3099 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3100 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3101 // In the 64-bit large code model, we have to make all calls
3102 // through a register, since the call instruction's 32-bit
3103 // pc-relative offset may not be large enough to hold the whole
3105 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3106 // If the callee is a GlobalAddress node (quite common, every direct call
3107 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3109 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3111 // We should use extra load for direct calls to dllimported functions in
3113 const GlobalValue *GV = G->getGlobal();
3114 if (!GV->hasDLLImportStorageClass()) {
3115 unsigned char OpFlags = 0;
3116 bool ExtraLoad = false;
3117 unsigned WrapperKind = ISD::DELETED_NODE;
3119 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3120 // external symbols most go through the PLT in PIC mode. If the symbol
3121 // has hidden or protected visibility, or if it is static or local, then
3122 // we don't need to use the PLT - we can directly call it.
3123 if (Subtarget->isTargetELF() &&
3124 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3125 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3126 OpFlags = X86II::MO_PLT;
3127 } else if (Subtarget->isPICStyleStubAny() &&
3128 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3129 (!Subtarget->getTargetTriple().isMacOSX() ||
3130 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3131 // PC-relative references to external symbols should go through $stub,
3132 // unless we're building with the leopard linker or later, which
3133 // automatically synthesizes these stubs.
3134 OpFlags = X86II::MO_DARWIN_STUB;
3135 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3136 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3137 // If the function is marked as non-lazy, generate an indirect call
3138 // which loads from the GOT directly. This avoids runtime overhead
3139 // at the cost of eager binding (and one extra byte of encoding).
3140 OpFlags = X86II::MO_GOTPCREL;
3141 WrapperKind = X86ISD::WrapperRIP;
3145 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3146 G->getOffset(), OpFlags);
3148 // Add a wrapper if needed.
3149 if (WrapperKind != ISD::DELETED_NODE)
3150 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3151 // Add extra indirection if needed.
3153 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3154 MachinePointerInfo::getGOT(),
3155 false, false, false, 0);
3157 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3158 unsigned char OpFlags = 0;
3160 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3161 // external symbols should go through the PLT.
3162 if (Subtarget->isTargetELF() &&
3163 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3164 OpFlags = X86II::MO_PLT;
3165 } else if (Subtarget->isPICStyleStubAny() &&
3166 (!Subtarget->getTargetTriple().isMacOSX() ||
3167 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3168 // PC-relative references to external symbols should go through $stub,
3169 // unless we're building with the leopard linker or later, which
3170 // automatically synthesizes these stubs.
3171 OpFlags = X86II::MO_DARWIN_STUB;
3174 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3176 } else if (Subtarget->isTarget64BitILP32() &&
3177 Callee->getValueType(0) == MVT::i32) {
3178 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3179 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3182 // Returns a chain & a flag for retval copy to use.
3183 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3184 SmallVector<SDValue, 8> Ops;
3186 if (!IsSibcall && isTailCall) {
3187 Chain = DAG.getCALLSEQ_END(Chain,
3188 DAG.getIntPtrConstant(NumBytesToPop, true),
3189 DAG.getIntPtrConstant(0, true), InFlag, dl);
3190 InFlag = Chain.getValue(1);
3193 Ops.push_back(Chain);
3194 Ops.push_back(Callee);
3197 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3199 // Add argument registers to the end of the list so that they are known live
3201 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3202 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3203 RegsToPass[i].second.getValueType()));
3205 // Add a register mask operand representing the call-preserved registers.
3206 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3207 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3208 assert(Mask && "Missing call preserved mask for calling convention");
3209 Ops.push_back(DAG.getRegisterMask(Mask));
3211 if (InFlag.getNode())
3212 Ops.push_back(InFlag);
3216 //// If this is the first return lowered for this function, add the regs
3217 //// to the liveout set for the function.
3218 // This isn't right, although it's probably harmless on x86; liveouts
3219 // should be computed from returns not tail calls. Consider a void
3220 // function making a tail call to a function returning int.
3221 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3224 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3225 InFlag = Chain.getValue(1);
3227 // Create the CALLSEQ_END node.
3228 unsigned NumBytesForCalleeToPop;
3229 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3230 DAG.getTarget().Options.GuaranteedTailCallOpt))
3231 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3232 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3233 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3234 SR == StackStructReturn)
3235 // If this is a call to a struct-return function, the callee
3236 // pops the hidden struct pointer, so we have to push it back.
3237 // This is common for Darwin/X86, Linux & Mingw32 targets.
3238 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3239 NumBytesForCalleeToPop = 4;
3241 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3243 // Returns a flag for retval copy to use.
3245 Chain = DAG.getCALLSEQ_END(Chain,
3246 DAG.getIntPtrConstant(NumBytesToPop, true),
3247 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3250 InFlag = Chain.getValue(1);
3253 // Handle result values, copying them out of physregs into vregs that we
3255 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3256 Ins, dl, DAG, InVals);
3259 //===----------------------------------------------------------------------===//
3260 // Fast Calling Convention (tail call) implementation
3261 //===----------------------------------------------------------------------===//
3263 // Like std call, callee cleans arguments, convention except that ECX is
3264 // reserved for storing the tail called function address. Only 2 registers are
3265 // free for argument passing (inreg). Tail call optimization is performed
3267 // * tailcallopt is enabled
3268 // * caller/callee are fastcc
3269 // On X86_64 architecture with GOT-style position independent code only local
3270 // (within module) calls are supported at the moment.
3271 // To keep the stack aligned according to platform abi the function
3272 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3273 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3274 // If a tail called function callee has more arguments than the caller the
3275 // caller needs to make sure that there is room to move the RETADDR to. This is
3276 // achieved by reserving an area the size of the argument delta right after the
3277 // original RETADDR, but before the saved framepointer or the spilled registers
3278 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3290 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3291 /// for a 16 byte align requirement.
3293 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3294 SelectionDAG& DAG) const {
3295 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3296 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3297 unsigned StackAlignment = TFI.getStackAlignment();
3298 uint64_t AlignMask = StackAlignment - 1;
3299 int64_t Offset = StackSize;
3300 unsigned SlotSize = RegInfo->getSlotSize();
3301 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3302 // Number smaller than 12 so just add the difference.
3303 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3305 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3306 Offset = ((~AlignMask) & Offset) + StackAlignment +
3307 (StackAlignment-SlotSize);
3312 /// MatchingStackOffset - Return true if the given stack call argument is
3313 /// already available in the same position (relatively) of the caller's
3314 /// incoming argument stack.
3316 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3317 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3318 const X86InstrInfo *TII) {
3319 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3321 if (Arg.getOpcode() == ISD::CopyFromReg) {
3322 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3323 if (!TargetRegisterInfo::isVirtualRegister(VR))
3325 MachineInstr *Def = MRI->getVRegDef(VR);
3328 if (!Flags.isByVal()) {
3329 if (!TII->isLoadFromStackSlot(Def, FI))
3332 unsigned Opcode = Def->getOpcode();
3333 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3334 Opcode == X86::LEA64_32r) &&
3335 Def->getOperand(1).isFI()) {
3336 FI = Def->getOperand(1).getIndex();
3337 Bytes = Flags.getByValSize();
3341 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3342 if (Flags.isByVal())
3343 // ByVal argument is passed in as a pointer but it's now being
3344 // dereferenced. e.g.
3345 // define @foo(%struct.X* %A) {
3346 // tail call @bar(%struct.X* byval %A)
3349 SDValue Ptr = Ld->getBasePtr();
3350 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3353 FI = FINode->getIndex();
3354 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3355 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3356 FI = FINode->getIndex();
3357 Bytes = Flags.getByValSize();
3361 assert(FI != INT_MAX);
3362 if (!MFI->isFixedObjectIndex(FI))
3364 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3367 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3368 /// for tail call optimization. Targets which want to do tail call
3369 /// optimization should implement this function.
3371 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3372 CallingConv::ID CalleeCC,
3374 bool isCalleeStructRet,
3375 bool isCallerStructRet,
3377 const SmallVectorImpl<ISD::OutputArg> &Outs,
3378 const SmallVectorImpl<SDValue> &OutVals,
3379 const SmallVectorImpl<ISD::InputArg> &Ins,
3380 SelectionDAG &DAG) const {
3381 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3384 // If -tailcallopt is specified, make fastcc functions tail-callable.
3385 const MachineFunction &MF = DAG.getMachineFunction();
3386 const Function *CallerF = MF.getFunction();
3388 // If the function return type is x86_fp80 and the callee return type is not,
3389 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3390 // perform a tailcall optimization here.
3391 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3394 CallingConv::ID CallerCC = CallerF->getCallingConv();
3395 bool CCMatch = CallerCC == CalleeCC;
3396 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3397 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3399 // Win64 functions have extra shadow space for argument homing. Don't do the
3400 // sibcall if the caller and callee have mismatched expectations for this
3402 if (IsCalleeWin64 != IsCallerWin64)
3405 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3406 if (IsTailCallConvention(CalleeCC) && CCMatch)
3411 // Look for obvious safe cases to perform tail call optimization that do not
3412 // require ABI changes. This is what gcc calls sibcall.
3414 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3415 // emit a special epilogue.
3416 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3417 if (RegInfo->needsStackRealignment(MF))
3420 // Also avoid sibcall optimization if either caller or callee uses struct
3421 // return semantics.
3422 if (isCalleeStructRet || isCallerStructRet)
3425 // An stdcall/thiscall caller is expected to clean up its arguments; the
3426 // callee isn't going to do that.
3427 // FIXME: this is more restrictive than needed. We could produce a tailcall
3428 // when the stack adjustment matches. For example, with a thiscall that takes
3429 // only one argument.
3430 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3431 CallerCC == CallingConv::X86_ThisCall))
3434 // Do not sibcall optimize vararg calls unless all arguments are passed via
3436 if (isVarArg && !Outs.empty()) {
3438 // Optimizing for varargs on Win64 is unlikely to be safe without
3439 // additional testing.
3440 if (IsCalleeWin64 || IsCallerWin64)
3443 SmallVector<CCValAssign, 16> ArgLocs;
3444 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3447 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3448 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3449 if (!ArgLocs[i].isRegLoc())
3453 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3454 // stack. Therefore, if it's not used by the call it is not safe to optimize
3455 // this into a sibcall.
3456 bool Unused = false;
3457 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3464 SmallVector<CCValAssign, 16> RVLocs;
3465 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3467 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3468 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3469 CCValAssign &VA = RVLocs[i];
3470 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3475 // If the calling conventions do not match, then we'd better make sure the
3476 // results are returned in the same way as what the caller expects.
3478 SmallVector<CCValAssign, 16> RVLocs1;
3479 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3481 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3483 SmallVector<CCValAssign, 16> RVLocs2;
3484 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3486 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3488 if (RVLocs1.size() != RVLocs2.size())
3490 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3491 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3493 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3495 if (RVLocs1[i].isRegLoc()) {
3496 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3499 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3505 // If the callee takes no arguments then go on to check the results of the
3507 if (!Outs.empty()) {
3508 // Check if stack adjustment is needed. For now, do not do this if any
3509 // argument is passed on the stack.
3510 SmallVector<CCValAssign, 16> ArgLocs;
3511 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3514 // Allocate shadow area for Win64
3516 CCInfo.AllocateStack(32, 8);
3518 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3519 if (CCInfo.getNextStackOffset()) {
3520 MachineFunction &MF = DAG.getMachineFunction();
3521 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3524 // Check if the arguments are already laid out in the right way as
3525 // the caller's fixed stack objects.
3526 MachineFrameInfo *MFI = MF.getFrameInfo();
3527 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3528 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3529 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3530 CCValAssign &VA = ArgLocs[i];
3531 SDValue Arg = OutVals[i];
3532 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3533 if (VA.getLocInfo() == CCValAssign::Indirect)
3535 if (!VA.isRegLoc()) {
3536 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3543 // If the tailcall address may be in a register, then make sure it's
3544 // possible to register allocate for it. In 32-bit, the call address can
3545 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3546 // callee-saved registers are restored. These happen to be the same
3547 // registers used to pass 'inreg' arguments so watch out for those.
3548 if (!Subtarget->is64Bit() &&
3549 ((!isa<GlobalAddressSDNode>(Callee) &&
3550 !isa<ExternalSymbolSDNode>(Callee)) ||
3551 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3552 unsigned NumInRegs = 0;
3553 // In PIC we need an extra register to formulate the address computation
3555 unsigned MaxInRegs =
3556 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3558 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3559 CCValAssign &VA = ArgLocs[i];
3562 unsigned Reg = VA.getLocReg();
3565 case X86::EAX: case X86::EDX: case X86::ECX:
3566 if (++NumInRegs == MaxInRegs)
3578 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3579 const TargetLibraryInfo *libInfo) const {
3580 return X86::createFastISel(funcInfo, libInfo);
3583 //===----------------------------------------------------------------------===//
3584 // Other Lowering Hooks
3585 //===----------------------------------------------------------------------===//
3587 static bool MayFoldLoad(SDValue Op) {
3588 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3591 static bool MayFoldIntoStore(SDValue Op) {
3592 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3595 static bool isTargetShuffle(unsigned Opcode) {
3597 default: return false;
3598 case X86ISD::BLENDI:
3599 case X86ISD::PSHUFB:
3600 case X86ISD::PSHUFD:
3601 case X86ISD::PSHUFHW:
3602 case X86ISD::PSHUFLW:
3604 case X86ISD::PALIGNR:
3605 case X86ISD::MOVLHPS:
3606 case X86ISD::MOVLHPD:
3607 case X86ISD::MOVHLPS:
3608 case X86ISD::MOVLPS:
3609 case X86ISD::MOVLPD:
3610 case X86ISD::MOVSHDUP:
3611 case X86ISD::MOVSLDUP:
3612 case X86ISD::MOVDDUP:
3615 case X86ISD::UNPCKL:
3616 case X86ISD::UNPCKH:
3617 case X86ISD::VPERMILPI:
3618 case X86ISD::VPERM2X128:
3619 case X86ISD::VPERMI:
3624 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3625 SDValue V1, unsigned TargetMask,
3626 SelectionDAG &DAG) {
3628 default: llvm_unreachable("Unknown x86 shuffle node");
3629 case X86ISD::PSHUFD:
3630 case X86ISD::PSHUFHW:
3631 case X86ISD::PSHUFLW:
3632 case X86ISD::VPERMILPI:
3633 case X86ISD::VPERMI:
3634 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3638 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3639 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3641 default: llvm_unreachable("Unknown x86 shuffle node");
3642 case X86ISD::MOVLHPS:
3643 case X86ISD::MOVLHPD:
3644 case X86ISD::MOVHLPS:
3645 case X86ISD::MOVLPS:
3646 case X86ISD::MOVLPD:
3649 case X86ISD::UNPCKL:
3650 case X86ISD::UNPCKH:
3651 return DAG.getNode(Opc, dl, VT, V1, V2);
3655 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3656 MachineFunction &MF = DAG.getMachineFunction();
3657 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3658 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3659 int ReturnAddrIndex = FuncInfo->getRAIndex();
3661 if (ReturnAddrIndex == 0) {
3662 // Set up a frame object for the return address.
3663 unsigned SlotSize = RegInfo->getSlotSize();
3664 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3667 FuncInfo->setRAIndex(ReturnAddrIndex);
3670 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3673 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3674 bool hasSymbolicDisplacement) {
3675 // Offset should fit into 32 bit immediate field.
3676 if (!isInt<32>(Offset))
3679 // If we don't have a symbolic displacement - we don't have any extra
3681 if (!hasSymbolicDisplacement)
3684 // FIXME: Some tweaks might be needed for medium code model.
3685 if (M != CodeModel::Small && M != CodeModel::Kernel)
3688 // For small code model we assume that latest object is 16MB before end of 31
3689 // bits boundary. We may also accept pretty large negative constants knowing
3690 // that all objects are in the positive half of address space.
3691 if (M == CodeModel::Small && Offset < 16*1024*1024)
3694 // For kernel code model we know that all object resist in the negative half
3695 // of 32bits address space. We may not accept negative offsets, since they may
3696 // be just off and we may accept pretty large positive ones.
3697 if (M == CodeModel::Kernel && Offset >= 0)
3703 /// isCalleePop - Determines whether the callee is required to pop its
3704 /// own arguments. Callee pop is necessary to support tail calls.
3705 bool X86::isCalleePop(CallingConv::ID CallingConv,
3706 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3707 switch (CallingConv) {
3710 case CallingConv::X86_StdCall:
3711 case CallingConv::X86_FastCall:
3712 case CallingConv::X86_ThisCall:
3714 case CallingConv::Fast:
3715 case CallingConv::GHC:
3716 case CallingConv::HiPE:
3723 /// \brief Return true if the condition is an unsigned comparison operation.
3724 static bool isX86CCUnsigned(unsigned X86CC) {
3726 default: llvm_unreachable("Invalid integer condition!");
3727 case X86::COND_E: return true;
3728 case X86::COND_G: return false;
3729 case X86::COND_GE: return false;
3730 case X86::COND_L: return false;
3731 case X86::COND_LE: return false;
3732 case X86::COND_NE: return true;
3733 case X86::COND_B: return true;
3734 case X86::COND_A: return true;
3735 case X86::COND_BE: return true;
3736 case X86::COND_AE: return true;
3738 llvm_unreachable("covered switch fell through?!");
3741 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3742 /// specific condition code, returning the condition code and the LHS/RHS of the
3743 /// comparison to make.
3744 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3745 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3747 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3748 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3749 // X > -1 -> X == 0, jump !sign.
3750 RHS = DAG.getConstant(0, RHS.getValueType());
3751 return X86::COND_NS;
3753 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3754 // X < 0 -> X == 0, jump on sign.
3757 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3759 RHS = DAG.getConstant(0, RHS.getValueType());
3760 return X86::COND_LE;
3764 switch (SetCCOpcode) {
3765 default: llvm_unreachable("Invalid integer condition!");
3766 case ISD::SETEQ: return X86::COND_E;
3767 case ISD::SETGT: return X86::COND_G;
3768 case ISD::SETGE: return X86::COND_GE;
3769 case ISD::SETLT: return X86::COND_L;
3770 case ISD::SETLE: return X86::COND_LE;
3771 case ISD::SETNE: return X86::COND_NE;
3772 case ISD::SETULT: return X86::COND_B;
3773 case ISD::SETUGT: return X86::COND_A;
3774 case ISD::SETULE: return X86::COND_BE;
3775 case ISD::SETUGE: return X86::COND_AE;
3779 // First determine if it is required or is profitable to flip the operands.
3781 // If LHS is a foldable load, but RHS is not, flip the condition.
3782 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3783 !ISD::isNON_EXTLoad(RHS.getNode())) {
3784 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3785 std::swap(LHS, RHS);
3788 switch (SetCCOpcode) {
3794 std::swap(LHS, RHS);
3798 // On a floating point condition, the flags are set as follows:
3800 // 0 | 0 | 0 | X > Y
3801 // 0 | 0 | 1 | X < Y
3802 // 1 | 0 | 0 | X == Y
3803 // 1 | 1 | 1 | unordered
3804 switch (SetCCOpcode) {
3805 default: llvm_unreachable("Condcode should be pre-legalized away");
3807 case ISD::SETEQ: return X86::COND_E;
3808 case ISD::SETOLT: // flipped
3810 case ISD::SETGT: return X86::COND_A;
3811 case ISD::SETOLE: // flipped
3813 case ISD::SETGE: return X86::COND_AE;
3814 case ISD::SETUGT: // flipped
3816 case ISD::SETLT: return X86::COND_B;
3817 case ISD::SETUGE: // flipped
3819 case ISD::SETLE: return X86::COND_BE;
3821 case ISD::SETNE: return X86::COND_NE;
3822 case ISD::SETUO: return X86::COND_P;
3823 case ISD::SETO: return X86::COND_NP;
3825 case ISD::SETUNE: return X86::COND_INVALID;
3829 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3830 /// code. Current x86 isa includes the following FP cmov instructions:
3831 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3832 static bool hasFPCMov(unsigned X86CC) {
3848 /// isFPImmLegal - Returns true if the target can instruction select the
3849 /// specified FP immediate natively. If false, the legalizer will
3850 /// materialize the FP immediate as a load from a constant pool.
3851 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3852 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3853 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3859 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3860 ISD::LoadExtType ExtTy,
3862 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3863 // relocation target a movq or addq instruction: don't let the load shrink.
3864 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3865 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3866 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3867 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3871 /// \brief Returns true if it is beneficial to convert a load of a constant
3872 /// to just the constant itself.
3873 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3875 assert(Ty->isIntegerTy());
3877 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3878 if (BitSize == 0 || BitSize > 64)
3883 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3884 unsigned Index) const {
3885 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3888 return (Index == 0 || Index == ResVT.getVectorNumElements());
3891 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3892 // Speculate cttz only if we can directly use TZCNT.
3893 return Subtarget->hasBMI();
3896 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3897 // Speculate ctlz only if we can directly use LZCNT.
3898 return Subtarget->hasLZCNT();
3901 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3902 /// the specified range (L, H].
3903 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3904 return (Val < 0) || (Val >= Low && Val < Hi);
3907 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3908 /// specified value.
3909 static bool isUndefOrEqual(int Val, int CmpVal) {
3910 return (Val < 0 || Val == CmpVal);
3913 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3914 /// from position Pos and ending in Pos+Size, falls within the specified
3915 /// sequential range (Low, Low+Size]. or is undef.
3916 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3917 unsigned Pos, unsigned Size, int Low) {
3918 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3919 if (!isUndefOrEqual(Mask[i], Low))
3924 /// isVEXTRACTIndex - Return true if the specified
3925 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3926 /// suitable for instruction that extract 128 or 256 bit vectors
3927 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3928 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3929 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3932 // The index should be aligned on a vecWidth-bit boundary.
3934 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3936 MVT VT = N->getSimpleValueType(0);
3937 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3938 bool Result = (Index * ElSize) % vecWidth == 0;
3943 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3944 /// operand specifies a subvector insert that is suitable for input to
3945 /// insertion of 128 or 256-bit subvectors
3946 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3947 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3948 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3950 // The index should be aligned on a vecWidth-bit boundary.
3952 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3954 MVT VT = N->getSimpleValueType(0);
3955 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3956 bool Result = (Index * ElSize) % vecWidth == 0;
3961 bool X86::isVINSERT128Index(SDNode *N) {
3962 return isVINSERTIndex(N, 128);
3965 bool X86::isVINSERT256Index(SDNode *N) {
3966 return isVINSERTIndex(N, 256);
3969 bool X86::isVEXTRACT128Index(SDNode *N) {
3970 return isVEXTRACTIndex(N, 128);
3973 bool X86::isVEXTRACT256Index(SDNode *N) {
3974 return isVEXTRACTIndex(N, 256);
3977 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3978 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3979 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3980 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3983 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3985 MVT VecVT = N->getOperand(0).getSimpleValueType();
3986 MVT ElVT = VecVT.getVectorElementType();
3988 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3989 return Index / NumElemsPerChunk;
3992 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3993 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3994 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3995 llvm_unreachable("Illegal insert subvector for VINSERT");
3998 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4000 MVT VecVT = N->getSimpleValueType(0);
4001 MVT ElVT = VecVT.getVectorElementType();
4003 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4004 return Index / NumElemsPerChunk;
4007 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4008 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4009 /// and VINSERTI128 instructions.
4010 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4011 return getExtractVEXTRACTImmediate(N, 128);
4014 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4015 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4016 /// and VINSERTI64x4 instructions.
4017 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4018 return getExtractVEXTRACTImmediate(N, 256);
4021 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4022 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4023 /// and VINSERTI128 instructions.
4024 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4025 return getInsertVINSERTImmediate(N, 128);
4028 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4029 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4030 /// and VINSERTI64x4 instructions.
4031 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4032 return getInsertVINSERTImmediate(N, 256);
4035 /// isZero - Returns true if Elt is a constant integer zero
4036 static bool isZero(SDValue V) {
4037 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4038 return C && C->isNullValue();
4041 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4043 bool X86::isZeroNode(SDValue Elt) {
4046 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4047 return CFP->getValueAPF().isPosZero();
4051 /// getZeroVector - Returns a vector of specified type with all zero elements.
4053 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4054 SelectionDAG &DAG, SDLoc dl) {
4055 assert(VT.isVector() && "Expected a vector type");
4057 // Always build SSE zero vectors as <4 x i32> bitcasted
4058 // to their dest type. This ensures they get CSE'd.
4060 if (VT.is128BitVector()) { // SSE
4061 if (Subtarget->hasSSE2()) { // SSE2
4062 SDValue Cst = DAG.getConstant(0, MVT::i32);
4063 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4065 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4066 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4068 } else if (VT.is256BitVector()) { // AVX
4069 if (Subtarget->hasInt256()) { // AVX2
4070 SDValue Cst = DAG.getConstant(0, MVT::i32);
4071 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4072 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4074 // 256-bit logic and arithmetic instructions in AVX are all
4075 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4076 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4077 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4078 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4080 } else if (VT.is512BitVector()) { // AVX-512
4081 SDValue Cst = DAG.getConstant(0, MVT::i32);
4082 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4083 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4084 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4085 } else if (VT.getScalarType() == MVT::i1) {
4087 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4088 && "Unexpected vector type");
4089 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4090 && "Unexpected vector type");
4091 SDValue Cst = DAG.getConstant(0, MVT::i1);
4092 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4093 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4095 llvm_unreachable("Unexpected vector type");
4097 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4100 /// getOnesVector - Returns a vector of specified type with all bits set.
4101 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4102 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4103 /// Then bitcast to their original type, ensuring they get CSE'd.
4104 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4106 assert(VT.isVector() && "Expected a vector type");
4108 SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4110 if (VT.is256BitVector()) {
4111 if (HasInt256) { // AVX2
4112 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4113 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4115 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4116 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4118 } else if (VT.is128BitVector()) {
4119 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4121 llvm_unreachable("Unexpected vector type");
4123 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4126 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4127 /// operation of specified width.
4128 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4130 unsigned NumElems = VT.getVectorNumElements();
4131 SmallVector<int, 8> Mask;
4132 Mask.push_back(NumElems);
4133 for (unsigned i = 1; i != NumElems; ++i)
4135 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4138 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4139 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4141 unsigned NumElems = VT.getVectorNumElements();
4142 SmallVector<int, 8> Mask;
4143 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4145 Mask.push_back(i + NumElems);
4147 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4150 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4151 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4153 unsigned NumElems = VT.getVectorNumElements();
4154 SmallVector<int, 8> Mask;
4155 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4156 Mask.push_back(i + Half);
4157 Mask.push_back(i + NumElems + Half);
4159 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4162 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4163 /// vector of zero or undef vector. This produces a shuffle where the low
4164 /// element of V2 is swizzled into the zero/undef vector, landing at element
4165 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4166 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4168 const X86Subtarget *Subtarget,
4169 SelectionDAG &DAG) {
4170 MVT VT = V2.getSimpleValueType();
4172 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4173 unsigned NumElems = VT.getVectorNumElements();
4174 SmallVector<int, 16> MaskVec;
4175 for (unsigned i = 0; i != NumElems; ++i)
4176 // If this is the insertion idx, put the low elt of V2 here.
4177 MaskVec.push_back(i == Idx ? NumElems : i);
4178 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4181 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4182 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4183 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4184 /// shuffles which use a single input multiple times, and in those cases it will
4185 /// adjust the mask to only have indices within that single input.
4186 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4187 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4188 unsigned NumElems = VT.getVectorNumElements();
4192 bool IsFakeUnary = false;
4193 switch(N->getOpcode()) {
4194 case X86ISD::BLENDI:
4195 ImmN = N->getOperand(N->getNumOperands()-1);
4196 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4199 ImmN = N->getOperand(N->getNumOperands()-1);
4200 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4201 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4203 case X86ISD::UNPCKH:
4204 DecodeUNPCKHMask(VT, Mask);
4205 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4207 case X86ISD::UNPCKL:
4208 DecodeUNPCKLMask(VT, Mask);
4209 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4211 case X86ISD::MOVHLPS:
4212 DecodeMOVHLPSMask(NumElems, Mask);
4213 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4215 case X86ISD::MOVLHPS:
4216 DecodeMOVLHPSMask(NumElems, Mask);
4217 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4219 case X86ISD::PALIGNR:
4220 ImmN = N->getOperand(N->getNumOperands()-1);
4221 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4223 case X86ISD::PSHUFD:
4224 case X86ISD::VPERMILPI:
4225 ImmN = N->getOperand(N->getNumOperands()-1);
4226 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4229 case X86ISD::PSHUFHW:
4230 ImmN = N->getOperand(N->getNumOperands()-1);
4231 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4234 case X86ISD::PSHUFLW:
4235 ImmN = N->getOperand(N->getNumOperands()-1);
4236 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4239 case X86ISD::PSHUFB: {
4241 SDValue MaskNode = N->getOperand(1);
4242 while (MaskNode->getOpcode() == ISD::BITCAST)
4243 MaskNode = MaskNode->getOperand(0);
4245 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4246 // If we have a build-vector, then things are easy.
4247 EVT VT = MaskNode.getValueType();
4248 assert(VT.isVector() &&
4249 "Can't produce a non-vector with a build_vector!");
4250 if (!VT.isInteger())
4253 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4255 SmallVector<uint64_t, 32> RawMask;
4256 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4257 SDValue Op = MaskNode->getOperand(i);
4258 if (Op->getOpcode() == ISD::UNDEF) {
4259 RawMask.push_back((uint64_t)SM_SentinelUndef);
4262 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4265 APInt MaskElement = CN->getAPIntValue();
4267 // We now have to decode the element which could be any integer size and
4268 // extract each byte of it.
4269 for (int j = 0; j < NumBytesPerElement; ++j) {
4270 // Note that this is x86 and so always little endian: the low byte is
4271 // the first byte of the mask.
4272 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4273 MaskElement = MaskElement.lshr(8);
4276 DecodePSHUFBMask(RawMask, Mask);
4280 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4284 SDValue Ptr = MaskLoad->getBasePtr();
4285 if (Ptr->getOpcode() == X86ISD::Wrapper)
4286 Ptr = Ptr->getOperand(0);
4288 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4289 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4292 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4293 DecodePSHUFBMask(C, Mask);
4301 case X86ISD::VPERMI:
4302 ImmN = N->getOperand(N->getNumOperands()-1);
4303 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4310 case X86ISD::VPERM2X128:
4311 ImmN = N->getOperand(N->getNumOperands()-1);
4312 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4313 if (Mask.empty()) return false;
4315 case X86ISD::MOVSLDUP:
4316 DecodeMOVSLDUPMask(VT, Mask);
4319 case X86ISD::MOVSHDUP:
4320 DecodeMOVSHDUPMask(VT, Mask);
4323 case X86ISD::MOVDDUP:
4324 DecodeMOVDDUPMask(VT, Mask);
4327 case X86ISD::MOVLHPD:
4328 case X86ISD::MOVLPD:
4329 case X86ISD::MOVLPS:
4330 // Not yet implemented
4332 default: llvm_unreachable("unknown target shuffle node");
4335 // If we have a fake unary shuffle, the shuffle mask is spread across two
4336 // inputs that are actually the same node. Re-map the mask to always point
4337 // into the first input.
4340 if (M >= (int)Mask.size())
4346 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4347 /// element of the result of the vector shuffle.
4348 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4351 return SDValue(); // Limit search depth.
4353 SDValue V = SDValue(N, 0);
4354 EVT VT = V.getValueType();
4355 unsigned Opcode = V.getOpcode();
4357 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4358 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4359 int Elt = SV->getMaskElt(Index);
4362 return DAG.getUNDEF(VT.getVectorElementType());
4364 unsigned NumElems = VT.getVectorNumElements();
4365 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4366 : SV->getOperand(1);
4367 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4370 // Recurse into target specific vector shuffles to find scalars.
4371 if (isTargetShuffle(Opcode)) {
4372 MVT ShufVT = V.getSimpleValueType();
4373 unsigned NumElems = ShufVT.getVectorNumElements();
4374 SmallVector<int, 16> ShuffleMask;
4377 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4380 int Elt = ShuffleMask[Index];
4382 return DAG.getUNDEF(ShufVT.getVectorElementType());
4384 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4386 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4390 // Actual nodes that may contain scalar elements
4391 if (Opcode == ISD::BITCAST) {
4392 V = V.getOperand(0);
4393 EVT SrcVT = V.getValueType();
4394 unsigned NumElems = VT.getVectorNumElements();
4396 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4400 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4401 return (Index == 0) ? V.getOperand(0)
4402 : DAG.getUNDEF(VT.getVectorElementType());
4404 if (V.getOpcode() == ISD::BUILD_VECTOR)
4405 return V.getOperand(Index);
4410 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4412 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4413 unsigned NumNonZero, unsigned NumZero,
4415 const X86Subtarget* Subtarget,
4416 const TargetLowering &TLI) {
4423 for (unsigned i = 0; i < 16; ++i) {
4424 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4425 if (ThisIsNonZero && First) {
4427 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4429 V = DAG.getUNDEF(MVT::v8i16);
4434 SDValue ThisElt, LastElt;
4435 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4436 if (LastIsNonZero) {
4437 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4438 MVT::i16, Op.getOperand(i-1));
4440 if (ThisIsNonZero) {
4441 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4442 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4443 ThisElt, DAG.getConstant(8, MVT::i8));
4445 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4449 if (ThisElt.getNode())
4450 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4451 DAG.getIntPtrConstant(i/2));
4455 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4458 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4460 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4461 unsigned NumNonZero, unsigned NumZero,
4463 const X86Subtarget* Subtarget,
4464 const TargetLowering &TLI) {
4471 for (unsigned i = 0; i < 8; ++i) {
4472 bool isNonZero = (NonZeros & (1 << i)) != 0;
4476 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4478 V = DAG.getUNDEF(MVT::v8i16);
4481 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4482 MVT::v8i16, V, Op.getOperand(i),
4483 DAG.getIntPtrConstant(i));
4490 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4491 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4492 const X86Subtarget *Subtarget,
4493 const TargetLowering &TLI) {
4494 // Find all zeroable elements.
4495 std::bitset<4> Zeroable;
4496 for (int i=0; i < 4; ++i) {
4497 SDValue Elt = Op->getOperand(i);
4498 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4500 assert(Zeroable.size() - Zeroable.count() > 1 &&
4501 "We expect at least two non-zero elements!");
4503 // We only know how to deal with build_vector nodes where elements are either
4504 // zeroable or extract_vector_elt with constant index.
4505 SDValue FirstNonZero;
4506 unsigned FirstNonZeroIdx;
4507 for (unsigned i=0; i < 4; ++i) {
4510 SDValue Elt = Op->getOperand(i);
4511 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4512 !isa<ConstantSDNode>(Elt.getOperand(1)))
4514 // Make sure that this node is extracting from a 128-bit vector.
4515 MVT VT = Elt.getOperand(0).getSimpleValueType();
4516 if (!VT.is128BitVector())
4518 if (!FirstNonZero.getNode()) {
4520 FirstNonZeroIdx = i;
4524 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4525 SDValue V1 = FirstNonZero.getOperand(0);
4526 MVT VT = V1.getSimpleValueType();
4528 // See if this build_vector can be lowered as a blend with zero.
4530 unsigned EltMaskIdx, EltIdx;
4532 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4533 if (Zeroable[EltIdx]) {
4534 // The zero vector will be on the right hand side.
4535 Mask[EltIdx] = EltIdx+4;
4539 Elt = Op->getOperand(EltIdx);
4540 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4541 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4542 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4544 Mask[EltIdx] = EltIdx;
4548 // Let the shuffle legalizer deal with blend operations.
4549 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4550 if (V1.getSimpleValueType() != VT)
4551 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4552 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4555 // See if we can lower this build_vector to a INSERTPS.
4556 if (!Subtarget->hasSSE41())
4559 SDValue V2 = Elt.getOperand(0);
4560 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4563 bool CanFold = true;
4564 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4568 SDValue Current = Op->getOperand(i);
4569 SDValue SrcVector = Current->getOperand(0);
4572 CanFold = SrcVector == V1 &&
4573 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4579 assert(V1.getNode() && "Expected at least two non-zero elements!");
4580 if (V1.getSimpleValueType() != MVT::v4f32)
4581 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4582 if (V2.getSimpleValueType() != MVT::v4f32)
4583 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4585 // Ok, we can emit an INSERTPS instruction.
4586 unsigned ZMask = Zeroable.to_ulong();
4588 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4589 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4590 SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4591 DAG.getIntPtrConstant(InsertPSMask));
4592 return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4595 /// Return a vector logical shift node.
4596 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4597 unsigned NumBits, SelectionDAG &DAG,
4598 const TargetLowering &TLI, SDLoc dl) {
4599 assert(VT.is128BitVector() && "Unknown type for VShift");
4600 MVT ShVT = MVT::v2i64;
4601 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4602 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4603 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4604 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4605 SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4606 return DAG.getNode(ISD::BITCAST, dl, VT,
4607 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4611 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4613 // Check if the scalar load can be widened into a vector load. And if
4614 // the address is "base + cst" see if the cst can be "absorbed" into
4615 // the shuffle mask.
4616 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4617 SDValue Ptr = LD->getBasePtr();
4618 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4620 EVT PVT = LD->getValueType(0);
4621 if (PVT != MVT::i32 && PVT != MVT::f32)
4626 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4627 FI = FINode->getIndex();
4629 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4630 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4631 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4632 Offset = Ptr.getConstantOperandVal(1);
4633 Ptr = Ptr.getOperand(0);
4638 // FIXME: 256-bit vector instructions don't require a strict alignment,
4639 // improve this code to support it better.
4640 unsigned RequiredAlign = VT.getSizeInBits()/8;
4641 SDValue Chain = LD->getChain();
4642 // Make sure the stack object alignment is at least 16 or 32.
4643 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4644 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4645 if (MFI->isFixedObjectIndex(FI)) {
4646 // Can't change the alignment. FIXME: It's possible to compute
4647 // the exact stack offset and reference FI + adjust offset instead.
4648 // If someone *really* cares about this. That's the way to implement it.
4651 MFI->setObjectAlignment(FI, RequiredAlign);
4655 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4656 // Ptr + (Offset & ~15).
4659 if ((Offset % RequiredAlign) & 3)
4661 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4663 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4664 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4666 int EltNo = (Offset - StartOffset) >> 2;
4667 unsigned NumElems = VT.getVectorNumElements();
4669 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4670 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4671 LD->getPointerInfo().getWithOffset(StartOffset),
4672 false, false, false, 0);
4674 SmallVector<int, 8> Mask(NumElems, EltNo);
4676 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4682 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4683 /// elements can be replaced by a single large load which has the same value as
4684 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4686 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4688 /// FIXME: we'd also like to handle the case where the last elements are zero
4689 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4690 /// There's even a handy isZeroNode for that purpose.
4691 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4692 SDLoc &DL, SelectionDAG &DAG,
4693 bool isAfterLegalize) {
4694 unsigned NumElems = Elts.size();
4696 LoadSDNode *LDBase = nullptr;
4697 unsigned LastLoadedElt = -1U;
4699 // For each element in the initializer, see if we've found a load or an undef.
4700 // If we don't find an initial load element, or later load elements are
4701 // non-consecutive, bail out.
4702 for (unsigned i = 0; i < NumElems; ++i) {
4703 SDValue Elt = Elts[i];
4704 // Look through a bitcast.
4705 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4706 Elt = Elt.getOperand(0);
4707 if (!Elt.getNode() ||
4708 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4711 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4713 LDBase = cast<LoadSDNode>(Elt.getNode());
4717 if (Elt.getOpcode() == ISD::UNDEF)
4720 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4721 EVT LdVT = Elt.getValueType();
4722 // Each loaded element must be the correct fractional portion of the
4723 // requested vector load.
4724 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4726 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4731 // If we have found an entire vector of loads and undefs, then return a large
4732 // load of the entire vector width starting at the base pointer. If we found
4733 // consecutive loads for the low half, generate a vzext_load node.
4734 if (LastLoadedElt == NumElems - 1) {
4735 assert(LDBase && "Did not find base load for merging consecutive loads");
4736 EVT EltVT = LDBase->getValueType(0);
4737 // Ensure that the input vector size for the merged loads matches the
4738 // cumulative size of the input elements.
4739 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4742 if (isAfterLegalize &&
4743 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4746 SDValue NewLd = SDValue();
4748 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4749 LDBase->getPointerInfo(), LDBase->isVolatile(),
4750 LDBase->isNonTemporal(), LDBase->isInvariant(),
4751 LDBase->getAlignment());
4753 if (LDBase->hasAnyUseOfValue(1)) {
4754 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4756 SDValue(NewLd.getNode(), 1));
4757 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4758 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4759 SDValue(NewLd.getNode(), 1));
4765 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4766 //of a v4i32 / v4f32. It's probably worth generalizing.
4767 EVT EltVT = VT.getVectorElementType();
4768 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4769 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4770 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4771 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4773 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4774 LDBase->getPointerInfo(),
4775 LDBase->getAlignment(),
4776 false/*isVolatile*/, true/*ReadMem*/,
4779 // Make sure the newly-created LOAD is in the same position as LDBase in
4780 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4781 // update uses of LDBase's output chain to use the TokenFactor.
4782 if (LDBase->hasAnyUseOfValue(1)) {
4783 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4784 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4785 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4786 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4787 SDValue(ResNode.getNode(), 1));
4790 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4795 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4796 /// to generate a splat value for the following cases:
4797 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4798 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4799 /// a scalar load, or a constant.
4800 /// The VBROADCAST node is returned when a pattern is found,
4801 /// or SDValue() otherwise.
4802 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4803 SelectionDAG &DAG) {
4804 // VBROADCAST requires AVX.
4805 // TODO: Splats could be generated for non-AVX CPUs using SSE
4806 // instructions, but there's less potential gain for only 128-bit vectors.
4807 if (!Subtarget->hasAVX())
4810 MVT VT = Op.getSimpleValueType();
4813 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4814 "Unsupported vector type for broadcast.");
4819 switch (Op.getOpcode()) {
4821 // Unknown pattern found.
4824 case ISD::BUILD_VECTOR: {
4825 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4826 BitVector UndefElements;
4827 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4829 // We need a splat of a single value to use broadcast, and it doesn't
4830 // make any sense if the value is only in one element of the vector.
4831 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4835 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4836 Ld.getOpcode() == ISD::ConstantFP);
4838 // Make sure that all of the users of a non-constant load are from the
4839 // BUILD_VECTOR node.
4840 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4845 case ISD::VECTOR_SHUFFLE: {
4846 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4848 // Shuffles must have a splat mask where the first element is
4850 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4853 SDValue Sc = Op.getOperand(0);
4854 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4855 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4857 if (!Subtarget->hasInt256())
4860 // Use the register form of the broadcast instruction available on AVX2.
4861 if (VT.getSizeInBits() >= 256)
4862 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4863 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4866 Ld = Sc.getOperand(0);
4867 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4868 Ld.getOpcode() == ISD::ConstantFP);
4870 // The scalar_to_vector node and the suspected
4871 // load node must have exactly one user.
4872 // Constants may have multiple users.
4874 // AVX-512 has register version of the broadcast
4875 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4876 Ld.getValueType().getSizeInBits() >= 32;
4877 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4884 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4885 bool IsGE256 = (VT.getSizeInBits() >= 256);
4887 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4888 // instruction to save 8 or more bytes of constant pool data.
4889 // TODO: If multiple splats are generated to load the same constant,
4890 // it may be detrimental to overall size. There needs to be a way to detect
4891 // that condition to know if this is truly a size win.
4892 const Function *F = DAG.getMachineFunction().getFunction();
4893 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4895 // Handle broadcasting a single constant scalar from the constant pool
4897 // On Sandybridge (no AVX2), it is still better to load a constant vector
4898 // from the constant pool and not to broadcast it from a scalar.
4899 // But override that restriction when optimizing for size.
4900 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4901 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4902 EVT CVT = Ld.getValueType();
4903 assert(!CVT.isVector() && "Must not broadcast a vector type");
4905 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4906 // For size optimization, also splat v2f64 and v2i64, and for size opt
4907 // with AVX2, also splat i8 and i16.
4908 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4909 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4910 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4911 const Constant *C = nullptr;
4912 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4913 C = CI->getConstantIntValue();
4914 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4915 C = CF->getConstantFPValue();
4917 assert(C && "Invalid constant type");
4919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4920 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4921 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4922 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4923 MachinePointerInfo::getConstantPool(),
4924 false, false, false, Alignment);
4926 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4930 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4932 // Handle AVX2 in-register broadcasts.
4933 if (!IsLoad && Subtarget->hasInt256() &&
4934 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4935 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4937 // The scalar source must be a normal load.
4941 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4942 (Subtarget->hasVLX() && ScalarSize == 64))
4943 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4945 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4946 // double since there is no vbroadcastsd xmm
4947 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4948 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4949 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4952 // Unsupported broadcast.
4956 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4957 /// underlying vector and index.
4959 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4961 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4963 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4964 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4967 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4969 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4971 // (extract_vector_elt (vector_shuffle<2,u,u,u>
4972 // (extract_subvector (v8f32 %vreg0), Constant<4>),
4975 // In this case the vector is the extract_subvector expression and the index
4976 // is 2, as specified by the shuffle.
4977 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4978 SDValue ShuffleVec = SVOp->getOperand(0);
4979 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4980 assert(ShuffleVecVT.getVectorElementType() ==
4981 ExtractedFromVec.getSimpleValueType().getVectorElementType());
4983 int ShuffleIdx = SVOp->getMaskElt(Idx);
4984 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4985 ExtractedFromVec = ShuffleVec;
4991 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4992 MVT VT = Op.getSimpleValueType();
4994 // Skip if insert_vec_elt is not supported.
4995 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4996 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5000 unsigned NumElems = Op.getNumOperands();
5004 SmallVector<unsigned, 4> InsertIndices;
5005 SmallVector<int, 8> Mask(NumElems, -1);
5007 for (unsigned i = 0; i != NumElems; ++i) {
5008 unsigned Opc = Op.getOperand(i).getOpcode();
5010 if (Opc == ISD::UNDEF)
5013 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5014 // Quit if more than 1 elements need inserting.
5015 if (InsertIndices.size() > 1)
5018 InsertIndices.push_back(i);
5022 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5023 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5024 // Quit if non-constant index.
5025 if (!isa<ConstantSDNode>(ExtIdx))
5027 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5029 // Quit if extracted from vector of different type.
5030 if (ExtractedFromVec.getValueType() != VT)
5033 if (!VecIn1.getNode())
5034 VecIn1 = ExtractedFromVec;
5035 else if (VecIn1 != ExtractedFromVec) {
5036 if (!VecIn2.getNode())
5037 VecIn2 = ExtractedFromVec;
5038 else if (VecIn2 != ExtractedFromVec)
5039 // Quit if more than 2 vectors to shuffle
5043 if (ExtractedFromVec == VecIn1)
5045 else if (ExtractedFromVec == VecIn2)
5046 Mask[i] = Idx + NumElems;
5049 if (!VecIn1.getNode())
5052 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5053 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5054 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5055 unsigned Idx = InsertIndices[i];
5056 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5057 DAG.getIntPtrConstant(Idx));
5063 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5065 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5067 MVT VT = Op.getSimpleValueType();
5068 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5069 "Unexpected type in LowerBUILD_VECTORvXi1!");
5072 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5073 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5074 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5075 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5078 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5079 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5080 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5081 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5084 bool AllContants = true;
5085 uint64_t Immediate = 0;
5086 int NonConstIdx = -1;
5087 bool IsSplat = true;
5088 unsigned NumNonConsts = 0;
5089 unsigned NumConsts = 0;
5090 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5091 SDValue In = Op.getOperand(idx);
5092 if (In.getOpcode() == ISD::UNDEF)
5094 if (!isa<ConstantSDNode>(In)) {
5095 AllContants = false;
5100 if (cast<ConstantSDNode>(In)->getZExtValue())
5101 Immediate |= (1ULL << idx);
5103 if (In != Op.getOperand(0))
5108 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5109 DAG.getConstant(Immediate, MVT::i16));
5110 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5111 DAG.getIntPtrConstant(0));
5114 if (NumNonConsts == 1 && NonConstIdx != 0) {
5117 SDValue VecAsImm = DAG.getConstant(Immediate,
5118 MVT::getIntegerVT(VT.getSizeInBits()));
5119 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5122 DstVec = DAG.getUNDEF(VT);
5123 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5124 Op.getOperand(NonConstIdx),
5125 DAG.getIntPtrConstant(NonConstIdx));
5127 if (!IsSplat && (NonConstIdx != 0))
5128 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5129 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5132 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5133 DAG.getConstant(-1, SelectVT),
5134 DAG.getConstant(0, SelectVT));
5136 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5137 DAG.getConstant((Immediate | 1), SelectVT),
5138 DAG.getConstant(Immediate, SelectVT));
5139 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5142 /// \brief Return true if \p N implements a horizontal binop and return the
5143 /// operands for the horizontal binop into V0 and V1.
5145 /// This is a helper function of PerformBUILD_VECTORCombine.
5146 /// This function checks that the build_vector \p N in input implements a
5147 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5148 /// operation to match.
5149 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5150 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5151 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5154 /// This function only analyzes elements of \p N whose indices are
5155 /// in range [BaseIdx, LastIdx).
5156 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5158 unsigned BaseIdx, unsigned LastIdx,
5159 SDValue &V0, SDValue &V1) {
5160 EVT VT = N->getValueType(0);
5162 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5163 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5164 "Invalid Vector in input!");
5166 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5167 bool CanFold = true;
5168 unsigned ExpectedVExtractIdx = BaseIdx;
5169 unsigned NumElts = LastIdx - BaseIdx;
5170 V0 = DAG.getUNDEF(VT);
5171 V1 = DAG.getUNDEF(VT);
5173 // Check if N implements a horizontal binop.
5174 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5175 SDValue Op = N->getOperand(i + BaseIdx);
5178 if (Op->getOpcode() == ISD::UNDEF) {
5179 // Update the expected vector extract index.
5180 if (i * 2 == NumElts)
5181 ExpectedVExtractIdx = BaseIdx;
5182 ExpectedVExtractIdx += 2;
5186 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5191 SDValue Op0 = Op.getOperand(0);
5192 SDValue Op1 = Op.getOperand(1);
5194 // Try to match the following pattern:
5195 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5196 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5197 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5198 Op0.getOperand(0) == Op1.getOperand(0) &&
5199 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5200 isa<ConstantSDNode>(Op1.getOperand(1)));
5204 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5205 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5207 if (i * 2 < NumElts) {
5208 if (V0.getOpcode() == ISD::UNDEF)
5209 V0 = Op0.getOperand(0);
5211 if (V1.getOpcode() == ISD::UNDEF)
5212 V1 = Op0.getOperand(0);
5213 if (i * 2 == NumElts)
5214 ExpectedVExtractIdx = BaseIdx;
5217 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5218 if (I0 == ExpectedVExtractIdx)
5219 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5220 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5221 // Try to match the following dag sequence:
5222 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5223 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5227 ExpectedVExtractIdx += 2;
5233 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5234 /// a concat_vector.
5236 /// This is a helper function of PerformBUILD_VECTORCombine.
5237 /// This function expects two 256-bit vectors called V0 and V1.
5238 /// At first, each vector is split into two separate 128-bit vectors.
5239 /// Then, the resulting 128-bit vectors are used to implement two
5240 /// horizontal binary operations.
5242 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5244 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5245 /// the two new horizontal binop.
5246 /// When Mode is set, the first horizontal binop dag node would take as input
5247 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5248 /// horizontal binop dag node would take as input the lower 128-bit of V1
5249 /// and the upper 128-bit of V1.
5251 /// HADD V0_LO, V0_HI
5252 /// HADD V1_LO, V1_HI
5254 /// Otherwise, the first horizontal binop dag node takes as input the lower
5255 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5256 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5258 /// HADD V0_LO, V1_LO
5259 /// HADD V0_HI, V1_HI
5261 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5262 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5263 /// the upper 128-bits of the result.
5264 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5265 SDLoc DL, SelectionDAG &DAG,
5266 unsigned X86Opcode, bool Mode,
5267 bool isUndefLO, bool isUndefHI) {
5268 EVT VT = V0.getValueType();
5269 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5270 "Invalid nodes in input!");
5272 unsigned NumElts = VT.getVectorNumElements();
5273 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5274 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5275 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5276 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5277 EVT NewVT = V0_LO.getValueType();
5279 SDValue LO = DAG.getUNDEF(NewVT);
5280 SDValue HI = DAG.getUNDEF(NewVT);
5283 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5284 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5285 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5286 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5287 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5289 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5290 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5291 V1_LO->getOpcode() != ISD::UNDEF))
5292 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5294 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5295 V1_HI->getOpcode() != ISD::UNDEF))
5296 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5299 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5302 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5303 /// sequence of 'vadd + vsub + blendi'.
5304 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5305 const X86Subtarget *Subtarget) {
5307 EVT VT = BV->getValueType(0);
5308 unsigned NumElts = VT.getVectorNumElements();
5309 SDValue InVec0 = DAG.getUNDEF(VT);
5310 SDValue InVec1 = DAG.getUNDEF(VT);
5312 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5313 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5315 // Odd-numbered elements in the input build vector are obtained from
5316 // adding two integer/float elements.
5317 // Even-numbered elements in the input build vector are obtained from
5318 // subtracting two integer/float elements.
5319 unsigned ExpectedOpcode = ISD::FSUB;
5320 unsigned NextExpectedOpcode = ISD::FADD;
5321 bool AddFound = false;
5322 bool SubFound = false;
5324 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5325 SDValue Op = BV->getOperand(i);
5327 // Skip 'undef' values.
5328 unsigned Opcode = Op.getOpcode();
5329 if (Opcode == ISD::UNDEF) {
5330 std::swap(ExpectedOpcode, NextExpectedOpcode);
5334 // Early exit if we found an unexpected opcode.
5335 if (Opcode != ExpectedOpcode)
5338 SDValue Op0 = Op.getOperand(0);
5339 SDValue Op1 = Op.getOperand(1);
5341 // Try to match the following pattern:
5342 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5343 // Early exit if we cannot match that sequence.
5344 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5345 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5346 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5347 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5348 Op0.getOperand(1) != Op1.getOperand(1))
5351 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5355 // We found a valid add/sub node. Update the information accordingly.
5361 // Update InVec0 and InVec1.
5362 if (InVec0.getOpcode() == ISD::UNDEF)
5363 InVec0 = Op0.getOperand(0);
5364 if (InVec1.getOpcode() == ISD::UNDEF)
5365 InVec1 = Op1.getOperand(0);
5367 // Make sure that operands in input to each add/sub node always
5368 // come from a same pair of vectors.
5369 if (InVec0 != Op0.getOperand(0)) {
5370 if (ExpectedOpcode == ISD::FSUB)
5373 // FADD is commutable. Try to commute the operands
5374 // and then test again.
5375 std::swap(Op0, Op1);
5376 if (InVec0 != Op0.getOperand(0))
5380 if (InVec1 != Op1.getOperand(0))
5383 // Update the pair of expected opcodes.
5384 std::swap(ExpectedOpcode, NextExpectedOpcode);
5387 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5388 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5389 InVec1.getOpcode() != ISD::UNDEF)
5390 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5395 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5396 const X86Subtarget *Subtarget) {
5398 EVT VT = N->getValueType(0);
5399 unsigned NumElts = VT.getVectorNumElements();
5400 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5401 SDValue InVec0, InVec1;
5403 // Try to match an ADDSUB.
5404 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5405 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5406 SDValue Value = matchAddSub(BV, DAG, Subtarget);
5407 if (Value.getNode())
5411 // Try to match horizontal ADD/SUB.
5412 unsigned NumUndefsLO = 0;
5413 unsigned NumUndefsHI = 0;
5414 unsigned Half = NumElts/2;
5416 // Count the number of UNDEF operands in the build_vector in input.
5417 for (unsigned i = 0, e = Half; i != e; ++i)
5418 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5421 for (unsigned i = Half, e = NumElts; i != e; ++i)
5422 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5425 // Early exit if this is either a build_vector of all UNDEFs or all the
5426 // operands but one are UNDEF.
5427 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5430 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5431 // Try to match an SSE3 float HADD/HSUB.
5432 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5433 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5435 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5436 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5437 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5438 // Try to match an SSSE3 integer HADD/HSUB.
5439 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5440 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5442 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5443 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5446 if (!Subtarget->hasAVX())
5449 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5450 // Try to match an AVX horizontal add/sub of packed single/double
5451 // precision floating point values from 256-bit vectors.
5452 SDValue InVec2, InVec3;
5453 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5454 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5455 ((InVec0.getOpcode() == ISD::UNDEF ||
5456 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5457 ((InVec1.getOpcode() == ISD::UNDEF ||
5458 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5459 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5461 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5462 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5463 ((InVec0.getOpcode() == ISD::UNDEF ||
5464 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5465 ((InVec1.getOpcode() == ISD::UNDEF ||
5466 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5467 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5468 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5469 // Try to match an AVX2 horizontal add/sub of signed integers.
5470 SDValue InVec2, InVec3;
5472 bool CanFold = true;
5474 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5475 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5476 ((InVec0.getOpcode() == ISD::UNDEF ||
5477 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5478 ((InVec1.getOpcode() == ISD::UNDEF ||
5479 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5480 X86Opcode = X86ISD::HADD;
5481 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5482 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5483 ((InVec0.getOpcode() == ISD::UNDEF ||
5484 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5485 ((InVec1.getOpcode() == ISD::UNDEF ||
5486 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5487 X86Opcode = X86ISD::HSUB;
5492 // Fold this build_vector into a single horizontal add/sub.
5493 // Do this only if the target has AVX2.
5494 if (Subtarget->hasAVX2())
5495 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5497 // Do not try to expand this build_vector into a pair of horizontal
5498 // add/sub if we can emit a pair of scalar add/sub.
5499 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5502 // Convert this build_vector into a pair of horizontal binop followed by
5504 bool isUndefLO = NumUndefsLO == Half;
5505 bool isUndefHI = NumUndefsHI == Half;
5506 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5507 isUndefLO, isUndefHI);
5511 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5512 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5514 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5515 X86Opcode = X86ISD::HADD;
5516 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5517 X86Opcode = X86ISD::HSUB;
5518 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5519 X86Opcode = X86ISD::FHADD;
5520 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5521 X86Opcode = X86ISD::FHSUB;
5525 // Don't try to expand this build_vector into a pair of horizontal add/sub
5526 // if we can simply emit a pair of scalar add/sub.
5527 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5530 // Convert this build_vector into two horizontal add/sub followed by
5532 bool isUndefLO = NumUndefsLO == Half;
5533 bool isUndefHI = NumUndefsHI == Half;
5534 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5535 isUndefLO, isUndefHI);
5542 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5545 MVT VT = Op.getSimpleValueType();
5546 MVT ExtVT = VT.getVectorElementType();
5547 unsigned NumElems = Op.getNumOperands();
5549 // Generate vectors for predicate vectors.
5550 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5551 return LowerBUILD_VECTORvXi1(Op, DAG);
5553 // Vectors containing all zeros can be matched by pxor and xorps later
5554 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5555 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5556 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5557 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5560 return getZeroVector(VT, Subtarget, DAG, dl);
5563 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5564 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5565 // vpcmpeqd on 256-bit vectors.
5566 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5567 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5570 if (!VT.is512BitVector())
5571 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5574 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5575 if (Broadcast.getNode())
5578 unsigned EVTBits = ExtVT.getSizeInBits();
5580 unsigned NumZero = 0;
5581 unsigned NumNonZero = 0;
5582 unsigned NonZeros = 0;
5583 bool IsAllConstants = true;
5584 SmallSet<SDValue, 8> Values;
5585 for (unsigned i = 0; i < NumElems; ++i) {
5586 SDValue Elt = Op.getOperand(i);
5587 if (Elt.getOpcode() == ISD::UNDEF)
5590 if (Elt.getOpcode() != ISD::Constant &&
5591 Elt.getOpcode() != ISD::ConstantFP)
5592 IsAllConstants = false;
5593 if (X86::isZeroNode(Elt))
5596 NonZeros |= (1 << i);
5601 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5602 if (NumNonZero == 0)
5603 return DAG.getUNDEF(VT);
5605 // Special case for single non-zero, non-undef, element.
5606 if (NumNonZero == 1) {
5607 unsigned Idx = countTrailingZeros(NonZeros);
5608 SDValue Item = Op.getOperand(Idx);
5610 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5611 // the value are obviously zero, truncate the value to i32 and do the
5612 // insertion that way. Only do this if the value is non-constant or if the
5613 // value is a constant being inserted into element 0. It is cheaper to do
5614 // a constant pool load than it is to do a movd + shuffle.
5615 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5616 (!IsAllConstants || Idx == 0)) {
5617 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5619 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5620 EVT VecVT = MVT::v4i32;
5622 // Truncate the value (which may itself be a constant) to i32, and
5623 // convert it to a vector with movd (S2V+shuffle to zero extend).
5624 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5625 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5627 ISD::BITCAST, dl, VT,
5628 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5632 // If we have a constant or non-constant insertion into the low element of
5633 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5634 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5635 // depending on what the source datatype is.
5638 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5640 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5641 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5642 if (VT.is512BitVector()) {
5643 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5644 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5645 Item, DAG.getIntPtrConstant(0));
5647 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5648 "Expected an SSE value type!");
5649 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5650 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5651 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5654 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5655 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5656 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5657 if (VT.is256BitVector()) {
5658 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5659 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5661 assert(VT.is128BitVector() && "Expected an SSE value type!");
5662 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5664 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5668 // Is it a vector logical left shift?
5669 if (NumElems == 2 && Idx == 1 &&
5670 X86::isZeroNode(Op.getOperand(0)) &&
5671 !X86::isZeroNode(Op.getOperand(1))) {
5672 unsigned NumBits = VT.getSizeInBits();
5673 return getVShift(true, VT,
5674 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5675 VT, Op.getOperand(1)),
5676 NumBits/2, DAG, *this, dl);
5679 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5682 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5683 // is a non-constant being inserted into an element other than the low one,
5684 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5685 // movd/movss) to move this into the low element, then shuffle it into
5687 if (EVTBits == 32) {
5688 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5689 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5693 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5694 if (Values.size() == 1) {
5695 if (EVTBits == 32) {
5696 // Instead of a shuffle like this:
5697 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5698 // Check if it's possible to issue this instead.
5699 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5700 unsigned Idx = countTrailingZeros(NonZeros);
5701 SDValue Item = Op.getOperand(Idx);
5702 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5703 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5708 // A vector full of immediates; various special cases are already
5709 // handled, so this is best done with a single constant-pool load.
5713 // For AVX-length vectors, see if we can use a vector load to get all of the
5714 // elements, otherwise build the individual 128-bit pieces and use
5715 // shuffles to put them in place.
5716 if (VT.is256BitVector() || VT.is512BitVector()) {
5717 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5719 // Check for a build vector of consecutive loads.
5720 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5723 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5725 // Build both the lower and upper subvector.
5726 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5727 makeArrayRef(&V[0], NumElems/2));
5728 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5729 makeArrayRef(&V[NumElems / 2], NumElems/2));
5731 // Recreate the wider vector with the lower and upper part.
5732 if (VT.is256BitVector())
5733 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5734 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5737 // Let legalizer expand 2-wide build_vectors.
5738 if (EVTBits == 64) {
5739 if (NumNonZero == 1) {
5740 // One half is zero or undef.
5741 unsigned Idx = countTrailingZeros(NonZeros);
5742 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5743 Op.getOperand(Idx));
5744 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5749 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5750 if (EVTBits == 8 && NumElems == 16) {
5751 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5753 if (V.getNode()) return V;
5756 if (EVTBits == 16 && NumElems == 8) {
5757 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5759 if (V.getNode()) return V;
5762 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5763 if (EVTBits == 32 && NumElems == 4) {
5764 SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5769 // If element VT is == 32 bits, turn it into a number of shuffles.
5770 SmallVector<SDValue, 8> V(NumElems);
5771 if (NumElems == 4 && NumZero > 0) {
5772 for (unsigned i = 0; i < 4; ++i) {
5773 bool isZero = !(NonZeros & (1 << i));
5775 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5777 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5780 for (unsigned i = 0; i < 2; ++i) {
5781 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5784 V[i] = V[i*2]; // Must be a zero vector.
5787 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5790 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5793 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5798 bool Reverse1 = (NonZeros & 0x3) == 2;
5799 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5803 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5804 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5806 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5809 if (Values.size() > 1 && VT.is128BitVector()) {
5810 // Check for a build vector of consecutive loads.
5811 for (unsigned i = 0; i < NumElems; ++i)
5812 V[i] = Op.getOperand(i);
5814 // Check for elements which are consecutive loads.
5815 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5819 // Check for a build vector from mostly shuffle plus few inserting.
5820 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5824 // For SSE 4.1, use insertps to put the high elements into the low element.
5825 if (Subtarget->hasSSE41()) {
5827 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5828 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5830 Result = DAG.getUNDEF(VT);
5832 for (unsigned i = 1; i < NumElems; ++i) {
5833 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5834 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5835 Op.getOperand(i), DAG.getIntPtrConstant(i));
5840 // Otherwise, expand into a number of unpckl*, start by extending each of
5841 // our (non-undef) elements to the full vector width with the element in the
5842 // bottom slot of the vector (which generates no code for SSE).
5843 for (unsigned i = 0; i < NumElems; ++i) {
5844 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5845 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5847 V[i] = DAG.getUNDEF(VT);
5850 // Next, we iteratively mix elements, e.g. for v4f32:
5851 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5852 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5853 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5854 unsigned EltStride = NumElems >> 1;
5855 while (EltStride != 0) {
5856 for (unsigned i = 0; i < EltStride; ++i) {
5857 // If V[i+EltStride] is undef and this is the first round of mixing,
5858 // then it is safe to just drop this shuffle: V[i] is already in the
5859 // right place, the one element (since it's the first round) being
5860 // inserted as undef can be dropped. This isn't safe for successive
5861 // rounds because they will permute elements within both vectors.
5862 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5863 EltStride == NumElems/2)
5866 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5875 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5876 // to create 256-bit vectors from two other 128-bit ones.
5877 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5879 MVT ResVT = Op.getSimpleValueType();
5881 assert((ResVT.is256BitVector() ||
5882 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5884 SDValue V1 = Op.getOperand(0);
5885 SDValue V2 = Op.getOperand(1);
5886 unsigned NumElems = ResVT.getVectorNumElements();
5887 if(ResVT.is256BitVector())
5888 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5890 if (Op.getNumOperands() == 4) {
5891 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5892 ResVT.getVectorNumElements()/2);
5893 SDValue V3 = Op.getOperand(2);
5894 SDValue V4 = Op.getOperand(3);
5895 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5896 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5898 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5901 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5902 const X86Subtarget *Subtarget,
5903 SelectionDAG & DAG) {
5905 MVT ResVT = Op.getSimpleValueType();
5906 unsigned NumOfOperands = Op.getNumOperands();
5908 assert(isPowerOf2_32(NumOfOperands) &&
5909 "Unexpected number of operands in CONCAT_VECTORS");
5911 if (NumOfOperands > 2) {
5912 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5913 ResVT.getVectorNumElements()/2);
5914 SmallVector<SDValue, 2> Ops;
5915 for (unsigned i = 0; i < NumOfOperands/2; i++)
5916 Ops.push_back(Op.getOperand(i));
5917 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5919 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
5920 Ops.push_back(Op.getOperand(i));
5921 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5922 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
5925 SDValue V1 = Op.getOperand(0);
5926 SDValue V2 = Op.getOperand(1);
5927 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
5928 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
5930 if (IsZeroV1 && IsZeroV2)
5931 return getZeroVector(ResVT, Subtarget, DAG, dl);
5933 SDValue ZeroIdx = DAG.getIntPtrConstant(0);
5934 SDValue Undef = DAG.getUNDEF(ResVT);
5935 unsigned NumElems = ResVT.getVectorNumElements();
5936 SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
5938 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
5939 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
5943 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
5944 // Zero the upper bits of V1
5945 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
5946 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
5949 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
5952 static SDValue LowerCONCAT_VECTORS(SDValue Op,
5953 const X86Subtarget *Subtarget,
5954 SelectionDAG &DAG) {
5955 MVT VT = Op.getSimpleValueType();
5956 if (VT.getVectorElementType() == MVT::i1)
5957 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
5959 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5960 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5961 Op.getNumOperands() == 4)));
5963 // AVX can use the vinsertf128 instruction to create 256-bit vectors
5964 // from two other 128-bit ones.
5966 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5967 return LowerAVXCONCAT_VECTORS(Op, DAG);
5971 //===----------------------------------------------------------------------===//
5972 // Vector shuffle lowering
5974 // This is an experimental code path for lowering vector shuffles on x86. It is
5975 // designed to handle arbitrary vector shuffles and blends, gracefully
5976 // degrading performance as necessary. It works hard to recognize idiomatic
5977 // shuffles and lower them to optimal instruction patterns without leaving
5978 // a framework that allows reasonably efficient handling of all vector shuffle
5980 //===----------------------------------------------------------------------===//
5982 /// \brief Tiny helper function to identify a no-op mask.
5984 /// This is a somewhat boring predicate function. It checks whether the mask
5985 /// array input, which is assumed to be a single-input shuffle mask of the kind
5986 /// used by the X86 shuffle instructions (not a fully general
5987 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5988 /// in-place shuffle are 'no-op's.
5989 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5990 for (int i = 0, Size = Mask.size(); i < Size; ++i)
5991 if (Mask[i] != -1 && Mask[i] != i)
5996 /// \brief Helper function to classify a mask as a single-input mask.
5998 /// This isn't a generic single-input test because in the vector shuffle
5999 /// lowering we canonicalize single inputs to be the first input operand. This
6000 /// means we can more quickly test for a single input by only checking whether
6001 /// an input from the second operand exists. We also assume that the size of
6002 /// mask corresponds to the size of the input vectors which isn't true in the
6003 /// fully general case.
6004 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6006 if (M >= (int)Mask.size())
6011 /// \brief Test whether there are elements crossing 128-bit lanes in this
6014 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6015 /// and we routinely test for these.
6016 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6017 int LaneSize = 128 / VT.getScalarSizeInBits();
6018 int Size = Mask.size();
6019 for (int i = 0; i < Size; ++i)
6020 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6025 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6027 /// This checks a shuffle mask to see if it is performing the same
6028 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6029 /// that it is also not lane-crossing. It may however involve a blend from the
6030 /// same lane of a second vector.
6032 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6033 /// non-trivial to compute in the face of undef lanes. The representation is
6034 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6035 /// entries from both V1 and V2 inputs to the wider mask.
6037 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6038 SmallVectorImpl<int> &RepeatedMask) {
6039 int LaneSize = 128 / VT.getScalarSizeInBits();
6040 RepeatedMask.resize(LaneSize, -1);
6041 int Size = Mask.size();
6042 for (int i = 0; i < Size; ++i) {
6045 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6046 // This entry crosses lanes, so there is no way to model this shuffle.
6049 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6050 if (RepeatedMask[i % LaneSize] == -1)
6051 // This is the first non-undef entry in this slot of a 128-bit lane.
6052 RepeatedMask[i % LaneSize] =
6053 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6054 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6055 // Found a mismatch with the repeated mask.
6061 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6064 /// This is a fast way to test a shuffle mask against a fixed pattern:
6066 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6068 /// It returns true if the mask is exactly as wide as the argument list, and
6069 /// each element of the mask is either -1 (signifying undef) or the value given
6070 /// in the argument.
6071 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6072 ArrayRef<int> ExpectedMask) {
6073 if (Mask.size() != ExpectedMask.size())
6076 int Size = Mask.size();
6078 // If the values are build vectors, we can look through them to find
6079 // equivalent inputs that make the shuffles equivalent.
6080 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6081 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6083 for (int i = 0; i < Size; ++i)
6084 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6085 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6086 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6087 if (!MaskBV || !ExpectedBV ||
6088 MaskBV->getOperand(Mask[i] % Size) !=
6089 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6096 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6098 /// This helper function produces an 8-bit shuffle immediate corresponding to
6099 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6100 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6103 /// NB: We rely heavily on "undef" masks preserving the input lane.
6104 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6105 SelectionDAG &DAG) {
6106 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6107 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6108 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6109 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6110 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6113 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6114 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6115 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6116 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6117 return DAG.getConstant(Imm, MVT::i8);
6120 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6122 /// This is used as a fallback approach when first class blend instructions are
6123 /// unavailable. Currently it is only suitable for integer vectors, but could
6124 /// be generalized for floating point vectors if desirable.
6125 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6126 SDValue V2, ArrayRef<int> Mask,
6127 SelectionDAG &DAG) {
6128 assert(VT.isInteger() && "Only supports integer vector types!");
6129 MVT EltVT = VT.getScalarType();
6130 int NumEltBits = EltVT.getSizeInBits();
6131 SDValue Zero = DAG.getConstant(0, EltVT);
6132 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6133 SmallVector<SDValue, 16> MaskOps;
6134 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6135 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6136 return SDValue(); // Shuffled input!
6137 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6140 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6141 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6142 // We have to cast V2 around.
6143 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6144 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6145 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6146 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6147 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6148 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6151 /// \brief Try to emit a blend instruction for a shuffle.
6153 /// This doesn't do any checks for the availability of instructions for blending
6154 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6155 /// be matched in the backend with the type given. What it does check for is
6156 /// that the shuffle mask is in fact a blend.
6157 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6158 SDValue V2, ArrayRef<int> Mask,
6159 const X86Subtarget *Subtarget,
6160 SelectionDAG &DAG) {
6161 unsigned BlendMask = 0;
6162 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6163 if (Mask[i] >= Size) {
6164 if (Mask[i] != i + Size)
6165 return SDValue(); // Shuffled V2 input!
6166 BlendMask |= 1u << i;
6169 if (Mask[i] >= 0 && Mask[i] != i)
6170 return SDValue(); // Shuffled V1 input!
6172 switch (VT.SimpleTy) {
6177 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6178 DAG.getConstant(BlendMask, MVT::i8));
6182 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6186 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6187 // that instruction.
6188 if (Subtarget->hasAVX2()) {
6189 // Scale the blend by the number of 32-bit dwords per element.
6190 int Scale = VT.getScalarSizeInBits() / 32;
6192 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6193 if (Mask[i] >= Size)
6194 for (int j = 0; j < Scale; ++j)
6195 BlendMask |= 1u << (i * Scale + j);
6197 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6198 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6199 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6200 return DAG.getNode(ISD::BITCAST, DL, VT,
6201 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6202 DAG.getConstant(BlendMask, MVT::i8)));
6206 // For integer shuffles we need to expand the mask and cast the inputs to
6207 // v8i16s prior to blending.
6208 int Scale = 8 / VT.getVectorNumElements();
6210 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6211 if (Mask[i] >= Size)
6212 for (int j = 0; j < Scale; ++j)
6213 BlendMask |= 1u << (i * Scale + j);
6215 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6216 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6217 return DAG.getNode(ISD::BITCAST, DL, VT,
6218 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6219 DAG.getConstant(BlendMask, MVT::i8)));
6223 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6224 SmallVector<int, 8> RepeatedMask;
6225 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6226 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6227 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6229 for (int i = 0; i < 8; ++i)
6230 if (RepeatedMask[i] >= 16)
6231 BlendMask |= 1u << i;
6232 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6233 DAG.getConstant(BlendMask, MVT::i8));
6239 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6240 "256-bit byte-blends require AVX2 support!");
6242 // Scale the blend by the number of bytes per element.
6243 int Scale = VT.getScalarSizeInBits() / 8;
6245 // This form of blend is always done on bytes. Compute the byte vector
6247 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6249 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6250 // mix of LLVM's code generator and the x86 backend. We tell the code
6251 // generator that boolean values in the elements of an x86 vector register
6252 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6253 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6254 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6255 // of the element (the remaining are ignored) and 0 in that high bit would
6256 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6257 // the LLVM model for boolean values in vector elements gets the relevant
6258 // bit set, it is set backwards and over constrained relative to x86's
6260 SmallVector<SDValue, 32> VSELECTMask;
6261 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6262 for (int j = 0; j < Scale; ++j)
6263 VSELECTMask.push_back(
6264 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6265 : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6267 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6268 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6270 ISD::BITCAST, DL, VT,
6271 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6272 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6277 llvm_unreachable("Not a supported integer vector type!");
6281 /// \brief Try to lower as a blend of elements from two inputs followed by
6282 /// a single-input permutation.
6284 /// This matches the pattern where we can blend elements from two inputs and
6285 /// then reduce the shuffle to a single-input permutation.
6286 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6289 SelectionDAG &DAG) {
6290 // We build up the blend mask while checking whether a blend is a viable way
6291 // to reduce the shuffle.
6292 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6293 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6295 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6299 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6301 if (BlendMask[Mask[i] % Size] == -1)
6302 BlendMask[Mask[i] % Size] = Mask[i];
6303 else if (BlendMask[Mask[i] % Size] != Mask[i])
6304 return SDValue(); // Can't blend in the needed input!
6306 PermuteMask[i] = Mask[i] % Size;
6309 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6310 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6313 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6314 /// blends and permutes.
6316 /// This matches the extremely common pattern for handling combined
6317 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6318 /// operations. It will try to pick the best arrangement of shuffles and
6320 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6324 SelectionDAG &DAG) {
6325 // Shuffle the input elements into the desired positions in V1 and V2 and
6326 // blend them together.
6327 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6328 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6329 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6330 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6331 if (Mask[i] >= 0 && Mask[i] < Size) {
6332 V1Mask[i] = Mask[i];
6334 } else if (Mask[i] >= Size) {
6335 V2Mask[i] = Mask[i] - Size;
6336 BlendMask[i] = i + Size;
6339 // Try to lower with the simpler initial blend strategy unless one of the
6340 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6341 // shuffle may be able to fold with a load or other benefit. However, when
6342 // we'll have to do 2x as many shuffles in order to achieve this, blending
6343 // first is a better strategy.
6344 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6345 if (SDValue BlendPerm =
6346 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6349 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6350 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6351 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6354 /// \brief Try to lower a vector shuffle as a byte rotation.
6356 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6357 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6358 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6359 /// try to generically lower a vector shuffle through such an pattern. It
6360 /// does not check for the profitability of lowering either as PALIGNR or
6361 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6362 /// This matches shuffle vectors that look like:
6364 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6366 /// Essentially it concatenates V1 and V2, shifts right by some number of
6367 /// elements, and takes the low elements as the result. Note that while this is
6368 /// specified as a *right shift* because x86 is little-endian, it is a *left
6369 /// rotate* of the vector lanes.
6370 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6373 const X86Subtarget *Subtarget,
6374 SelectionDAG &DAG) {
6375 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6377 int NumElts = Mask.size();
6378 int NumLanes = VT.getSizeInBits() / 128;
6379 int NumLaneElts = NumElts / NumLanes;
6381 // We need to detect various ways of spelling a rotation:
6382 // [11, 12, 13, 14, 15, 0, 1, 2]
6383 // [-1, 12, 13, 14, -1, -1, 1, -1]
6384 // [-1, -1, -1, -1, -1, -1, 1, 2]
6385 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6386 // [-1, 4, 5, 6, -1, -1, 9, -1]
6387 // [-1, 4, 5, 6, -1, -1, -1, -1]
6390 for (int l = 0; l < NumElts; l += NumLaneElts) {
6391 for (int i = 0; i < NumLaneElts; ++i) {
6392 if (Mask[l + i] == -1)
6394 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6396 // Get the mod-Size index and lane correct it.
6397 int LaneIdx = (Mask[l + i] % NumElts) - l;
6398 // Make sure it was in this lane.
6399 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6402 // Determine where a rotated vector would have started.
6403 int StartIdx = i - LaneIdx;
6405 // The identity rotation isn't interesting, stop.
6408 // If we found the tail of a vector the rotation must be the missing
6409 // front. If we found the head of a vector, it must be how much of the
6411 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6414 Rotation = CandidateRotation;
6415 else if (Rotation != CandidateRotation)
6416 // The rotations don't match, so we can't match this mask.
6419 // Compute which value this mask is pointing at.
6420 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6422 // Compute which of the two target values this index should be assigned
6423 // to. This reflects whether the high elements are remaining or the low
6424 // elements are remaining.
6425 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6427 // Either set up this value if we've not encountered it before, or check
6428 // that it remains consistent.
6431 else if (TargetV != MaskV)
6432 // This may be a rotation, but it pulls from the inputs in some
6433 // unsupported interleaving.
6438 // Check that we successfully analyzed the mask, and normalize the results.
6439 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6440 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6446 // The actual rotate instruction rotates bytes, so we need to scale the
6447 // rotation based on how many bytes are in the vector lane.
6448 int Scale = 16 / NumLaneElts;
6450 // SSSE3 targets can use the palignr instruction.
6451 if (Subtarget->hasSSSE3()) {
6452 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6453 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6454 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6455 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6457 return DAG.getNode(ISD::BITCAST, DL, VT,
6458 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6459 DAG.getConstant(Rotation * Scale, MVT::i8)));
6462 assert(VT.getSizeInBits() == 128 &&
6463 "Rotate-based lowering only supports 128-bit lowering!");
6464 assert(Mask.size() <= 16 &&
6465 "Can shuffle at most 16 bytes in a 128-bit vector!");
6467 // Default SSE2 implementation
6468 int LoByteShift = 16 - Rotation * Scale;
6469 int HiByteShift = Rotation * Scale;
6471 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6472 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6473 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6475 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6476 DAG.getConstant(LoByteShift, MVT::i8));
6477 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6478 DAG.getConstant(HiByteShift, MVT::i8));
6479 return DAG.getNode(ISD::BITCAST, DL, VT,
6480 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6483 /// \brief Compute whether each element of a shuffle is zeroable.
6485 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6486 /// Either it is an undef element in the shuffle mask, the element of the input
6487 /// referenced is undef, or the element of the input referenced is known to be
6488 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6489 /// as many lanes with this technique as possible to simplify the remaining
6491 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6492 SDValue V1, SDValue V2) {
6493 SmallBitVector Zeroable(Mask.size(), false);
6495 while (V1.getOpcode() == ISD::BITCAST)
6496 V1 = V1->getOperand(0);
6497 while (V2.getOpcode() == ISD::BITCAST)
6498 V2 = V2->getOperand(0);
6500 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6501 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6503 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6505 // Handle the easy cases.
6506 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6511 // If this is an index into a build_vector node (which has the same number
6512 // of elements), dig out the input value and use it.
6513 SDValue V = M < Size ? V1 : V2;
6514 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6517 SDValue Input = V.getOperand(M % Size);
6518 // The UNDEF opcode check really should be dead code here, but not quite
6519 // worth asserting on (it isn't invalid, just unexpected).
6520 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6527 /// \brief Try to emit a bitmask instruction for a shuffle.
6529 /// This handles cases where we can model a blend exactly as a bitmask due to
6530 /// one of the inputs being zeroable.
6531 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6532 SDValue V2, ArrayRef<int> Mask,
6533 SelectionDAG &DAG) {
6534 MVT EltVT = VT.getScalarType();
6535 int NumEltBits = EltVT.getSizeInBits();
6536 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6537 SDValue Zero = DAG.getConstant(0, IntEltVT);
6538 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6539 if (EltVT.isFloatingPoint()) {
6540 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6541 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6543 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6544 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6546 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6549 if (Mask[i] % Size != i)
6550 return SDValue(); // Not a blend.
6552 V = Mask[i] < Size ? V1 : V2;
6553 else if (V != (Mask[i] < Size ? V1 : V2))
6554 return SDValue(); // Can only let one input through the mask.
6556 VMaskOps[i] = AllOnes;
6559 return SDValue(); // No non-zeroable elements!
6561 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6562 V = DAG.getNode(VT.isFloatingPoint()
6563 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6568 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6570 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6571 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6572 /// matches elements from one of the input vectors shuffled to the left or
6573 /// right with zeroable elements 'shifted in'. It handles both the strictly
6574 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6577 /// PSHL : (little-endian) left bit shift.
6578 /// [ zz, 0, zz, 2 ]
6579 /// [ -1, 4, zz, -1 ]
6580 /// PSRL : (little-endian) right bit shift.
6582 /// [ -1, -1, 7, zz]
6583 /// PSLLDQ : (little-endian) left byte shift
6584 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6585 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6586 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6587 /// PSRLDQ : (little-endian) right byte shift
6588 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6589 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6590 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6591 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6592 SDValue V2, ArrayRef<int> Mask,
6593 SelectionDAG &DAG) {
6594 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6596 int Size = Mask.size();
6597 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6599 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6600 for (int i = 0; i < Size; i += Scale)
6601 for (int j = 0; j < Shift; ++j)
6602 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6608 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6609 for (int i = 0; i != Size; i += Scale) {
6610 unsigned Pos = Left ? i + Shift : i;
6611 unsigned Low = Left ? i : i + Shift;
6612 unsigned Len = Scale - Shift;
6613 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6614 Low + (V == V1 ? 0 : Size)))
6618 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6619 bool ByteShift = ShiftEltBits > 64;
6620 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6621 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6622 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6624 // Normalize the scale for byte shifts to still produce an i64 element
6626 Scale = ByteShift ? Scale / 2 : Scale;
6628 // We need to round trip through the appropriate type for the shift.
6629 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6630 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6631 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6632 "Illegal integer vector type");
6633 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6635 V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6636 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6639 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6640 // keep doubling the size of the integer elements up to that. We can
6641 // then shift the elements of the integer vector by whole multiples of
6642 // their width within the elements of the larger integer vector. Test each
6643 // multiple to see if we can find a match with the moved element indices
6644 // and that the shifted in elements are all zeroable.
6645 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6646 for (int Shift = 1; Shift != Scale; ++Shift)
6647 for (bool Left : {true, false})
6648 if (CheckZeros(Shift, Scale, Left))
6649 for (SDValue V : {V1, V2})
6650 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6657 /// \brief Lower a vector shuffle as a zero or any extension.
6659 /// Given a specific number of elements, element bit width, and extension
6660 /// stride, produce either a zero or any extension based on the available
6661 /// features of the subtarget.
6662 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6663 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6664 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6665 assert(Scale > 1 && "Need a scale to extend.");
6666 int NumElements = VT.getVectorNumElements();
6667 int EltBits = VT.getScalarSizeInBits();
6668 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6669 "Only 8, 16, and 32 bit elements can be extended.");
6670 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6672 // Found a valid zext mask! Try various lowering strategies based on the
6673 // input type and available ISA extensions.
6674 if (Subtarget->hasSSE41()) {
6675 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6676 NumElements / Scale);
6677 return DAG.getNode(ISD::BITCAST, DL, VT,
6678 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6681 // For any extends we can cheat for larger element sizes and use shuffle
6682 // instructions that can fold with a load and/or copy.
6683 if (AnyExt && EltBits == 32) {
6684 int PSHUFDMask[4] = {0, -1, 1, -1};
6686 ISD::BITCAST, DL, VT,
6687 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6688 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6689 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6691 if (AnyExt && EltBits == 16 && Scale > 2) {
6692 int PSHUFDMask[4] = {0, -1, 0, -1};
6693 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6694 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6695 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6696 int PSHUFHWMask[4] = {1, -1, -1, -1};
6698 ISD::BITCAST, DL, VT,
6699 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6700 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6701 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6704 // If this would require more than 2 unpack instructions to expand, use
6705 // pshufb when available. We can only use more than 2 unpack instructions
6706 // when zero extending i8 elements which also makes it easier to use pshufb.
6707 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6708 assert(NumElements == 16 && "Unexpected byte vector width!");
6709 SDValue PSHUFBMask[16];
6710 for (int i = 0; i < 16; ++i)
6712 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6713 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6714 return DAG.getNode(ISD::BITCAST, DL, VT,
6715 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6716 DAG.getNode(ISD::BUILD_VECTOR, DL,
6717 MVT::v16i8, PSHUFBMask)));
6720 // Otherwise emit a sequence of unpacks.
6722 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6723 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6724 : getZeroVector(InputVT, Subtarget, DAG, DL);
6725 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6726 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6730 } while (Scale > 1);
6731 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6734 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6736 /// This routine will try to do everything in its power to cleverly lower
6737 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6738 /// check for the profitability of this lowering, it tries to aggressively
6739 /// match this pattern. It will use all of the micro-architectural details it
6740 /// can to emit an efficient lowering. It handles both blends with all-zero
6741 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6742 /// masking out later).
6744 /// The reason we have dedicated lowering for zext-style shuffles is that they
6745 /// are both incredibly common and often quite performance sensitive.
6746 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6747 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6748 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6749 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6751 int Bits = VT.getSizeInBits();
6752 int NumElements = VT.getVectorNumElements();
6753 assert(VT.getScalarSizeInBits() <= 32 &&
6754 "Exceeds 32-bit integer zero extension limit");
6755 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6757 // Define a helper function to check a particular ext-scale and lower to it if
6759 auto Lower = [&](int Scale) -> SDValue {
6762 for (int i = 0; i < NumElements; ++i) {
6764 continue; // Valid anywhere but doesn't tell us anything.
6765 if (i % Scale != 0) {
6766 // Each of the extended elements need to be zeroable.
6770 // We no longer are in the anyext case.
6775 // Each of the base elements needs to be consecutive indices into the
6776 // same input vector.
6777 SDValue V = Mask[i] < NumElements ? V1 : V2;
6780 else if (InputV != V)
6781 return SDValue(); // Flip-flopping inputs.
6783 if (Mask[i] % NumElements != i / Scale)
6784 return SDValue(); // Non-consecutive strided elements.
6787 // If we fail to find an input, we have a zero-shuffle which should always
6788 // have already been handled.
6789 // FIXME: Maybe handle this here in case during blending we end up with one?
6793 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6794 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6797 // The widest scale possible for extending is to a 64-bit integer.
6798 assert(Bits % 64 == 0 &&
6799 "The number of bits in a vector must be divisible by 64 on x86!");
6800 int NumExtElements = Bits / 64;
6802 // Each iteration, try extending the elements half as much, but into twice as
6804 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6805 assert(NumElements % NumExtElements == 0 &&
6806 "The input vector size must be divisible by the extended size.");
6807 if (SDValue V = Lower(NumElements / NumExtElements))
6811 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6815 // Returns one of the source operands if the shuffle can be reduced to a
6816 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6817 auto CanZExtLowHalf = [&]() {
6818 for (int i = NumElements / 2; i != NumElements; ++i)
6821 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6823 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6828 if (SDValue V = CanZExtLowHalf()) {
6829 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6830 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6831 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6834 // No viable ext lowering found.
6838 /// \brief Try to get a scalar value for a specific element of a vector.
6840 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6841 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6842 SelectionDAG &DAG) {
6843 MVT VT = V.getSimpleValueType();
6844 MVT EltVT = VT.getVectorElementType();
6845 while (V.getOpcode() == ISD::BITCAST)
6846 V = V.getOperand(0);
6847 // If the bitcasts shift the element size, we can't extract an equivalent
6849 MVT NewVT = V.getSimpleValueType();
6850 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6853 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6854 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6855 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6860 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6862 /// This is particularly important because the set of instructions varies
6863 /// significantly based on whether the operand is a load or not.
6864 static bool isShuffleFoldableLoad(SDValue V) {
6865 while (V.getOpcode() == ISD::BITCAST)
6866 V = V.getOperand(0);
6868 return ISD::isNON_EXTLoad(V.getNode());
6871 /// \brief Try to lower insertion of a single element into a zero vector.
6873 /// This is a common pattern that we have especially efficient patterns to lower
6874 /// across all subtarget feature sets.
6875 static SDValue lowerVectorShuffleAsElementInsertion(
6876 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6877 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6878 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6880 MVT EltVT = VT.getVectorElementType();
6882 int V2Index = std::find_if(Mask.begin(), Mask.end(),
6883 [&Mask](int M) { return M >= (int)Mask.size(); }) -
6885 bool IsV1Zeroable = true;
6886 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6887 if (i != V2Index && !Zeroable[i]) {
6888 IsV1Zeroable = false;
6892 // Check for a single input from a SCALAR_TO_VECTOR node.
6893 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6894 // all the smarts here sunk into that routine. However, the current
6895 // lowering of BUILD_VECTOR makes that nearly impossible until the old
6896 // vector shuffle lowering is dead.
6897 if (SDValue V2S = getScalarValueForVectorElement(
6898 V2, Mask[V2Index] - Mask.size(), DAG)) {
6899 // We need to zext the scalar if it is smaller than an i32.
6900 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6901 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6902 // Using zext to expand a narrow element won't work for non-zero
6907 // Zero-extend directly to i32.
6909 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6911 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6912 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6913 EltVT == MVT::i16) {
6914 // Either not inserting from the low element of the input or the input
6915 // element size is too small to use VZEXT_MOVL to clear the high bits.
6919 if (!IsV1Zeroable) {
6920 // If V1 can't be treated as a zero vector we have fewer options to lower
6921 // this. We can't support integer vectors or non-zero targets cheaply, and
6922 // the V1 elements can't be permuted in any way.
6923 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6924 if (!VT.isFloatingPoint() || V2Index != 0)
6926 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6927 V1Mask[V2Index] = -1;
6928 if (!isNoopShuffleMask(V1Mask))
6930 // This is essentially a special case blend operation, but if we have
6931 // general purpose blend operations, they are always faster. Bail and let
6932 // the rest of the lowering handle these as blends.
6933 if (Subtarget->hasSSE41())
6936 // Otherwise, use MOVSD or MOVSS.
6937 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6938 "Only two types of floating point element types to handle!");
6939 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6943 // This lowering only works for the low element with floating point vectors.
6944 if (VT.isFloatingPoint() && V2Index != 0)
6947 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6949 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6952 // If we have 4 or fewer lanes we can cheaply shuffle the element into
6953 // the desired position. Otherwise it is more efficient to do a vector
6954 // shift left. We know that we can do a vector shift left because all
6955 // the inputs are zero.
6956 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6957 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6958 V2Shuffle[V2Index] = 0;
6959 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6961 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6963 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6965 V2Index * EltVT.getSizeInBits()/8,
6966 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6967 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6973 /// \brief Try to lower broadcast of a single element.
6975 /// For convenience, this code also bundles all of the subtarget feature set
6976 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6977 /// a convenient way to factor it out.
6978 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6980 const X86Subtarget *Subtarget,
6981 SelectionDAG &DAG) {
6982 if (!Subtarget->hasAVX())
6984 if (VT.isInteger() && !Subtarget->hasAVX2())
6987 // Check that the mask is a broadcast.
6988 int BroadcastIdx = -1;
6990 if (M >= 0 && BroadcastIdx == -1)
6992 else if (M >= 0 && M != BroadcastIdx)
6995 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6996 "a sorted mask where the broadcast "
6999 // Go up the chain of (vector) values to try and find a scalar load that
7000 // we can combine with the broadcast.
7002 switch (V.getOpcode()) {
7003 case ISD::CONCAT_VECTORS: {
7004 int OperandSize = Mask.size() / V.getNumOperands();
7005 V = V.getOperand(BroadcastIdx / OperandSize);
7006 BroadcastIdx %= OperandSize;
7010 case ISD::INSERT_SUBVECTOR: {
7011 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7012 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7016 int BeginIdx = (int)ConstantIdx->getZExtValue();
7018 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7019 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7020 BroadcastIdx -= BeginIdx;
7031 // Check if this is a broadcast of a scalar. We special case lowering
7032 // for scalars so that we can more effectively fold with loads.
7033 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7034 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7035 V = V.getOperand(BroadcastIdx);
7037 // If the scalar isn't a load we can't broadcast from it in AVX1, only with
7039 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7041 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7042 // We can't broadcast from a vector register w/o AVX2, and we can only
7043 // broadcast from the zero-element of a vector register.
7047 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7050 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7051 // INSERTPS when the V1 elements are already in the correct locations
7052 // because otherwise we can just always use two SHUFPS instructions which
7053 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7054 // perform INSERTPS if a single V1 element is out of place and all V2
7055 // elements are zeroable.
7056 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7058 SelectionDAG &DAG) {
7059 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7060 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7061 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7062 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7064 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7067 int V1DstIndex = -1;
7068 int V2DstIndex = -1;
7069 bool V1UsedInPlace = false;
7071 for (int i = 0; i < 4; ++i) {
7072 // Synthesize a zero mask from the zeroable elements (includes undefs).
7078 // Flag if we use any V1 inputs in place.
7080 V1UsedInPlace = true;
7084 // We can only insert a single non-zeroable element.
7085 if (V1DstIndex != -1 || V2DstIndex != -1)
7089 // V1 input out of place for insertion.
7092 // V2 input for insertion.
7097 // Don't bother if we have no (non-zeroable) element for insertion.
7098 if (V1DstIndex == -1 && V2DstIndex == -1)
7101 // Determine element insertion src/dst indices. The src index is from the
7102 // start of the inserted vector, not the start of the concatenated vector.
7103 unsigned V2SrcIndex = 0;
7104 if (V1DstIndex != -1) {
7105 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7106 // and don't use the original V2 at all.
7107 V2SrcIndex = Mask[V1DstIndex];
7108 V2DstIndex = V1DstIndex;
7111 V2SrcIndex = Mask[V2DstIndex] - 4;
7114 // If no V1 inputs are used in place, then the result is created only from
7115 // the zero mask and the V2 insertion - so remove V1 dependency.
7117 V1 = DAG.getUNDEF(MVT::v4f32);
7119 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7120 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7122 // Insert the V2 element into the desired position.
7124 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7125 DAG.getConstant(InsertPSMask, MVT::i8));
7128 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7129 /// UNPCK instruction.
7131 /// This specifically targets cases where we end up with alternating between
7132 /// the two inputs, and so can permute them into something that feeds a single
7133 /// UNPCK instruction. Note that this routine only targets integer vectors
7134 /// because for floating point vectors we have a generalized SHUFPS lowering
7135 /// strategy that handles everything that doesn't *exactly* match an unpack,
7136 /// making this clever lowering unnecessary.
7137 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7138 SDValue V2, ArrayRef<int> Mask,
7139 SelectionDAG &DAG) {
7140 assert(!VT.isFloatingPoint() &&
7141 "This routine only supports integer vectors.");
7142 assert(!isSingleInputShuffleMask(Mask) &&
7143 "This routine should only be used when blending two inputs.");
7144 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7146 int Size = Mask.size();
7148 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7149 return M >= 0 && M % Size < Size / 2;
7151 int NumHiInputs = std::count_if(
7152 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7154 bool UnpackLo = NumLoInputs >= NumHiInputs;
7156 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7157 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7158 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7160 for (int i = 0; i < Size; ++i) {
7164 // Each element of the unpack contains Scale elements from this mask.
7165 int UnpackIdx = i / Scale;
7167 // We only handle the case where V1 feeds the first slots of the unpack.
7168 // We rely on canonicalization to ensure this is the case.
7169 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7172 // Setup the mask for this input. The indexing is tricky as we have to
7173 // handle the unpack stride.
7174 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7175 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7179 // If we will have to shuffle both inputs to use the unpack, check whether
7180 // we can just unpack first and shuffle the result. If so, skip this unpack.
7181 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7182 !isNoopShuffleMask(V2Mask))
7185 // Shuffle the inputs into place.
7186 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7187 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7189 // Cast the inputs to the type we will use to unpack them.
7190 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7191 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7193 // Unpack the inputs and cast the result back to the desired type.
7194 return DAG.getNode(ISD::BITCAST, DL, VT,
7195 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7196 DL, UnpackVT, V1, V2));
7199 // We try each unpack from the largest to the smallest to try and find one
7200 // that fits this mask.
7201 int OrigNumElements = VT.getVectorNumElements();
7202 int OrigScalarSize = VT.getScalarSizeInBits();
7203 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7204 int Scale = ScalarSize / OrigScalarSize;
7205 int NumElements = OrigNumElements / Scale;
7206 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7207 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7211 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7213 if (NumLoInputs == 0 || NumHiInputs == 0) {
7214 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7215 "We have to have *some* inputs!");
7216 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7218 // FIXME: We could consider the total complexity of the permute of each
7219 // possible unpacking. Or at the least we should consider how many
7220 // half-crossings are created.
7221 // FIXME: We could consider commuting the unpacks.
7223 SmallVector<int, 32> PermMask;
7224 PermMask.assign(Size, -1);
7225 for (int i = 0; i < Size; ++i) {
7229 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7232 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7234 return DAG.getVectorShuffle(
7235 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7237 DAG.getUNDEF(VT), PermMask);
7243 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7245 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7246 /// support for floating point shuffles but not integer shuffles. These
7247 /// instructions will incur a domain crossing penalty on some chips though so
7248 /// it is better to avoid lowering through this for integer vectors where
7250 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7251 const X86Subtarget *Subtarget,
7252 SelectionDAG &DAG) {
7254 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7255 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7256 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7257 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7258 ArrayRef<int> Mask = SVOp->getMask();
7259 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7261 if (isSingleInputShuffleMask(Mask)) {
7262 // Use low duplicate instructions for masks that match their pattern.
7263 if (Subtarget->hasSSE3())
7264 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7265 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7267 // Straight shuffle of a single input vector. Simulate this by using the
7268 // single input as both of the "inputs" to this instruction..
7269 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7271 if (Subtarget->hasAVX()) {
7272 // If we have AVX, we can use VPERMILPS which will allow folding a load
7273 // into the shuffle.
7274 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7275 DAG.getConstant(SHUFPDMask, MVT::i8));
7278 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7279 DAG.getConstant(SHUFPDMask, MVT::i8));
7281 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7282 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7284 // If we have a single input, insert that into V1 if we can do so cheaply.
7285 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7286 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7287 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7289 // Try inverting the insertion since for v2 masks it is easy to do and we
7290 // can't reliably sort the mask one way or the other.
7291 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7292 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7293 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7294 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7298 // Try to use one of the special instruction patterns to handle two common
7299 // blend patterns if a zero-blend above didn't work.
7300 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7301 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7302 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7303 // We can either use a special instruction to load over the low double or
7304 // to move just the low double.
7306 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7308 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7310 if (Subtarget->hasSSE41())
7311 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7315 // Use dedicated unpack instructions for masks that match their pattern.
7316 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7317 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7318 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7319 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7321 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7322 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7323 DAG.getConstant(SHUFPDMask, MVT::i8));
7326 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7328 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7329 /// the integer unit to minimize domain crossing penalties. However, for blends
7330 /// it falls back to the floating point shuffle operation with appropriate bit
7332 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7333 const X86Subtarget *Subtarget,
7334 SelectionDAG &DAG) {
7336 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7337 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7338 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7339 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7340 ArrayRef<int> Mask = SVOp->getMask();
7341 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7343 if (isSingleInputShuffleMask(Mask)) {
7344 // Check for being able to broadcast a single element.
7345 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7346 Mask, Subtarget, DAG))
7349 // Straight shuffle of a single input vector. For everything from SSE2
7350 // onward this has a single fast instruction with no scary immediates.
7351 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7352 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7353 int WidenedMask[4] = {
7354 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7355 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7357 ISD::BITCAST, DL, MVT::v2i64,
7358 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7359 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7361 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7362 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7363 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7364 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7366 // If we have a blend of two PACKUS operations an the blend aligns with the
7367 // low and half halves, we can just merge the PACKUS operations. This is
7368 // particularly important as it lets us merge shuffles that this routine itself
7370 auto GetPackNode = [](SDValue V) {
7371 while (V.getOpcode() == ISD::BITCAST)
7372 V = V.getOperand(0);
7374 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7376 if (SDValue V1Pack = GetPackNode(V1))
7377 if (SDValue V2Pack = GetPackNode(V2))
7378 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7379 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7380 Mask[0] == 0 ? V1Pack.getOperand(0)
7381 : V1Pack.getOperand(1),
7382 Mask[1] == 2 ? V2Pack.getOperand(0)
7383 : V2Pack.getOperand(1)));
7385 // Try to use shift instructions.
7387 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7390 // When loading a scalar and then shuffling it into a vector we can often do
7391 // the insertion cheaply.
7392 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7393 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7395 // Try inverting the insertion since for v2 masks it is easy to do and we
7396 // can't reliably sort the mask one way or the other.
7397 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7398 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7399 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7402 // We have different paths for blend lowering, but they all must use the
7403 // *exact* same predicate.
7404 bool IsBlendSupported = Subtarget->hasSSE41();
7405 if (IsBlendSupported)
7406 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7410 // Use dedicated unpack instructions for masks that match their pattern.
7411 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7412 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7413 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7414 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7416 // Try to use byte rotation instructions.
7417 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7418 if (Subtarget->hasSSSE3())
7419 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7420 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7423 // If we have direct support for blends, we should lower by decomposing into
7424 // a permute. That will be faster than the domain cross.
7425 if (IsBlendSupported)
7426 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7429 // We implement this with SHUFPD which is pretty lame because it will likely
7430 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7431 // However, all the alternatives are still more cycles and newer chips don't
7432 // have this problem. It would be really nice if x86 had better shuffles here.
7433 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7434 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7435 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7436 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7439 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7441 /// This is used to disable more specialized lowerings when the shufps lowering
7442 /// will happen to be efficient.
7443 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7444 // This routine only handles 128-bit shufps.
7445 assert(Mask.size() == 4 && "Unsupported mask size!");
7447 // To lower with a single SHUFPS we need to have the low half and high half
7448 // each requiring a single input.
7449 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7451 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7457 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7459 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7460 /// It makes no assumptions about whether this is the *best* lowering, it simply
7462 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7463 ArrayRef<int> Mask, SDValue V1,
7464 SDValue V2, SelectionDAG &DAG) {
7465 SDValue LowV = V1, HighV = V2;
7466 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7469 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7471 if (NumV2Elements == 1) {
7473 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7476 // Compute the index adjacent to V2Index and in the same half by toggling
7478 int V2AdjIndex = V2Index ^ 1;
7480 if (Mask[V2AdjIndex] == -1) {
7481 // Handles all the cases where we have a single V2 element and an undef.
7482 // This will only ever happen in the high lanes because we commute the
7483 // vector otherwise.
7485 std::swap(LowV, HighV);
7486 NewMask[V2Index] -= 4;
7488 // Handle the case where the V2 element ends up adjacent to a V1 element.
7489 // To make this work, blend them together as the first step.
7490 int V1Index = V2AdjIndex;
7491 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7492 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7493 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7495 // Now proceed to reconstruct the final blend as we have the necessary
7496 // high or low half formed.
7503 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7504 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7506 } else if (NumV2Elements == 2) {
7507 if (Mask[0] < 4 && Mask[1] < 4) {
7508 // Handle the easy case where we have V1 in the low lanes and V2 in the
7512 } else if (Mask[2] < 4 && Mask[3] < 4) {
7513 // We also handle the reversed case because this utility may get called
7514 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7515 // arrange things in the right direction.
7521 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7522 // trying to place elements directly, just blend them and set up the final
7523 // shuffle to place them.
7525 // The first two blend mask elements are for V1, the second two are for
7527 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7528 Mask[2] < 4 ? Mask[2] : Mask[3],
7529 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7530 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7531 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7532 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7534 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7537 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7538 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7539 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7540 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7543 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7544 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7547 /// \brief Lower 4-lane 32-bit floating point shuffles.
7549 /// Uses instructions exclusively from the floating point unit to minimize
7550 /// domain crossing penalties, as these are sufficient to implement all v4f32
7552 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7553 const X86Subtarget *Subtarget,
7554 SelectionDAG &DAG) {
7556 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7557 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7558 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7559 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7560 ArrayRef<int> Mask = SVOp->getMask();
7561 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7564 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7566 if (NumV2Elements == 0) {
7567 // Check for being able to broadcast a single element.
7568 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7569 Mask, Subtarget, DAG))
7572 // Use even/odd duplicate instructions for masks that match their pattern.
7573 if (Subtarget->hasSSE3()) {
7574 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7575 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7576 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7577 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7580 if (Subtarget->hasAVX()) {
7581 // If we have AVX, we can use VPERMILPS which will allow folding a load
7582 // into the shuffle.
7583 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7584 getV4X86ShuffleImm8ForMask(Mask, DAG));
7587 // Otherwise, use a straight shuffle of a single input vector. We pass the
7588 // input vector to both operands to simulate this with a SHUFPS.
7589 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7590 getV4X86ShuffleImm8ForMask(Mask, DAG));
7593 // There are special ways we can lower some single-element blends. However, we
7594 // have custom ways we can lower more complex single-element blends below that
7595 // we defer to if both this and BLENDPS fail to match, so restrict this to
7596 // when the V2 input is targeting element 0 of the mask -- that is the fast
7598 if (NumV2Elements == 1 && Mask[0] >= 4)
7599 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7600 Mask, Subtarget, DAG))
7603 if (Subtarget->hasSSE41()) {
7604 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7608 // Use INSERTPS if we can complete the shuffle efficiently.
7609 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7612 if (!isSingleSHUFPSMask(Mask))
7613 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7614 DL, MVT::v4f32, V1, V2, Mask, DAG))
7618 // Use dedicated unpack instructions for masks that match their pattern.
7619 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7620 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7621 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7622 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7623 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7624 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7625 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7626 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7628 // Otherwise fall back to a SHUFPS lowering strategy.
7629 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7632 /// \brief Lower 4-lane i32 vector shuffles.
7634 /// We try to handle these with integer-domain shuffles where we can, but for
7635 /// blends we use the floating point domain blend instructions.
7636 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7637 const X86Subtarget *Subtarget,
7638 SelectionDAG &DAG) {
7640 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7641 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7642 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7643 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7644 ArrayRef<int> Mask = SVOp->getMask();
7645 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7647 // Whenever we can lower this as a zext, that instruction is strictly faster
7648 // than any alternative. It also allows us to fold memory operands into the
7649 // shuffle in many cases.
7650 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7651 Mask, Subtarget, DAG))
7655 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7657 if (NumV2Elements == 0) {
7658 // Check for being able to broadcast a single element.
7659 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7660 Mask, Subtarget, DAG))
7663 // Straight shuffle of a single input vector. For everything from SSE2
7664 // onward this has a single fast instruction with no scary immediates.
7665 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7666 // but we aren't actually going to use the UNPCK instruction because doing
7667 // so prevents folding a load into this instruction or making a copy.
7668 const int UnpackLoMask[] = {0, 0, 1, 1};
7669 const int UnpackHiMask[] = {2, 2, 3, 3};
7670 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7671 Mask = UnpackLoMask;
7672 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7673 Mask = UnpackHiMask;
7675 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7676 getV4X86ShuffleImm8ForMask(Mask, DAG));
7679 // Try to use shift instructions.
7681 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7684 // There are special ways we can lower some single-element blends.
7685 if (NumV2Elements == 1)
7686 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7687 Mask, Subtarget, DAG))
7690 // We have different paths for blend lowering, but they all must use the
7691 // *exact* same predicate.
7692 bool IsBlendSupported = Subtarget->hasSSE41();
7693 if (IsBlendSupported)
7694 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7698 if (SDValue Masked =
7699 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7702 // Use dedicated unpack instructions for masks that match their pattern.
7703 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7704 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7705 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7706 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7707 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7708 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7709 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7710 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7712 // Try to use byte rotation instructions.
7713 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7714 if (Subtarget->hasSSSE3())
7715 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7716 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7719 // If we have direct support for blends, we should lower by decomposing into
7720 // a permute. That will be faster than the domain cross.
7721 if (IsBlendSupported)
7722 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7725 // Try to lower by permuting the inputs into an unpack instruction.
7726 if (SDValue Unpack =
7727 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7730 // We implement this with SHUFPS because it can blend from two vectors.
7731 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7732 // up the inputs, bypassing domain shift penalties that we would encur if we
7733 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7735 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7736 DAG.getVectorShuffle(
7738 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7739 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7742 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7743 /// shuffle lowering, and the most complex part.
7745 /// The lowering strategy is to try to form pairs of input lanes which are
7746 /// targeted at the same half of the final vector, and then use a dword shuffle
7747 /// to place them onto the right half, and finally unpack the paired lanes into
7748 /// their final position.
7750 /// The exact breakdown of how to form these dword pairs and align them on the
7751 /// correct sides is really tricky. See the comments within the function for
7752 /// more of the details.
7754 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7755 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7756 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7757 /// vector, form the analogous 128-bit 8-element Mask.
7758 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7759 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7760 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7761 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7762 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7764 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7765 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7766 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7768 SmallVector<int, 4> LoInputs;
7769 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7770 [](int M) { return M >= 0; });
7771 std::sort(LoInputs.begin(), LoInputs.end());
7772 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7773 SmallVector<int, 4> HiInputs;
7774 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7775 [](int M) { return M >= 0; });
7776 std::sort(HiInputs.begin(), HiInputs.end());
7777 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7779 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7780 int NumHToL = LoInputs.size() - NumLToL;
7782 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7783 int NumHToH = HiInputs.size() - NumLToH;
7784 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7785 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7786 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7787 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7789 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7790 // such inputs we can swap two of the dwords across the half mark and end up
7791 // with <=2 inputs to each half in each half. Once there, we can fall through
7792 // to the generic code below. For example:
7794 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7795 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7797 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7798 // and an existing 2-into-2 on the other half. In this case we may have to
7799 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7800 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7801 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7802 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7803 // half than the one we target for fixing) will be fixed when we re-enter this
7804 // path. We will also combine away any sequence of PSHUFD instructions that
7805 // result into a single instruction. Here is an example of the tricky case:
7807 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7808 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7810 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7812 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7813 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7815 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7816 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7818 // The result is fine to be handled by the generic logic.
7819 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7820 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7821 int AOffset, int BOffset) {
7822 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7823 "Must call this with A having 3 or 1 inputs from the A half.");
7824 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7825 "Must call this with B having 1 or 3 inputs from the B half.");
7826 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7827 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7829 // Compute the index of dword with only one word among the three inputs in
7830 // a half by taking the sum of the half with three inputs and subtracting
7831 // the sum of the actual three inputs. The difference is the remaining
7834 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7835 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7836 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7837 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7838 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7839 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7840 int TripleNonInputIdx =
7841 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7842 TripleDWord = TripleNonInputIdx / 2;
7844 // We use xor with one to compute the adjacent DWord to whichever one the
7846 OneInputDWord = (OneInput / 2) ^ 1;
7848 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7849 // and BToA inputs. If there is also such a problem with the BToB and AToB
7850 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7851 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7852 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7853 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7854 // Compute how many inputs will be flipped by swapping these DWords. We
7856 // to balance this to ensure we don't form a 3-1 shuffle in the other
7858 int NumFlippedAToBInputs =
7859 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7860 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7861 int NumFlippedBToBInputs =
7862 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7863 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7864 if ((NumFlippedAToBInputs == 1 &&
7865 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7866 (NumFlippedBToBInputs == 1 &&
7867 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7868 // We choose whether to fix the A half or B half based on whether that
7869 // half has zero flipped inputs. At zero, we may not be able to fix it
7870 // with that half. We also bias towards fixing the B half because that
7871 // will more commonly be the high half, and we have to bias one way.
7872 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7873 ArrayRef<int> Inputs) {
7874 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7875 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7876 PinnedIdx ^ 1) != Inputs.end();
7877 // Determine whether the free index is in the flipped dword or the
7878 // unflipped dword based on where the pinned index is. We use this bit
7879 // in an xor to conditionally select the adjacent dword.
7880 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7881 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7882 FixFreeIdx) != Inputs.end();
7883 if (IsFixIdxInput == IsFixFreeIdxInput)
7885 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7886 FixFreeIdx) != Inputs.end();
7887 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7888 "We need to be changing the number of flipped inputs!");
7889 int PSHUFHalfMask[] = {0, 1, 2, 3};
7890 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7891 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7893 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7896 if (M != -1 && M == FixIdx)
7898 else if (M != -1 && M == FixFreeIdx)
7901 if (NumFlippedBToBInputs != 0) {
7903 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7904 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7906 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7908 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7909 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7914 int PSHUFDMask[] = {0, 1, 2, 3};
7915 PSHUFDMask[ADWord] = BDWord;
7916 PSHUFDMask[BDWord] = ADWord;
7917 V = DAG.getNode(ISD::BITCAST, DL, VT,
7918 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7919 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7920 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7922 // Adjust the mask to match the new locations of A and B.
7924 if (M != -1 && M/2 == ADWord)
7925 M = 2 * BDWord + M % 2;
7926 else if (M != -1 && M/2 == BDWord)
7927 M = 2 * ADWord + M % 2;
7929 // Recurse back into this routine to re-compute state now that this isn't
7930 // a 3 and 1 problem.
7931 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7934 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7935 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7936 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7937 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7939 // At this point there are at most two inputs to the low and high halves from
7940 // each half. That means the inputs can always be grouped into dwords and
7941 // those dwords can then be moved to the correct half with a dword shuffle.
7942 // We use at most one low and one high word shuffle to collect these paired
7943 // inputs into dwords, and finally a dword shuffle to place them.
7944 int PSHUFLMask[4] = {-1, -1, -1, -1};
7945 int PSHUFHMask[4] = {-1, -1, -1, -1};
7946 int PSHUFDMask[4] = {-1, -1, -1, -1};
7948 // First fix the masks for all the inputs that are staying in their
7949 // original halves. This will then dictate the targets of the cross-half
7951 auto fixInPlaceInputs =
7952 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7953 MutableArrayRef<int> SourceHalfMask,
7954 MutableArrayRef<int> HalfMask, int HalfOffset) {
7955 if (InPlaceInputs.empty())
7957 if (InPlaceInputs.size() == 1) {
7958 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7959 InPlaceInputs[0] - HalfOffset;
7960 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7963 if (IncomingInputs.empty()) {
7964 // Just fix all of the in place inputs.
7965 for (int Input : InPlaceInputs) {
7966 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7967 PSHUFDMask[Input / 2] = Input / 2;
7972 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7973 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7974 InPlaceInputs[0] - HalfOffset;
7975 // Put the second input next to the first so that they are packed into
7976 // a dword. We find the adjacent index by toggling the low bit.
7977 int AdjIndex = InPlaceInputs[0] ^ 1;
7978 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7979 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7980 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7982 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7983 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7985 // Now gather the cross-half inputs and place them into a free dword of
7986 // their target half.
7987 // FIXME: This operation could almost certainly be simplified dramatically to
7988 // look more like the 3-1 fixing operation.
7989 auto moveInputsToRightHalf = [&PSHUFDMask](
7990 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7991 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7992 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7994 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7995 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7997 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7999 int LowWord = Word & ~1;
8000 int HighWord = Word | 1;
8001 return isWordClobbered(SourceHalfMask, LowWord) ||
8002 isWordClobbered(SourceHalfMask, HighWord);
8005 if (IncomingInputs.empty())
8008 if (ExistingInputs.empty()) {
8009 // Map any dwords with inputs from them into the right half.
8010 for (int Input : IncomingInputs) {
8011 // If the source half mask maps over the inputs, turn those into
8012 // swaps and use the swapped lane.
8013 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8014 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8015 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8016 Input - SourceOffset;
8017 // We have to swap the uses in our half mask in one sweep.
8018 for (int &M : HalfMask)
8019 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8021 else if (M == Input)
8022 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8024 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8025 Input - SourceOffset &&
8026 "Previous placement doesn't match!");
8028 // Note that this correctly re-maps both when we do a swap and when
8029 // we observe the other side of the swap above. We rely on that to
8030 // avoid swapping the members of the input list directly.
8031 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8034 // Map the input's dword into the correct half.
8035 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8036 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8038 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8040 "Previous placement doesn't match!");
8043 // And just directly shift any other-half mask elements to be same-half
8044 // as we will have mirrored the dword containing the element into the
8045 // same position within that half.
8046 for (int &M : HalfMask)
8047 if (M >= SourceOffset && M < SourceOffset + 4) {
8048 M = M - SourceOffset + DestOffset;
8049 assert(M >= 0 && "This should never wrap below zero!");
8054 // Ensure we have the input in a viable dword of its current half. This
8055 // is particularly tricky because the original position may be clobbered
8056 // by inputs being moved and *staying* in that half.
8057 if (IncomingInputs.size() == 1) {
8058 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8059 int InputFixed = std::find(std::begin(SourceHalfMask),
8060 std::end(SourceHalfMask), -1) -
8061 std::begin(SourceHalfMask) + SourceOffset;
8062 SourceHalfMask[InputFixed - SourceOffset] =
8063 IncomingInputs[0] - SourceOffset;
8064 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8066 IncomingInputs[0] = InputFixed;
8068 } else if (IncomingInputs.size() == 2) {
8069 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8070 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8071 // We have two non-adjacent or clobbered inputs we need to extract from
8072 // the source half. To do this, we need to map them into some adjacent
8073 // dword slot in the source mask.
8074 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8075 IncomingInputs[1] - SourceOffset};
8077 // If there is a free slot in the source half mask adjacent to one of
8078 // the inputs, place the other input in it. We use (Index XOR 1) to
8079 // compute an adjacent index.
8080 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8081 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8082 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8083 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8084 InputsFixed[1] = InputsFixed[0] ^ 1;
8085 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8086 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8087 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8088 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8089 InputsFixed[0] = InputsFixed[1] ^ 1;
8090 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8091 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8092 // The two inputs are in the same DWord but it is clobbered and the
8093 // adjacent DWord isn't used at all. Move both inputs to the free
8095 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8096 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8097 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8098 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8100 // The only way we hit this point is if there is no clobbering
8101 // (because there are no off-half inputs to this half) and there is no
8102 // free slot adjacent to one of the inputs. In this case, we have to
8103 // swap an input with a non-input.
8104 for (int i = 0; i < 4; ++i)
8105 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8106 "We can't handle any clobbers here!");
8107 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8108 "Cannot have adjacent inputs here!");
8110 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8111 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8113 // We also have to update the final source mask in this case because
8114 // it may need to undo the above swap.
8115 for (int &M : FinalSourceHalfMask)
8116 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8117 M = InputsFixed[1] + SourceOffset;
8118 else if (M == InputsFixed[1] + SourceOffset)
8119 M = (InputsFixed[0] ^ 1) + SourceOffset;
8121 InputsFixed[1] = InputsFixed[0] ^ 1;
8124 // Point everything at the fixed inputs.
8125 for (int &M : HalfMask)
8126 if (M == IncomingInputs[0])
8127 M = InputsFixed[0] + SourceOffset;
8128 else if (M == IncomingInputs[1])
8129 M = InputsFixed[1] + SourceOffset;
8131 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8132 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8135 llvm_unreachable("Unhandled input size!");
8138 // Now hoist the DWord down to the right half.
8139 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8140 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8141 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8142 for (int &M : HalfMask)
8143 for (int Input : IncomingInputs)
8145 M = FreeDWord * 2 + Input % 2;
8147 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8148 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8149 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8150 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8152 // Now enact all the shuffles we've computed to move the inputs into their
8154 if (!isNoopShuffleMask(PSHUFLMask))
8155 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8156 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8157 if (!isNoopShuffleMask(PSHUFHMask))
8158 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8159 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8160 if (!isNoopShuffleMask(PSHUFDMask))
8161 V = DAG.getNode(ISD::BITCAST, DL, VT,
8162 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8163 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8164 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8166 // At this point, each half should contain all its inputs, and we can then
8167 // just shuffle them into their final position.
8168 assert(std::count_if(LoMask.begin(), LoMask.end(),
8169 [](int M) { return M >= 4; }) == 0 &&
8170 "Failed to lift all the high half inputs to the low mask!");
8171 assert(std::count_if(HiMask.begin(), HiMask.end(),
8172 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8173 "Failed to lift all the low half inputs to the high mask!");
8175 // Do a half shuffle for the low mask.
8176 if (!isNoopShuffleMask(LoMask))
8177 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8178 getV4X86ShuffleImm8ForMask(LoMask, DAG));
8180 // Do a half shuffle with the high mask after shifting its values down.
8181 for (int &M : HiMask)
8184 if (!isNoopShuffleMask(HiMask))
8185 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8186 getV4X86ShuffleImm8ForMask(HiMask, DAG));
8191 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8192 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8193 SDValue V2, ArrayRef<int> Mask,
8194 SelectionDAG &DAG, bool &V1InUse,
8196 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8202 int Size = Mask.size();
8203 int Scale = 16 / Size;
8204 for (int i = 0; i < 16; ++i) {
8205 if (Mask[i / Scale] == -1) {
8206 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8208 const int ZeroMask = 0x80;
8209 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8211 int V2Idx = Mask[i / Scale] < Size
8213 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8214 if (Zeroable[i / Scale])
8215 V1Idx = V2Idx = ZeroMask;
8216 V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8217 V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8218 V1InUse |= (ZeroMask != V1Idx);
8219 V2InUse |= (ZeroMask != V2Idx);
8224 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8225 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8226 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8228 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8229 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8230 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8232 // If we need shuffled inputs from both, blend the two.
8234 if (V1InUse && V2InUse)
8235 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8237 V = V1InUse ? V1 : V2;
8239 // Cast the result back to the correct type.
8240 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8243 /// \brief Generic lowering of 8-lane i16 shuffles.
8245 /// This handles both single-input shuffles and combined shuffle/blends with
8246 /// two inputs. The single input shuffles are immediately delegated to
8247 /// a dedicated lowering routine.
8249 /// The blends are lowered in one of three fundamental ways. If there are few
8250 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8251 /// of the input is significantly cheaper when lowered as an interleaving of
8252 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8253 /// halves of the inputs separately (making them have relatively few inputs)
8254 /// and then concatenate them.
8255 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8256 const X86Subtarget *Subtarget,
8257 SelectionDAG &DAG) {
8259 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8260 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8261 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8262 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8263 ArrayRef<int> OrigMask = SVOp->getMask();
8264 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8265 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8266 MutableArrayRef<int> Mask(MaskStorage);
8268 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8270 // Whenever we can lower this as a zext, that instruction is strictly faster
8271 // than any alternative.
8272 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8273 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8276 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8278 auto isV2 = [](int M) { return M >= 8; };
8280 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8282 if (NumV2Inputs == 0) {
8283 // Check for being able to broadcast a single element.
8284 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8285 Mask, Subtarget, DAG))
8288 // Try to use shift instructions.
8290 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8293 // Use dedicated unpack instructions for masks that match their pattern.
8294 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8295 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8296 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8297 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8299 // Try to use byte rotation instructions.
8300 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8301 Mask, Subtarget, DAG))
8304 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8308 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8309 "All single-input shuffles should be canonicalized to be V1-input "
8312 // Try to use shift instructions.
8314 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8317 // There are special ways we can lower some single-element blends.
8318 if (NumV2Inputs == 1)
8319 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8320 Mask, Subtarget, DAG))
8323 // We have different paths for blend lowering, but they all must use the
8324 // *exact* same predicate.
8325 bool IsBlendSupported = Subtarget->hasSSE41();
8326 if (IsBlendSupported)
8327 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8331 if (SDValue Masked =
8332 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8335 // Use dedicated unpack instructions for masks that match their pattern.
8336 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8337 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8338 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8339 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8341 // Try to use byte rotation instructions.
8342 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8343 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8346 if (SDValue BitBlend =
8347 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8350 if (SDValue Unpack =
8351 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8354 // If we can't directly blend but can use PSHUFB, that will be better as it
8355 // can both shuffle and set up the inefficient blend.
8356 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8357 bool V1InUse, V2InUse;
8358 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8362 // We can always bit-blend if we have to so the fallback strategy is to
8363 // decompose into single-input permutes and blends.
8364 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8368 /// \brief Check whether a compaction lowering can be done by dropping even
8369 /// elements and compute how many times even elements must be dropped.
8371 /// This handles shuffles which take every Nth element where N is a power of
8372 /// two. Example shuffle masks:
8374 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8375 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8376 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8377 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8378 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8379 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8381 /// Any of these lanes can of course be undef.
8383 /// This routine only supports N <= 3.
8384 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8387 /// \returns N above, or the number of times even elements must be dropped if
8388 /// there is such a number. Otherwise returns zero.
8389 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8390 // Figure out whether we're looping over two inputs or just one.
8391 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8393 // The modulus for the shuffle vector entries is based on whether this is
8394 // a single input or not.
8395 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8396 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8397 "We should only be called with masks with a power-of-2 size!");
8399 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8401 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8402 // and 2^3 simultaneously. This is because we may have ambiguity with
8403 // partially undef inputs.
8404 bool ViableForN[3] = {true, true, true};
8406 for (int i = 0, e = Mask.size(); i < e; ++i) {
8407 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8412 bool IsAnyViable = false;
8413 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8414 if (ViableForN[j]) {
8417 // The shuffle mask must be equal to (i * 2^N) % M.
8418 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8421 ViableForN[j] = false;
8423 // Early exit if we exhaust the possible powers of two.
8428 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8432 // Return 0 as there is no viable power of two.
8436 /// \brief Generic lowering of v16i8 shuffles.
8438 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8439 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8440 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8441 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8443 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8444 const X86Subtarget *Subtarget,
8445 SelectionDAG &DAG) {
8447 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8448 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8449 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8450 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8451 ArrayRef<int> Mask = SVOp->getMask();
8452 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8454 // Try to use shift instructions.
8456 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8459 // Try to use byte rotation instructions.
8460 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8461 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8464 // Try to use a zext lowering.
8465 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8466 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8470 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8472 // For single-input shuffles, there are some nicer lowering tricks we can use.
8473 if (NumV2Elements == 0) {
8474 // Check for being able to broadcast a single element.
8475 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8476 Mask, Subtarget, DAG))
8479 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8480 // Notably, this handles splat and partial-splat shuffles more efficiently.
8481 // However, it only makes sense if the pre-duplication shuffle simplifies
8482 // things significantly. Currently, this means we need to be able to
8483 // express the pre-duplication shuffle as an i16 shuffle.
8485 // FIXME: We should check for other patterns which can be widened into an
8486 // i16 shuffle as well.
8487 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8488 for (int i = 0; i < 16; i += 2)
8489 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8494 auto tryToWidenViaDuplication = [&]() -> SDValue {
8495 if (!canWidenViaDuplication(Mask))
8497 SmallVector<int, 4> LoInputs;
8498 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8499 [](int M) { return M >= 0 && M < 8; });
8500 std::sort(LoInputs.begin(), LoInputs.end());
8501 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8503 SmallVector<int, 4> HiInputs;
8504 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8505 [](int M) { return M >= 8; });
8506 std::sort(HiInputs.begin(), HiInputs.end());
8507 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8510 bool TargetLo = LoInputs.size() >= HiInputs.size();
8511 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8512 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8514 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8515 SmallDenseMap<int, int, 8> LaneMap;
8516 for (int I : InPlaceInputs) {
8517 PreDupI16Shuffle[I/2] = I/2;
8520 int j = TargetLo ? 0 : 4, je = j + 4;
8521 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8522 // Check if j is already a shuffle of this input. This happens when
8523 // there are two adjacent bytes after we move the low one.
8524 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8525 // If we haven't yet mapped the input, search for a slot into which
8527 while (j < je && PreDupI16Shuffle[j] != -1)
8531 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8534 // Map this input with the i16 shuffle.
8535 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8538 // Update the lane map based on the mapping we ended up with.
8539 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8542 ISD::BITCAST, DL, MVT::v16i8,
8543 DAG.getVectorShuffle(MVT::v8i16, DL,
8544 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8545 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8547 // Unpack the bytes to form the i16s that will be shuffled into place.
8548 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8549 MVT::v16i8, V1, V1);
8551 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8552 for (int i = 0; i < 16; ++i)
8553 if (Mask[i] != -1) {
8554 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8555 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8556 if (PostDupI16Shuffle[i / 2] == -1)
8557 PostDupI16Shuffle[i / 2] = MappedMask;
8559 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8560 "Conflicting entrties in the original shuffle!");
8563 ISD::BITCAST, DL, MVT::v16i8,
8564 DAG.getVectorShuffle(MVT::v8i16, DL,
8565 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8566 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8568 if (SDValue V = tryToWidenViaDuplication())
8572 // Use dedicated unpack instructions for masks that match their pattern.
8573 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8574 0, 16, 1, 17, 2, 18, 3, 19,
8576 4, 20, 5, 21, 6, 22, 7, 23}))
8577 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8578 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8579 8, 24, 9, 25, 10, 26, 11, 27,
8581 12, 28, 13, 29, 14, 30, 15, 31}))
8582 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8584 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8585 // with PSHUFB. It is important to do this before we attempt to generate any
8586 // blends but after all of the single-input lowerings. If the single input
8587 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8588 // want to preserve that and we can DAG combine any longer sequences into
8589 // a PSHUFB in the end. But once we start blending from multiple inputs,
8590 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8591 // and there are *very* few patterns that would actually be faster than the
8592 // PSHUFB approach because of its ability to zero lanes.
8594 // FIXME: The only exceptions to the above are blends which are exact
8595 // interleavings with direct instructions supporting them. We currently don't
8596 // handle those well here.
8597 if (Subtarget->hasSSSE3()) {
8598 bool V1InUse = false;
8599 bool V2InUse = false;
8601 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8602 DAG, V1InUse, V2InUse);
8604 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8605 // do so. This avoids using them to handle blends-with-zero which is
8606 // important as a single pshufb is significantly faster for that.
8607 if (V1InUse && V2InUse) {
8608 if (Subtarget->hasSSE41())
8609 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8610 Mask, Subtarget, DAG))
8613 // We can use an unpack to do the blending rather than an or in some
8614 // cases. Even though the or may be (very minorly) more efficient, we
8615 // preference this lowering because there are common cases where part of
8616 // the complexity of the shuffles goes away when we do the final blend as
8618 // FIXME: It might be worth trying to detect if the unpack-feeding
8619 // shuffles will both be pshufb, in which case we shouldn't bother with
8621 if (SDValue Unpack =
8622 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8629 // There are special ways we can lower some single-element blends.
8630 if (NumV2Elements == 1)
8631 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8632 Mask, Subtarget, DAG))
8635 if (SDValue BitBlend =
8636 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8639 // Check whether a compaction lowering can be done. This handles shuffles
8640 // which take every Nth element for some even N. See the helper function for
8643 // We special case these as they can be particularly efficiently handled with
8644 // the PACKUSB instruction on x86 and they show up in common patterns of
8645 // rearranging bytes to truncate wide elements.
8646 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8647 // NumEvenDrops is the power of two stride of the elements. Another way of
8648 // thinking about it is that we need to drop the even elements this many
8649 // times to get the original input.
8650 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8652 // First we need to zero all the dropped bytes.
8653 assert(NumEvenDrops <= 3 &&
8654 "No support for dropping even elements more than 3 times.");
8655 // We use the mask type to pick which bytes are preserved based on how many
8656 // elements are dropped.
8657 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8658 SDValue ByteClearMask =
8659 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8660 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8661 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8663 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8665 // Now pack things back together.
8666 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8667 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8668 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8669 for (int i = 1; i < NumEvenDrops; ++i) {
8670 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8671 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8677 // Handle multi-input cases by blending single-input shuffles.
8678 if (NumV2Elements > 0)
8679 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8682 // The fallback path for single-input shuffles widens this into two v8i16
8683 // vectors with unpacks, shuffles those, and then pulls them back together
8687 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8688 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8689 for (int i = 0; i < 16; ++i)
8691 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8693 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8695 SDValue VLoHalf, VHiHalf;
8696 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8697 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8699 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8700 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8701 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8702 [](int M) { return M >= 0 && M % 2 == 1; })) {
8703 // Use a mask to drop the high bytes.
8704 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8705 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8706 DAG.getConstant(0x00FF, MVT::v8i16));
8708 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8709 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8711 // Squash the masks to point directly into VLoHalf.
8712 for (int &M : LoBlendMask)
8715 for (int &M : HiBlendMask)
8719 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8720 // VHiHalf so that we can blend them as i16s.
8721 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8722 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8723 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8724 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8727 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8728 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8730 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8733 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8735 /// This routine breaks down the specific type of 128-bit shuffle and
8736 /// dispatches to the lowering routines accordingly.
8737 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8738 MVT VT, const X86Subtarget *Subtarget,
8739 SelectionDAG &DAG) {
8740 switch (VT.SimpleTy) {
8742 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8744 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8746 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8748 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8750 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8752 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8755 llvm_unreachable("Unimplemented!");
8759 /// \brief Helper function to test whether a shuffle mask could be
8760 /// simplified by widening the elements being shuffled.
8762 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8763 /// leaves it in an unspecified state.
8765 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8766 /// shuffle masks. The latter have the special property of a '-2' representing
8767 /// a zero-ed lane of a vector.
8768 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8769 SmallVectorImpl<int> &WidenedMask) {
8770 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8771 // If both elements are undef, its trivial.
8772 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8773 WidenedMask.push_back(SM_SentinelUndef);
8777 // Check for an undef mask and a mask value properly aligned to fit with
8778 // a pair of values. If we find such a case, use the non-undef mask's value.
8779 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8780 WidenedMask.push_back(Mask[i + 1] / 2);
8783 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8784 WidenedMask.push_back(Mask[i] / 2);
8788 // When zeroing, we need to spread the zeroing across both lanes to widen.
8789 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8790 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8791 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8792 WidenedMask.push_back(SM_SentinelZero);
8798 // Finally check if the two mask values are adjacent and aligned with
8800 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8801 WidenedMask.push_back(Mask[i] / 2);
8805 // Otherwise we can't safely widen the elements used in this shuffle.
8808 assert(WidenedMask.size() == Mask.size() / 2 &&
8809 "Incorrect size of mask after widening the elements!");
8814 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8816 /// This routine just extracts two subvectors, shuffles them independently, and
8817 /// then concatenates them back together. This should work effectively with all
8818 /// AVX vector shuffle types.
8819 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8820 SDValue V2, ArrayRef<int> Mask,
8821 SelectionDAG &DAG) {
8822 assert(VT.getSizeInBits() >= 256 &&
8823 "Only for 256-bit or wider vector shuffles!");
8824 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8825 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8827 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8828 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8830 int NumElements = VT.getVectorNumElements();
8831 int SplitNumElements = NumElements / 2;
8832 MVT ScalarVT = VT.getScalarType();
8833 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8835 // Rather than splitting build-vectors, just build two narrower build
8836 // vectors. This helps shuffling with splats and zeros.
8837 auto SplitVector = [&](SDValue V) {
8838 while (V.getOpcode() == ISD::BITCAST)
8839 V = V->getOperand(0);
8841 MVT OrigVT = V.getSimpleValueType();
8842 int OrigNumElements = OrigVT.getVectorNumElements();
8843 int OrigSplitNumElements = OrigNumElements / 2;
8844 MVT OrigScalarVT = OrigVT.getScalarType();
8845 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8849 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8851 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8852 DAG.getIntPtrConstant(0));
8853 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8854 DAG.getIntPtrConstant(OrigSplitNumElements));
8857 SmallVector<SDValue, 16> LoOps, HiOps;
8858 for (int i = 0; i < OrigSplitNumElements; ++i) {
8859 LoOps.push_back(BV->getOperand(i));
8860 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8862 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8863 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8865 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8866 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8869 SDValue LoV1, HiV1, LoV2, HiV2;
8870 std::tie(LoV1, HiV1) = SplitVector(V1);
8871 std::tie(LoV2, HiV2) = SplitVector(V2);
8873 // Now create two 4-way blends of these half-width vectors.
8874 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8875 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8876 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8877 for (int i = 0; i < SplitNumElements; ++i) {
8878 int M = HalfMask[i];
8879 if (M >= NumElements) {
8880 if (M >= NumElements + SplitNumElements)
8884 V2BlendMask.push_back(M - NumElements);
8885 V1BlendMask.push_back(-1);
8886 BlendMask.push_back(SplitNumElements + i);
8887 } else if (M >= 0) {
8888 if (M >= SplitNumElements)
8892 V2BlendMask.push_back(-1);
8893 V1BlendMask.push_back(M);
8894 BlendMask.push_back(i);
8896 V2BlendMask.push_back(-1);
8897 V1BlendMask.push_back(-1);
8898 BlendMask.push_back(-1);
8902 // Because the lowering happens after all combining takes place, we need to
8903 // manually combine these blend masks as much as possible so that we create
8904 // a minimal number of high-level vector shuffle nodes.
8906 // First try just blending the halves of V1 or V2.
8907 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8908 return DAG.getUNDEF(SplitVT);
8909 if (!UseLoV2 && !UseHiV2)
8910 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8911 if (!UseLoV1 && !UseHiV1)
8912 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8914 SDValue V1Blend, V2Blend;
8915 if (UseLoV1 && UseHiV1) {
8917 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8919 // We only use half of V1 so map the usage down into the final blend mask.
8920 V1Blend = UseLoV1 ? LoV1 : HiV1;
8921 for (int i = 0; i < SplitNumElements; ++i)
8922 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8923 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8925 if (UseLoV2 && UseHiV2) {
8927 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8929 // We only use half of V2 so map the usage down into the final blend mask.
8930 V2Blend = UseLoV2 ? LoV2 : HiV2;
8931 for (int i = 0; i < SplitNumElements; ++i)
8932 if (BlendMask[i] >= SplitNumElements)
8933 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8935 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8937 SDValue Lo = HalfBlend(LoMask);
8938 SDValue Hi = HalfBlend(HiMask);
8939 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8942 /// \brief Either split a vector in halves or decompose the shuffles and the
8945 /// This is provided as a good fallback for many lowerings of non-single-input
8946 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8947 /// between splitting the shuffle into 128-bit components and stitching those
8948 /// back together vs. extracting the single-input shuffles and blending those
8950 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8951 SDValue V2, ArrayRef<int> Mask,
8952 SelectionDAG &DAG) {
8953 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8954 "lower single-input shuffles as it "
8955 "could then recurse on itself.");
8956 int Size = Mask.size();
8958 // If this can be modeled as a broadcast of two elements followed by a blend,
8959 // prefer that lowering. This is especially important because broadcasts can
8960 // often fold with memory operands.
8961 auto DoBothBroadcast = [&] {
8962 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8965 if (V2BroadcastIdx == -1)
8966 V2BroadcastIdx = M - Size;
8967 else if (M - Size != V2BroadcastIdx)
8969 } else if (M >= 0) {
8970 if (V1BroadcastIdx == -1)
8972 else if (M != V1BroadcastIdx)
8977 if (DoBothBroadcast())
8978 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8981 // If the inputs all stem from a single 128-bit lane of each input, then we
8982 // split them rather than blending because the split will decompose to
8983 // unusually few instructions.
8984 int LaneCount = VT.getSizeInBits() / 128;
8985 int LaneSize = Size / LaneCount;
8986 SmallBitVector LaneInputs[2];
8987 LaneInputs[0].resize(LaneCount, false);
8988 LaneInputs[1].resize(LaneCount, false);
8989 for (int i = 0; i < Size; ++i)
8991 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8992 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8993 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8995 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8996 // that the decomposed single-input shuffles don't end up here.
8997 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9000 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9001 /// a permutation and blend of those lanes.
9003 /// This essentially blends the out-of-lane inputs to each lane into the lane
9004 /// from a permuted copy of the vector. This lowering strategy results in four
9005 /// instructions in the worst case for a single-input cross lane shuffle which
9006 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9007 /// of. Special cases for each particular shuffle pattern should be handled
9008 /// prior to trying this lowering.
9009 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9010 SDValue V1, SDValue V2,
9012 SelectionDAG &DAG) {
9013 // FIXME: This should probably be generalized for 512-bit vectors as well.
9014 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9015 int LaneSize = Mask.size() / 2;
9017 // If there are only inputs from one 128-bit lane, splitting will in fact be
9018 // less expensive. The flags track whether the given lane contains an element
9019 // that crosses to another lane.
9020 bool LaneCrossing[2] = {false, false};
9021 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9022 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9023 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9024 if (!LaneCrossing[0] || !LaneCrossing[1])
9025 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9027 if (isSingleInputShuffleMask(Mask)) {
9028 SmallVector<int, 32> FlippedBlendMask;
9029 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9030 FlippedBlendMask.push_back(
9031 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9033 : Mask[i] % LaneSize +
9034 (i / LaneSize) * LaneSize + Size));
9036 // Flip the vector, and blend the results which should now be in-lane. The
9037 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9038 // 5 for the high source. The value 3 selects the high half of source 2 and
9039 // the value 2 selects the low half of source 2. We only use source 2 to
9040 // allow folding it into a memory operand.
9041 unsigned PERMMask = 3 | 2 << 4;
9042 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9043 V1, DAG.getConstant(PERMMask, MVT::i8));
9044 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9047 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9048 // will be handled by the above logic and a blend of the results, much like
9049 // other patterns in AVX.
9050 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9053 /// \brief Handle lowering 2-lane 128-bit shuffles.
9054 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9055 SDValue V2, ArrayRef<int> Mask,
9056 const X86Subtarget *Subtarget,
9057 SelectionDAG &DAG) {
9058 // Blends are faster and handle all the non-lane-crossing cases.
9059 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9063 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9064 VT.getVectorNumElements() / 2);
9065 // Check for patterns which can be matched with a single insert of a 128-bit
9067 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9068 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9069 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9070 DAG.getIntPtrConstant(0));
9071 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9072 OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9073 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9075 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9076 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9077 DAG.getIntPtrConstant(0));
9078 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9079 DAG.getIntPtrConstant(2));
9080 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9083 // Otherwise form a 128-bit permutation.
9084 // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9085 int MaskLO = Mask[0];
9086 if (MaskLO == SM_SentinelUndef)
9087 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9089 int MaskHI = Mask[2];
9090 if (MaskHI == SM_SentinelUndef)
9091 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9093 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9094 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9095 DAG.getConstant(PermMask, MVT::i8));
9098 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9099 /// shuffling each lane.
9101 /// This will only succeed when the result of fixing the 128-bit lanes results
9102 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9103 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9104 /// the lane crosses early and then use simpler shuffles within each lane.
9106 /// FIXME: It might be worthwhile at some point to support this without
9107 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9108 /// in x86 only floating point has interesting non-repeating shuffles, and even
9109 /// those are still *marginally* more expensive.
9110 static SDValue lowerVectorShuffleByMerging128BitLanes(
9111 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9112 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9113 assert(!isSingleInputShuffleMask(Mask) &&
9114 "This is only useful with multiple inputs.");
9116 int Size = Mask.size();
9117 int LaneSize = 128 / VT.getScalarSizeInBits();
9118 int NumLanes = Size / LaneSize;
9119 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9121 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9122 // check whether the in-128-bit lane shuffles share a repeating pattern.
9123 SmallVector<int, 4> Lanes;
9124 Lanes.resize(NumLanes, -1);
9125 SmallVector<int, 4> InLaneMask;
9126 InLaneMask.resize(LaneSize, -1);
9127 for (int i = 0; i < Size; ++i) {
9131 int j = i / LaneSize;
9134 // First entry we've seen for this lane.
9135 Lanes[j] = Mask[i] / LaneSize;
9136 } else if (Lanes[j] != Mask[i] / LaneSize) {
9137 // This doesn't match the lane selected previously!
9141 // Check that within each lane we have a consistent shuffle mask.
9142 int k = i % LaneSize;
9143 if (InLaneMask[k] < 0) {
9144 InLaneMask[k] = Mask[i] % LaneSize;
9145 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9146 // This doesn't fit a repeating in-lane mask.
9151 // First shuffle the lanes into place.
9152 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9153 VT.getSizeInBits() / 64);
9154 SmallVector<int, 8> LaneMask;
9155 LaneMask.resize(NumLanes * 2, -1);
9156 for (int i = 0; i < NumLanes; ++i)
9157 if (Lanes[i] >= 0) {
9158 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9159 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9162 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9163 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9164 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9166 // Cast it back to the type we actually want.
9167 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9169 // Now do a simple shuffle that isn't lane crossing.
9170 SmallVector<int, 8> NewMask;
9171 NewMask.resize(Size, -1);
9172 for (int i = 0; i < Size; ++i)
9174 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9175 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9176 "Must not introduce lane crosses at this point!");
9178 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9181 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9184 /// This returns true if the elements from a particular input are already in the
9185 /// slot required by the given mask and require no permutation.
9186 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9187 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9188 int Size = Mask.size();
9189 for (int i = 0; i < Size; ++i)
9190 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9196 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9198 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9199 /// isn't available.
9200 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9201 const X86Subtarget *Subtarget,
9202 SelectionDAG &DAG) {
9204 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9205 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9206 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9207 ArrayRef<int> Mask = SVOp->getMask();
9208 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9210 SmallVector<int, 4> WidenedMask;
9211 if (canWidenShuffleElements(Mask, WidenedMask))
9212 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9215 if (isSingleInputShuffleMask(Mask)) {
9216 // Check for being able to broadcast a single element.
9217 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9218 Mask, Subtarget, DAG))
9221 // Use low duplicate instructions for masks that match their pattern.
9222 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9223 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9225 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9226 // Non-half-crossing single input shuffles can be lowerid with an
9227 // interleaved permutation.
9228 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9229 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9230 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9231 DAG.getConstant(VPERMILPMask, MVT::i8));
9234 // With AVX2 we have direct support for this permutation.
9235 if (Subtarget->hasAVX2())
9236 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9237 getV4X86ShuffleImm8ForMask(Mask, DAG));
9239 // Otherwise, fall back.
9240 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9244 // X86 has dedicated unpack instructions that can handle specific blend
9245 // operations: UNPCKH and UNPCKL.
9246 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9247 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9248 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9249 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9250 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9251 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9252 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9253 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9255 // If we have a single input to the zero element, insert that into V1 if we
9256 // can do so cheaply.
9258 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9259 if (NumV2Elements == 1 && Mask[0] >= 4)
9260 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9261 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9264 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9268 // Check if the blend happens to exactly fit that of SHUFPD.
9269 if ((Mask[0] == -1 || Mask[0] < 2) &&
9270 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9271 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9272 (Mask[3] == -1 || Mask[3] >= 6)) {
9273 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9274 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9275 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9276 DAG.getConstant(SHUFPDMask, MVT::i8));
9278 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9279 (Mask[1] == -1 || Mask[1] < 2) &&
9280 (Mask[2] == -1 || Mask[2] >= 6) &&
9281 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9282 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9283 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9284 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9285 DAG.getConstant(SHUFPDMask, MVT::i8));
9288 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9289 // shuffle. However, if we have AVX2 and either inputs are already in place,
9290 // we will be able to shuffle even across lanes the other input in a single
9291 // instruction so skip this pattern.
9292 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9293 isShuffleMaskInputInPlace(1, Mask))))
9294 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9295 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9298 // If we have AVX2 then we always want to lower with a blend because an v4 we
9299 // can fully permute the elements.
9300 if (Subtarget->hasAVX2())
9301 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9304 // Otherwise fall back on generic lowering.
9305 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9308 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9310 /// This routine is only called when we have AVX2 and thus a reasonable
9311 /// instruction set for v4i64 shuffling..
9312 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9313 const X86Subtarget *Subtarget,
9314 SelectionDAG &DAG) {
9316 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9317 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9318 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9319 ArrayRef<int> Mask = SVOp->getMask();
9320 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9321 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9323 SmallVector<int, 4> WidenedMask;
9324 if (canWidenShuffleElements(Mask, WidenedMask))
9325 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9328 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9332 // Check for being able to broadcast a single element.
9333 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9334 Mask, Subtarget, DAG))
9337 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9338 // use lower latency instructions that will operate on both 128-bit lanes.
9339 SmallVector<int, 2> RepeatedMask;
9340 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9341 if (isSingleInputShuffleMask(Mask)) {
9342 int PSHUFDMask[] = {-1, -1, -1, -1};
9343 for (int i = 0; i < 2; ++i)
9344 if (RepeatedMask[i] >= 0) {
9345 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9346 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9349 ISD::BITCAST, DL, MVT::v4i64,
9350 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9351 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9352 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9356 // AVX2 provides a direct instruction for permuting a single input across
9358 if (isSingleInputShuffleMask(Mask))
9359 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9360 getV4X86ShuffleImm8ForMask(Mask, DAG));
9362 // Try to use shift instructions.
9364 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9367 // Use dedicated unpack instructions for masks that match their pattern.
9368 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9369 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9370 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9371 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9372 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9373 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9374 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9375 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9377 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9378 // shuffle. However, if we have AVX2 and either inputs are already in place,
9379 // we will be able to shuffle even across lanes the other input in a single
9380 // instruction so skip this pattern.
9381 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9382 isShuffleMaskInputInPlace(1, Mask))))
9383 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9384 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9387 // Otherwise fall back on generic blend lowering.
9388 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9392 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9394 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9395 /// isn't available.
9396 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9397 const X86Subtarget *Subtarget,
9398 SelectionDAG &DAG) {
9400 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9401 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9402 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9403 ArrayRef<int> Mask = SVOp->getMask();
9404 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9406 // If we have a single input to the zero element, insert that into V1 if we
9407 // can do so cheaply.
9409 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 8; });
9410 if (NumV2Elements == 1 && Mask[0] >= 8)
9411 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9412 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9415 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9419 // Check for being able to broadcast a single element.
9420 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9421 Mask, Subtarget, DAG))
9424 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9425 // options to efficiently lower the shuffle.
9426 SmallVector<int, 4> RepeatedMask;
9427 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9428 assert(RepeatedMask.size() == 4 &&
9429 "Repeated masks must be half the mask width!");
9431 // Use even/odd duplicate instructions for masks that match their pattern.
9432 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9433 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9434 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9435 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9437 if (isSingleInputShuffleMask(Mask))
9438 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9439 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9441 // Use dedicated unpack instructions for masks that match their pattern.
9442 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9443 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9444 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9445 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9446 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9447 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9448 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9449 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9451 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9452 // have already handled any direct blends. We also need to squash the
9453 // repeated mask into a simulated v4f32 mask.
9454 for (int i = 0; i < 4; ++i)
9455 if (RepeatedMask[i] >= 8)
9456 RepeatedMask[i] -= 4;
9457 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9460 // If we have a single input shuffle with different shuffle patterns in the
9461 // two 128-bit lanes use the variable mask to VPERMILPS.
9462 if (isSingleInputShuffleMask(Mask)) {
9463 SDValue VPermMask[8];
9464 for (int i = 0; i < 8; ++i)
9465 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9466 : DAG.getConstant(Mask[i], MVT::i32);
9467 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9469 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9470 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9472 if (Subtarget->hasAVX2())
9473 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9474 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9475 DAG.getNode(ISD::BUILD_VECTOR, DL,
9476 MVT::v8i32, VPermMask)),
9479 // Otherwise, fall back.
9480 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9484 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9486 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9487 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9490 // If we have AVX2 then we always want to lower with a blend because at v8 we
9491 // can fully permute the elements.
9492 if (Subtarget->hasAVX2())
9493 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9496 // Otherwise fall back on generic lowering.
9497 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9500 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9502 /// This routine is only called when we have AVX2 and thus a reasonable
9503 /// instruction set for v8i32 shuffling..
9504 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9505 const X86Subtarget *Subtarget,
9506 SelectionDAG &DAG) {
9508 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9509 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9510 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9511 ArrayRef<int> Mask = SVOp->getMask();
9512 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9513 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9515 // Whenever we can lower this as a zext, that instruction is strictly faster
9516 // than any alternative. It also allows us to fold memory operands into the
9517 // shuffle in many cases.
9518 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9519 Mask, Subtarget, DAG))
9522 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9526 // Check for being able to broadcast a single element.
9527 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9528 Mask, Subtarget, DAG))
9531 // If the shuffle mask is repeated in each 128-bit lane we can use more
9532 // efficient instructions that mirror the shuffles across the two 128-bit
9534 SmallVector<int, 4> RepeatedMask;
9535 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9536 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9537 if (isSingleInputShuffleMask(Mask))
9538 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9539 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9541 // Use dedicated unpack instructions for masks that match their pattern.
9542 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9543 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9544 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9545 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9546 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9547 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9548 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9549 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9552 // Try to use shift instructions.
9554 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9557 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9558 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9561 // If the shuffle patterns aren't repeated but it is a single input, directly
9562 // generate a cross-lane VPERMD instruction.
9563 if (isSingleInputShuffleMask(Mask)) {
9564 SDValue VPermMask[8];
9565 for (int i = 0; i < 8; ++i)
9566 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9567 : DAG.getConstant(Mask[i], MVT::i32);
9569 X86ISD::VPERMV, DL, MVT::v8i32,
9570 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9573 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9575 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9576 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9579 // Otherwise fall back on generic blend lowering.
9580 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9584 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9586 /// This routine is only called when we have AVX2 and thus a reasonable
9587 /// instruction set for v16i16 shuffling..
9588 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9589 const X86Subtarget *Subtarget,
9590 SelectionDAG &DAG) {
9592 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9593 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9594 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9595 ArrayRef<int> Mask = SVOp->getMask();
9596 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9597 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9599 // Whenever we can lower this as a zext, that instruction is strictly faster
9600 // than any alternative. It also allows us to fold memory operands into the
9601 // shuffle in many cases.
9602 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9603 Mask, Subtarget, DAG))
9606 // Check for being able to broadcast a single element.
9607 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9608 Mask, Subtarget, DAG))
9611 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9615 // Use dedicated unpack instructions for masks that match their pattern.
9616 if (isShuffleEquivalent(V1, V2, Mask,
9617 {// First 128-bit lane:
9618 0, 16, 1, 17, 2, 18, 3, 19,
9619 // Second 128-bit lane:
9620 8, 24, 9, 25, 10, 26, 11, 27}))
9621 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9622 if (isShuffleEquivalent(V1, V2, Mask,
9623 {// First 128-bit lane:
9624 4, 20, 5, 21, 6, 22, 7, 23,
9625 // Second 128-bit lane:
9626 12, 28, 13, 29, 14, 30, 15, 31}))
9627 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9629 // Try to use shift instructions.
9631 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9634 // Try to use byte rotation instructions.
9635 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9636 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9639 if (isSingleInputShuffleMask(Mask)) {
9640 // There are no generalized cross-lane shuffle operations available on i16
9642 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9643 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9646 SmallVector<int, 8> RepeatedMask;
9647 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9648 // As this is a single-input shuffle, the repeated mask should be
9649 // a strictly valid v8i16 mask that we can pass through to the v8i16
9650 // lowering to handle even the v16 case.
9651 return lowerV8I16GeneralSingleInputVectorShuffle(
9652 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9655 SDValue PSHUFBMask[32];
9656 for (int i = 0; i < 16; ++i) {
9657 if (Mask[i] == -1) {
9658 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9662 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9663 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9664 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9665 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9668 ISD::BITCAST, DL, MVT::v16i16,
9670 X86ISD::PSHUFB, DL, MVT::v32i8,
9671 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9672 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9675 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9677 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9678 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9681 // Otherwise fall back on generic lowering.
9682 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9685 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9687 /// This routine is only called when we have AVX2 and thus a reasonable
9688 /// instruction set for v32i8 shuffling..
9689 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9690 const X86Subtarget *Subtarget,
9691 SelectionDAG &DAG) {
9693 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9694 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9695 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9696 ArrayRef<int> Mask = SVOp->getMask();
9697 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9698 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9700 // Whenever we can lower this as a zext, that instruction is strictly faster
9701 // than any alternative. It also allows us to fold memory operands into the
9702 // shuffle in many cases.
9703 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9704 Mask, Subtarget, DAG))
9707 // Check for being able to broadcast a single element.
9708 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9709 Mask, Subtarget, DAG))
9712 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9716 // Use dedicated unpack instructions for masks that match their pattern.
9717 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9719 if (isShuffleEquivalent(
9721 {// First 128-bit lane:
9722 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9723 // Second 128-bit lane:
9724 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9725 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9726 if (isShuffleEquivalent(
9728 {// First 128-bit lane:
9729 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9730 // Second 128-bit lane:
9731 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9732 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9734 // Try to use shift instructions.
9736 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9739 // Try to use byte rotation instructions.
9740 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9741 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9744 if (isSingleInputShuffleMask(Mask)) {
9745 // There are no generalized cross-lane shuffle operations available on i8
9747 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9748 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9751 SDValue PSHUFBMask[32];
9752 for (int i = 0; i < 32; ++i)
9755 ? DAG.getUNDEF(MVT::i8)
9756 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9759 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9760 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9763 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9765 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9766 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9769 // Otherwise fall back on generic lowering.
9770 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9773 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9775 /// This routine either breaks down the specific type of a 256-bit x86 vector
9776 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9777 /// together based on the available instructions.
9778 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9779 MVT VT, const X86Subtarget *Subtarget,
9780 SelectionDAG &DAG) {
9782 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9783 ArrayRef<int> Mask = SVOp->getMask();
9785 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9786 // check for those subtargets here and avoid much of the subtarget querying in
9787 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9788 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9789 // floating point types there eventually, just immediately cast everything to
9790 // a float and operate entirely in that domain.
9791 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9792 int ElementBits = VT.getScalarSizeInBits();
9793 if (ElementBits < 32)
9794 // No floating point type available, decompose into 128-bit vectors.
9795 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9797 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9798 VT.getVectorNumElements());
9799 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9800 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9801 return DAG.getNode(ISD::BITCAST, DL, VT,
9802 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9805 switch (VT.SimpleTy) {
9807 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9809 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9811 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9813 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9815 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9817 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9820 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9824 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9825 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9826 const X86Subtarget *Subtarget,
9827 SelectionDAG &DAG) {
9829 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9830 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9831 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9832 ArrayRef<int> Mask = SVOp->getMask();
9833 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9835 // X86 has dedicated unpack instructions that can handle specific blend
9836 // operations: UNPCKH and UNPCKL.
9837 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9838 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9839 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9840 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9842 // FIXME: Implement direct support for this type!
9843 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9846 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9847 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9848 const X86Subtarget *Subtarget,
9849 SelectionDAG &DAG) {
9851 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9852 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9853 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9854 ArrayRef<int> Mask = SVOp->getMask();
9855 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9857 // Use dedicated unpack instructions for masks that match their pattern.
9858 if (isShuffleEquivalent(V1, V2, Mask,
9859 {// First 128-bit lane.
9860 0, 16, 1, 17, 4, 20, 5, 21,
9861 // Second 128-bit lane.
9862 8, 24, 9, 25, 12, 28, 13, 29}))
9863 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9864 if (isShuffleEquivalent(V1, V2, Mask,
9865 {// First 128-bit lane.
9866 2, 18, 3, 19, 6, 22, 7, 23,
9867 // Second 128-bit lane.
9868 10, 26, 11, 27, 14, 30, 15, 31}))
9869 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9871 // FIXME: Implement direct support for this type!
9872 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9875 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9876 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9877 const X86Subtarget *Subtarget,
9878 SelectionDAG &DAG) {
9880 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9881 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9882 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9883 ArrayRef<int> Mask = SVOp->getMask();
9884 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9886 // X86 has dedicated unpack instructions that can handle specific blend
9887 // operations: UNPCKH and UNPCKL.
9888 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9889 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9890 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9891 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9893 // FIXME: Implement direct support for this type!
9894 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9897 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9898 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9899 const X86Subtarget *Subtarget,
9900 SelectionDAG &DAG) {
9902 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9903 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9904 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9905 ArrayRef<int> Mask = SVOp->getMask();
9906 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9908 // Use dedicated unpack instructions for masks that match their pattern.
9909 if (isShuffleEquivalent(V1, V2, Mask,
9910 {// First 128-bit lane.
9911 0, 16, 1, 17, 4, 20, 5, 21,
9912 // Second 128-bit lane.
9913 8, 24, 9, 25, 12, 28, 13, 29}))
9914 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9915 if (isShuffleEquivalent(V1, V2, Mask,
9916 {// First 128-bit lane.
9917 2, 18, 3, 19, 6, 22, 7, 23,
9918 // Second 128-bit lane.
9919 10, 26, 11, 27, 14, 30, 15, 31}))
9920 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9922 // FIXME: Implement direct support for this type!
9923 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9926 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9927 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9928 const X86Subtarget *Subtarget,
9929 SelectionDAG &DAG) {
9931 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9932 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9933 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9934 ArrayRef<int> Mask = SVOp->getMask();
9935 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9936 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9938 // FIXME: Implement direct support for this type!
9939 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9942 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9943 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9944 const X86Subtarget *Subtarget,
9945 SelectionDAG &DAG) {
9947 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9948 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9949 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9950 ArrayRef<int> Mask = SVOp->getMask();
9951 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9952 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9954 // FIXME: Implement direct support for this type!
9955 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9958 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9960 /// This routine either breaks down the specific type of a 512-bit x86 vector
9961 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9962 /// together based on the available instructions.
9963 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9964 MVT VT, const X86Subtarget *Subtarget,
9965 SelectionDAG &DAG) {
9967 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9968 ArrayRef<int> Mask = SVOp->getMask();
9969 assert(Subtarget->hasAVX512() &&
9970 "Cannot lower 512-bit vectors w/ basic ISA!");
9972 // Check for being able to broadcast a single element.
9973 if (SDValue Broadcast =
9974 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9977 // Dispatch to each element type for lowering. If we don't have supprot for
9978 // specific element type shuffles at 512 bits, immediately split them and
9979 // lower them. Each lowering routine of a given type is allowed to assume that
9980 // the requisite ISA extensions for that element type are available.
9981 switch (VT.SimpleTy) {
9983 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9985 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9987 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9989 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9991 if (Subtarget->hasBWI())
9992 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9995 if (Subtarget->hasBWI())
9996 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10000 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10003 // Otherwise fall back on splitting.
10004 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10007 /// \brief Top-level lowering for x86 vector shuffles.
10009 /// This handles decomposition, canonicalization, and lowering of all x86
10010 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10011 /// above in helper routines. The canonicalization attempts to widen shuffles
10012 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10013 /// s.t. only one of the two inputs needs to be tested, etc.
10014 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10015 SelectionDAG &DAG) {
10016 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10017 ArrayRef<int> Mask = SVOp->getMask();
10018 SDValue V1 = Op.getOperand(0);
10019 SDValue V2 = Op.getOperand(1);
10020 MVT VT = Op.getSimpleValueType();
10021 int NumElements = VT.getVectorNumElements();
10024 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10026 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10027 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10028 if (V1IsUndef && V2IsUndef)
10029 return DAG.getUNDEF(VT);
10031 // When we create a shuffle node we put the UNDEF node to second operand,
10032 // but in some cases the first operand may be transformed to UNDEF.
10033 // In this case we should just commute the node.
10035 return DAG.getCommutedVectorShuffle(*SVOp);
10037 // Check for non-undef masks pointing at an undef vector and make the masks
10038 // undef as well. This makes it easier to match the shuffle based solely on
10042 if (M >= NumElements) {
10043 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10044 for (int &M : NewMask)
10045 if (M >= NumElements)
10047 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10050 // We actually see shuffles that are entirely re-arrangements of a set of
10051 // zero inputs. This mostly happens while decomposing complex shuffles into
10052 // simple ones. Directly lower these as a buildvector of zeros.
10053 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10054 if (Zeroable.all())
10055 return getZeroVector(VT, Subtarget, DAG, dl);
10057 // Try to collapse shuffles into using a vector type with fewer elements but
10058 // wider element types. We cap this to not form integers or floating point
10059 // elements wider than 64 bits, but it might be interesting to form i128
10060 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10061 SmallVector<int, 16> WidenedMask;
10062 if (VT.getScalarSizeInBits() < 64 &&
10063 canWidenShuffleElements(Mask, WidenedMask)) {
10064 MVT NewEltVT = VT.isFloatingPoint()
10065 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10066 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10067 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10068 // Make sure that the new vector type is legal. For example, v2f64 isn't
10070 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10071 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10072 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10073 return DAG.getNode(ISD::BITCAST, dl, VT,
10074 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10078 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10079 for (int M : SVOp->getMask())
10081 ++NumUndefElements;
10082 else if (M < NumElements)
10087 // Commute the shuffle as needed such that more elements come from V1 than
10088 // V2. This allows us to match the shuffle pattern strictly on how many
10089 // elements come from V1 without handling the symmetric cases.
10090 if (NumV2Elements > NumV1Elements)
10091 return DAG.getCommutedVectorShuffle(*SVOp);
10093 // When the number of V1 and V2 elements are the same, try to minimize the
10094 // number of uses of V2 in the low half of the vector. When that is tied,
10095 // ensure that the sum of indices for V1 is equal to or lower than the sum
10096 // indices for V2. When those are equal, try to ensure that the number of odd
10097 // indices for V1 is lower than the number of odd indices for V2.
10098 if (NumV1Elements == NumV2Elements) {
10099 int LowV1Elements = 0, LowV2Elements = 0;
10100 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10101 if (M >= NumElements)
10105 if (LowV2Elements > LowV1Elements) {
10106 return DAG.getCommutedVectorShuffle(*SVOp);
10107 } else if (LowV2Elements == LowV1Elements) {
10108 int SumV1Indices = 0, SumV2Indices = 0;
10109 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10110 if (SVOp->getMask()[i] >= NumElements)
10112 else if (SVOp->getMask()[i] >= 0)
10114 if (SumV2Indices < SumV1Indices) {
10115 return DAG.getCommutedVectorShuffle(*SVOp);
10116 } else if (SumV2Indices == SumV1Indices) {
10117 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10118 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10119 if (SVOp->getMask()[i] >= NumElements)
10120 NumV2OddIndices += i % 2;
10121 else if (SVOp->getMask()[i] >= 0)
10122 NumV1OddIndices += i % 2;
10123 if (NumV2OddIndices < NumV1OddIndices)
10124 return DAG.getCommutedVectorShuffle(*SVOp);
10129 // For each vector width, delegate to a specialized lowering routine.
10130 if (VT.getSizeInBits() == 128)
10131 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10133 if (VT.getSizeInBits() == 256)
10134 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10136 // Force AVX-512 vectors to be scalarized for now.
10137 // FIXME: Implement AVX-512 support!
10138 if (VT.getSizeInBits() == 512)
10139 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10141 llvm_unreachable("Unimplemented!");
10144 // This function assumes its argument is a BUILD_VECTOR of constants or
10145 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10147 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10148 unsigned &MaskValue) {
10150 unsigned NumElems = BuildVector->getNumOperands();
10151 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10152 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10153 unsigned NumElemsInLane = NumElems / NumLanes;
10155 // Blend for v16i16 should be symetric for the both lanes.
10156 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10157 SDValue EltCond = BuildVector->getOperand(i);
10158 SDValue SndLaneEltCond =
10159 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10161 int Lane1Cond = -1, Lane2Cond = -1;
10162 if (isa<ConstantSDNode>(EltCond))
10163 Lane1Cond = !isZero(EltCond);
10164 if (isa<ConstantSDNode>(SndLaneEltCond))
10165 Lane2Cond = !isZero(SndLaneEltCond);
10167 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10168 // Lane1Cond != 0, means we want the first argument.
10169 // Lane1Cond == 0, means we want the second argument.
10170 // The encoding of this argument is 0 for the first argument, 1
10171 // for the second. Therefore, invert the condition.
10172 MaskValue |= !Lane1Cond << i;
10173 else if (Lane1Cond < 0)
10174 MaskValue |= !Lane2Cond << i;
10181 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10182 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10183 const X86Subtarget *Subtarget,
10184 SelectionDAG &DAG) {
10185 SDValue Cond = Op.getOperand(0);
10186 SDValue LHS = Op.getOperand(1);
10187 SDValue RHS = Op.getOperand(2);
10189 MVT VT = Op.getSimpleValueType();
10191 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10193 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10195 // Only non-legal VSELECTs reach this lowering, convert those into generic
10196 // shuffles and re-use the shuffle lowering path for blends.
10197 SmallVector<int, 32> Mask;
10198 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10199 SDValue CondElt = CondBV->getOperand(i);
10201 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10203 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10206 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10207 // A vselect where all conditions and data are constants can be optimized into
10208 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10209 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10210 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10211 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10214 // Try to lower this to a blend-style vector shuffle. This can handle all
10215 // constant condition cases.
10216 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10219 // Variable blends are only legal from SSE4.1 onward.
10220 if (!Subtarget->hasSSE41())
10223 // Only some types will be legal on some subtargets. If we can emit a legal
10224 // VSELECT-matching blend, return Op, and but if we need to expand, return
10226 switch (Op.getSimpleValueType().SimpleTy) {
10228 // Most of the vector types have blends past SSE4.1.
10232 // The byte blends for AVX vectors were introduced only in AVX2.
10233 if (Subtarget->hasAVX2())
10240 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10241 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10244 // FIXME: We should custom lower this by fixing the condition and using i8
10250 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10251 MVT VT = Op.getSimpleValueType();
10254 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10257 if (VT.getSizeInBits() == 8) {
10258 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10259 Op.getOperand(0), Op.getOperand(1));
10260 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10261 DAG.getValueType(VT));
10262 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10265 if (VT.getSizeInBits() == 16) {
10266 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10267 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10269 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10270 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10271 DAG.getNode(ISD::BITCAST, dl,
10274 Op.getOperand(1)));
10275 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10276 Op.getOperand(0), Op.getOperand(1));
10277 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10278 DAG.getValueType(VT));
10279 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10282 if (VT == MVT::f32) {
10283 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10284 // the result back to FR32 register. It's only worth matching if the
10285 // result has a single use which is a store or a bitcast to i32. And in
10286 // the case of a store, it's not worth it if the index is a constant 0,
10287 // because a MOVSSmr can be used instead, which is smaller and faster.
10288 if (!Op.hasOneUse())
10290 SDNode *User = *Op.getNode()->use_begin();
10291 if ((User->getOpcode() != ISD::STORE ||
10292 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10293 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10294 (User->getOpcode() != ISD::BITCAST ||
10295 User->getValueType(0) != MVT::i32))
10297 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10298 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10301 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10304 if (VT == MVT::i32 || VT == MVT::i64) {
10305 // ExtractPS/pextrq works with constant index.
10306 if (isa<ConstantSDNode>(Op.getOperand(1)))
10312 /// Extract one bit from mask vector, like v16i1 or v8i1.
10313 /// AVX-512 feature.
10315 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10316 SDValue Vec = Op.getOperand(0);
10318 MVT VecVT = Vec.getSimpleValueType();
10319 SDValue Idx = Op.getOperand(1);
10320 MVT EltVT = Op.getSimpleValueType();
10322 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10323 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10324 "Unexpected vector type in ExtractBitFromMaskVector");
10326 // variable index can't be handled in mask registers,
10327 // extend vector to VR512
10328 if (!isa<ConstantSDNode>(Idx)) {
10329 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10330 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10331 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10332 ExtVT.getVectorElementType(), Ext, Idx);
10333 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10336 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10337 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10338 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10339 rc = getRegClassFor(MVT::v16i1);
10340 unsigned MaxSift = rc->getSize()*8 - 1;
10341 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10342 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10343 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10344 DAG.getConstant(MaxSift, MVT::i8));
10345 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10346 DAG.getIntPtrConstant(0));
10350 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10351 SelectionDAG &DAG) const {
10353 SDValue Vec = Op.getOperand(0);
10354 MVT VecVT = Vec.getSimpleValueType();
10355 SDValue Idx = Op.getOperand(1);
10357 if (Op.getSimpleValueType() == MVT::i1)
10358 return ExtractBitFromMaskVector(Op, DAG);
10360 if (!isa<ConstantSDNode>(Idx)) {
10361 if (VecVT.is512BitVector() ||
10362 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10363 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10366 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10367 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10368 MaskEltVT.getSizeInBits());
10370 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10371 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10372 getZeroVector(MaskVT, Subtarget, DAG, dl),
10373 Idx, DAG.getConstant(0, getPointerTy()));
10374 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10375 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10376 Perm, DAG.getConstant(0, getPointerTy()));
10381 // If this is a 256-bit vector result, first extract the 128-bit vector and
10382 // then extract the element from the 128-bit vector.
10383 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10385 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10386 // Get the 128-bit vector.
10387 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10388 MVT EltVT = VecVT.getVectorElementType();
10390 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10392 //if (IdxVal >= NumElems/2)
10393 // IdxVal -= NumElems/2;
10394 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10395 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10396 DAG.getConstant(IdxVal, MVT::i32));
10399 assert(VecVT.is128BitVector() && "Unexpected vector length");
10401 if (Subtarget->hasSSE41()) {
10402 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10407 MVT VT = Op.getSimpleValueType();
10408 // TODO: handle v16i8.
10409 if (VT.getSizeInBits() == 16) {
10410 SDValue Vec = Op.getOperand(0);
10411 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10413 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10414 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10415 DAG.getNode(ISD::BITCAST, dl,
10417 Op.getOperand(1)));
10418 // Transform it so it match pextrw which produces a 32-bit result.
10419 MVT EltVT = MVT::i32;
10420 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10421 Op.getOperand(0), Op.getOperand(1));
10422 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10423 DAG.getValueType(VT));
10424 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10427 if (VT.getSizeInBits() == 32) {
10428 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10432 // SHUFPS the element to the lowest double word, then movss.
10433 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10434 MVT VVT = Op.getOperand(0).getSimpleValueType();
10435 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10436 DAG.getUNDEF(VVT), Mask);
10437 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10438 DAG.getIntPtrConstant(0));
10441 if (VT.getSizeInBits() == 64) {
10442 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10443 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10444 // to match extract_elt for f64.
10445 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10449 // UNPCKHPD the element to the lowest double word, then movsd.
10450 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10451 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10452 int Mask[2] = { 1, -1 };
10453 MVT VVT = Op.getOperand(0).getSimpleValueType();
10454 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10455 DAG.getUNDEF(VVT), Mask);
10456 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10457 DAG.getIntPtrConstant(0));
10463 /// Insert one bit to mask vector, like v16i1 or v8i1.
10464 /// AVX-512 feature.
10466 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10468 SDValue Vec = Op.getOperand(0);
10469 SDValue Elt = Op.getOperand(1);
10470 SDValue Idx = Op.getOperand(2);
10471 MVT VecVT = Vec.getSimpleValueType();
10473 if (!isa<ConstantSDNode>(Idx)) {
10474 // Non constant index. Extend source and destination,
10475 // insert element and then truncate the result.
10476 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10477 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10478 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10479 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10480 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10481 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10484 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10485 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10486 if (Vec.getOpcode() == ISD::UNDEF)
10487 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10488 DAG.getConstant(IdxVal, MVT::i8));
10489 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10490 unsigned MaxSift = rc->getSize()*8 - 1;
10491 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10492 DAG.getConstant(MaxSift, MVT::i8));
10493 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10494 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10495 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10498 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10499 SelectionDAG &DAG) const {
10500 MVT VT = Op.getSimpleValueType();
10501 MVT EltVT = VT.getVectorElementType();
10503 if (EltVT == MVT::i1)
10504 return InsertBitToMaskVector(Op, DAG);
10507 SDValue N0 = Op.getOperand(0);
10508 SDValue N1 = Op.getOperand(1);
10509 SDValue N2 = Op.getOperand(2);
10510 if (!isa<ConstantSDNode>(N2))
10512 auto *N2C = cast<ConstantSDNode>(N2);
10513 unsigned IdxVal = N2C->getZExtValue();
10515 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10516 // into that, and then insert the subvector back into the result.
10517 if (VT.is256BitVector() || VT.is512BitVector()) {
10518 // Get the desired 128-bit vector chunk.
10519 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10521 // Insert the element into the desired chunk.
10522 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10523 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10525 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10526 DAG.getConstant(IdxIn128, MVT::i32));
10528 // Insert the changed part back into the bigger vector
10529 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10531 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10533 if (Subtarget->hasSSE41()) {
10534 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10536 if (VT == MVT::v8i16) {
10537 Opc = X86ISD::PINSRW;
10539 assert(VT == MVT::v16i8);
10540 Opc = X86ISD::PINSRB;
10543 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10545 if (N1.getValueType() != MVT::i32)
10546 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10547 if (N2.getValueType() != MVT::i32)
10548 N2 = DAG.getIntPtrConstant(IdxVal);
10549 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10552 if (EltVT == MVT::f32) {
10553 // Bits [7:6] of the constant are the source select. This will always be
10554 // zero here. The DAG Combiner may combine an extract_elt index into
10556 // bits. For example (insert (extract, 3), 2) could be matched by
10558 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10559 // Bits [5:4] of the constant are the destination select. This is the
10560 // value of the incoming immediate.
10561 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10562 // combine either bitwise AND or insert of float 0.0 to set these bits.
10563 N2 = DAG.getIntPtrConstant(IdxVal << 4);
10564 // Create this as a scalar to vector..
10565 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10566 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10569 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10570 // PINSR* works with constant index.
10575 if (EltVT == MVT::i8)
10578 if (EltVT.getSizeInBits() == 16) {
10579 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10580 // as its second argument.
10581 if (N1.getValueType() != MVT::i32)
10582 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10583 if (N2.getValueType() != MVT::i32)
10584 N2 = DAG.getIntPtrConstant(IdxVal);
10585 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10590 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10592 MVT OpVT = Op.getSimpleValueType();
10594 // If this is a 256-bit vector result, first insert into a 128-bit
10595 // vector and then insert into the 256-bit vector.
10596 if (!OpVT.is128BitVector()) {
10597 // Insert into a 128-bit vector.
10598 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10599 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10600 OpVT.getVectorNumElements() / SizeFactor);
10602 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10604 // Insert the 128-bit vector.
10605 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10608 if (OpVT == MVT::v1i64 &&
10609 Op.getOperand(0).getValueType() == MVT::i64)
10610 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10612 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10613 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10614 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10615 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10618 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10619 // a simple subregister reference or explicit instructions to grab
10620 // upper bits of a vector.
10621 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10622 SelectionDAG &DAG) {
10624 SDValue In = Op.getOperand(0);
10625 SDValue Idx = Op.getOperand(1);
10626 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10627 MVT ResVT = Op.getSimpleValueType();
10628 MVT InVT = In.getSimpleValueType();
10630 if (Subtarget->hasFp256()) {
10631 if (ResVT.is128BitVector() &&
10632 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10633 isa<ConstantSDNode>(Idx)) {
10634 return Extract128BitVector(In, IdxVal, DAG, dl);
10636 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10637 isa<ConstantSDNode>(Idx)) {
10638 return Extract256BitVector(In, IdxVal, DAG, dl);
10644 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10645 // simple superregister reference or explicit instructions to insert
10646 // the upper bits of a vector.
10647 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10648 SelectionDAG &DAG) {
10649 if (!Subtarget->hasAVX())
10653 SDValue Vec = Op.getOperand(0);
10654 SDValue SubVec = Op.getOperand(1);
10655 SDValue Idx = Op.getOperand(2);
10657 if (!isa<ConstantSDNode>(Idx))
10660 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10661 MVT OpVT = Op.getSimpleValueType();
10662 MVT SubVecVT = SubVec.getSimpleValueType();
10664 // Fold two 16-byte subvector loads into one 32-byte load:
10665 // (insert_subvector (insert_subvector undef, (load addr), 0),
10666 // (load addr + 16), Elts/2)
10668 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10669 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10670 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10671 !Subtarget->isUnalignedMem32Slow()) {
10672 SDValue SubVec2 = Vec.getOperand(1);
10673 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10674 if (Idx2->getZExtValue() == 0) {
10675 SDValue Ops[] = { SubVec2, SubVec };
10676 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10683 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10684 SubVecVT.is128BitVector())
10685 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10687 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10688 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10690 if (OpVT.getVectorElementType() == MVT::i1) {
10691 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10693 SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10694 SDValue Undef = DAG.getUNDEF(OpVT);
10695 unsigned NumElems = OpVT.getVectorNumElements();
10696 SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10698 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10699 // Zero upper bits of the Vec
10700 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10701 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10703 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10705 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10706 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10709 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10711 // Zero upper bits of the Vec2
10712 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10713 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10714 // Zero lower bits of the Vec
10715 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10716 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10717 // Merge them together
10718 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10724 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10725 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10726 // one of the above mentioned nodes. It has to be wrapped because otherwise
10727 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10728 // be used to form addressing mode. These wrapped nodes will be selected
10731 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10732 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10734 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10735 // global base reg.
10736 unsigned char OpFlag = 0;
10737 unsigned WrapperKind = X86ISD::Wrapper;
10738 CodeModel::Model M = DAG.getTarget().getCodeModel();
10740 if (Subtarget->isPICStyleRIPRel() &&
10741 (M == CodeModel::Small || M == CodeModel::Kernel))
10742 WrapperKind = X86ISD::WrapperRIP;
10743 else if (Subtarget->isPICStyleGOT())
10744 OpFlag = X86II::MO_GOTOFF;
10745 else if (Subtarget->isPICStyleStubPIC())
10746 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10748 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10749 CP->getAlignment(),
10750 CP->getOffset(), OpFlag);
10752 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10753 // With PIC, the address is actually $g + Offset.
10755 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10756 DAG.getNode(X86ISD::GlobalBaseReg,
10757 SDLoc(), getPointerTy()),
10764 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10765 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10767 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10768 // global base reg.
10769 unsigned char OpFlag = 0;
10770 unsigned WrapperKind = X86ISD::Wrapper;
10771 CodeModel::Model M = DAG.getTarget().getCodeModel();
10773 if (Subtarget->isPICStyleRIPRel() &&
10774 (M == CodeModel::Small || M == CodeModel::Kernel))
10775 WrapperKind = X86ISD::WrapperRIP;
10776 else if (Subtarget->isPICStyleGOT())
10777 OpFlag = X86II::MO_GOTOFF;
10778 else if (Subtarget->isPICStyleStubPIC())
10779 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10781 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10784 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10786 // With PIC, the address is actually $g + Offset.
10788 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10789 DAG.getNode(X86ISD::GlobalBaseReg,
10790 SDLoc(), getPointerTy()),
10797 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10798 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10800 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10801 // global base reg.
10802 unsigned char OpFlag = 0;
10803 unsigned WrapperKind = X86ISD::Wrapper;
10804 CodeModel::Model M = DAG.getTarget().getCodeModel();
10806 if (Subtarget->isPICStyleRIPRel() &&
10807 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10808 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10809 OpFlag = X86II::MO_GOTPCREL;
10810 WrapperKind = X86ISD::WrapperRIP;
10811 } else if (Subtarget->isPICStyleGOT()) {
10812 OpFlag = X86II::MO_GOT;
10813 } else if (Subtarget->isPICStyleStubPIC()) {
10814 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10815 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10816 OpFlag = X86II::MO_DARWIN_NONLAZY;
10819 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10822 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10824 // With PIC, the address is actually $g + Offset.
10825 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10826 !Subtarget->is64Bit()) {
10827 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10828 DAG.getNode(X86ISD::GlobalBaseReg,
10829 SDLoc(), getPointerTy()),
10833 // For symbols that require a load from a stub to get the address, emit the
10835 if (isGlobalStubReference(OpFlag))
10836 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10837 MachinePointerInfo::getGOT(), false, false, false, 0);
10843 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10844 // Create the TargetBlockAddressAddress node.
10845 unsigned char OpFlags =
10846 Subtarget->ClassifyBlockAddressReference();
10847 CodeModel::Model M = DAG.getTarget().getCodeModel();
10848 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10849 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10851 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10854 if (Subtarget->isPICStyleRIPRel() &&
10855 (M == CodeModel::Small || M == CodeModel::Kernel))
10856 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10858 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10860 // With PIC, the address is actually $g + Offset.
10861 if (isGlobalRelativeToPICBase(OpFlags)) {
10862 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10863 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10871 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10872 int64_t Offset, SelectionDAG &DAG) const {
10873 // Create the TargetGlobalAddress node, folding in the constant
10874 // offset if it is legal.
10875 unsigned char OpFlags =
10876 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10877 CodeModel::Model M = DAG.getTarget().getCodeModel();
10879 if (OpFlags == X86II::MO_NO_FLAG &&
10880 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10881 // A direct static reference to a global.
10882 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10885 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10888 if (Subtarget->isPICStyleRIPRel() &&
10889 (M == CodeModel::Small || M == CodeModel::Kernel))
10890 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10892 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10894 // With PIC, the address is actually $g + Offset.
10895 if (isGlobalRelativeToPICBase(OpFlags)) {
10896 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10897 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10901 // For globals that require a load from a stub to get the address, emit the
10903 if (isGlobalStubReference(OpFlags))
10904 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10905 MachinePointerInfo::getGOT(), false, false, false, 0);
10907 // If there was a non-zero offset that we didn't fold, create an explicit
10908 // addition for it.
10910 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10911 DAG.getConstant(Offset, getPointerTy()));
10917 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10918 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10919 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10920 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10924 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10925 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10926 unsigned char OperandFlags, bool LocalDynamic = false) {
10927 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10928 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10930 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10931 GA->getValueType(0),
10935 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10939 SDValue Ops[] = { Chain, TGA, *InFlag };
10940 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10942 SDValue Ops[] = { Chain, TGA };
10943 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10946 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10947 MFI->setAdjustsStack(true);
10948 MFI->setHasCalls(true);
10950 SDValue Flag = Chain.getValue(1);
10951 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10954 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10956 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10959 SDLoc dl(GA); // ? function entry point might be better
10960 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10961 DAG.getNode(X86ISD::GlobalBaseReg,
10962 SDLoc(), PtrVT), InFlag);
10963 InFlag = Chain.getValue(1);
10965 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10968 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10970 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10972 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10973 X86::RAX, X86II::MO_TLSGD);
10976 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10982 // Get the start address of the TLS block for this module.
10983 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10984 .getInfo<X86MachineFunctionInfo>();
10985 MFI->incNumLocalDynamicTLSAccesses();
10989 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10990 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10993 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10994 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10995 InFlag = Chain.getValue(1);
10996 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10997 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11000 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11004 unsigned char OperandFlags = X86II::MO_DTPOFF;
11005 unsigned WrapperKind = X86ISD::Wrapper;
11006 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11007 GA->getValueType(0),
11008 GA->getOffset(), OperandFlags);
11009 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11011 // Add x@dtpoff with the base.
11012 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11015 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11016 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11017 const EVT PtrVT, TLSModel::Model model,
11018 bool is64Bit, bool isPIC) {
11021 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11022 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11023 is64Bit ? 257 : 256));
11025 SDValue ThreadPointer =
11026 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11027 MachinePointerInfo(Ptr), false, false, false, 0);
11029 unsigned char OperandFlags = 0;
11030 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11032 unsigned WrapperKind = X86ISD::Wrapper;
11033 if (model == TLSModel::LocalExec) {
11034 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11035 } else if (model == TLSModel::InitialExec) {
11037 OperandFlags = X86II::MO_GOTTPOFF;
11038 WrapperKind = X86ISD::WrapperRIP;
11040 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11043 llvm_unreachable("Unexpected model");
11046 // emit "addl x@ntpoff,%eax" (local exec)
11047 // or "addl x@indntpoff,%eax" (initial exec)
11048 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11050 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11051 GA->getOffset(), OperandFlags);
11052 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11054 if (model == TLSModel::InitialExec) {
11055 if (isPIC && !is64Bit) {
11056 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11057 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11061 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11062 MachinePointerInfo::getGOT(), false, false, false, 0);
11065 // The address of the thread local variable is the add of the thread
11066 // pointer with the offset of the variable.
11067 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11071 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11073 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11074 const GlobalValue *GV = GA->getGlobal();
11076 if (Subtarget->isTargetELF()) {
11077 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11080 case TLSModel::GeneralDynamic:
11081 if (Subtarget->is64Bit())
11082 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11083 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11084 case TLSModel::LocalDynamic:
11085 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11086 Subtarget->is64Bit());
11087 case TLSModel::InitialExec:
11088 case TLSModel::LocalExec:
11089 return LowerToTLSExecModel(
11090 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11091 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11093 llvm_unreachable("Unknown TLS model.");
11096 if (Subtarget->isTargetDarwin()) {
11097 // Darwin only has one model of TLS. Lower to that.
11098 unsigned char OpFlag = 0;
11099 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11100 X86ISD::WrapperRIP : X86ISD::Wrapper;
11102 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11103 // global base reg.
11104 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11105 !Subtarget->is64Bit();
11107 OpFlag = X86II::MO_TLVP_PIC_BASE;
11109 OpFlag = X86II::MO_TLVP;
11111 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11112 GA->getValueType(0),
11113 GA->getOffset(), OpFlag);
11114 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11116 // With PIC32, the address is actually $g + Offset.
11118 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11119 DAG.getNode(X86ISD::GlobalBaseReg,
11120 SDLoc(), getPointerTy()),
11123 // Lowering the machine isd will make sure everything is in the right
11125 SDValue Chain = DAG.getEntryNode();
11126 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11127 SDValue Args[] = { Chain, Offset };
11128 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11130 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11131 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11132 MFI->setAdjustsStack(true);
11134 // And our return value (tls address) is in the standard call return value
11136 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11137 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11138 Chain.getValue(1));
11141 if (Subtarget->isTargetKnownWindowsMSVC() ||
11142 Subtarget->isTargetWindowsGNU()) {
11143 // Just use the implicit TLS architecture
11144 // Need to generate someting similar to:
11145 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11147 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11148 // mov rcx, qword [rdx+rcx*8]
11149 // mov eax, .tls$:tlsvar
11150 // [rax+rcx] contains the address
11151 // Windows 64bit: gs:0x58
11152 // Windows 32bit: fs:__tls_array
11155 SDValue Chain = DAG.getEntryNode();
11157 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11158 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11159 // use its literal value of 0x2C.
11160 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11161 ? Type::getInt8PtrTy(*DAG.getContext(),
11163 : Type::getInt32PtrTy(*DAG.getContext(),
11167 Subtarget->is64Bit()
11168 ? DAG.getIntPtrConstant(0x58)
11169 : (Subtarget->isTargetWindowsGNU()
11170 ? DAG.getIntPtrConstant(0x2C)
11171 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11173 SDValue ThreadPointer =
11174 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11175 MachinePointerInfo(Ptr), false, false, false, 0);
11177 // Load the _tls_index variable
11178 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11179 if (Subtarget->is64Bit())
11180 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11181 IDX, MachinePointerInfo(), MVT::i32,
11182 false, false, false, 0);
11184 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11185 false, false, false, 0);
11187 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11189 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11191 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11192 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11193 false, false, false, 0);
11195 // Get the offset of start of .tls section
11196 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11197 GA->getValueType(0),
11198 GA->getOffset(), X86II::MO_SECREL);
11199 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11201 // The address of the thread local variable is the add of the thread
11202 // pointer with the offset of the variable.
11203 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11206 llvm_unreachable("TLS not implemented for this target.");
11209 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11210 /// and take a 2 x i32 value to shift plus a shift amount.
11211 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11212 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11213 MVT VT = Op.getSimpleValueType();
11214 unsigned VTBits = VT.getSizeInBits();
11216 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11217 SDValue ShOpLo = Op.getOperand(0);
11218 SDValue ShOpHi = Op.getOperand(1);
11219 SDValue ShAmt = Op.getOperand(2);
11220 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11221 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11223 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11224 DAG.getConstant(VTBits - 1, MVT::i8));
11225 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11226 DAG.getConstant(VTBits - 1, MVT::i8))
11227 : DAG.getConstant(0, VT);
11229 SDValue Tmp2, Tmp3;
11230 if (Op.getOpcode() == ISD::SHL_PARTS) {
11231 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11232 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11234 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11235 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11238 // If the shift amount is larger or equal than the width of a part we can't
11239 // rely on the results of shld/shrd. Insert a test and select the appropriate
11240 // values for large shift amounts.
11241 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11242 DAG.getConstant(VTBits, MVT::i8));
11243 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11244 AndNode, DAG.getConstant(0, MVT::i8));
11247 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11248 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11249 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11251 if (Op.getOpcode() == ISD::SHL_PARTS) {
11252 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11253 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11255 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11256 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11259 SDValue Ops[2] = { Lo, Hi };
11260 return DAG.getMergeValues(Ops, dl);
11263 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11264 SelectionDAG &DAG) const {
11265 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11268 if (SrcVT.isVector()) {
11269 if (SrcVT.getVectorElementType() == MVT::i1) {
11270 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11271 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11272 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11273 Op.getOperand(0)));
11278 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11279 "Unknown SINT_TO_FP to lower!");
11281 // These are really Legal; return the operand so the caller accepts it as
11283 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11285 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11286 Subtarget->is64Bit()) {
11290 unsigned Size = SrcVT.getSizeInBits()/8;
11291 MachineFunction &MF = DAG.getMachineFunction();
11292 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11293 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11294 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11296 MachinePointerInfo::getFixedStack(SSFI),
11298 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11301 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11303 SelectionDAG &DAG) const {
11307 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11309 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11311 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11313 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11315 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11316 MachineMemOperand *MMO;
11318 int SSFI = FI->getIndex();
11320 DAG.getMachineFunction()
11321 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11322 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11324 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11325 StackSlot = StackSlot.getOperand(1);
11327 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11328 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11330 Tys, Ops, SrcVT, MMO);
11333 Chain = Result.getValue(1);
11334 SDValue InFlag = Result.getValue(2);
11336 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11337 // shouldn't be necessary except that RFP cannot be live across
11338 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11339 MachineFunction &MF = DAG.getMachineFunction();
11340 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11341 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11342 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11343 Tys = DAG.getVTList(MVT::Other);
11345 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11347 MachineMemOperand *MMO =
11348 DAG.getMachineFunction()
11349 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11350 MachineMemOperand::MOStore, SSFISize, SSFISize);
11352 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11353 Ops, Op.getValueType(), MMO);
11354 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11355 MachinePointerInfo::getFixedStack(SSFI),
11356 false, false, false, 0);
11362 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11363 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11364 SelectionDAG &DAG) const {
11365 // This algorithm is not obvious. Here it is what we're trying to output:
11368 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11369 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11371 haddpd %xmm0, %xmm0
11373 pshufd $0x4e, %xmm0, %xmm1
11379 LLVMContext *Context = DAG.getContext();
11381 // Build some magic constants.
11382 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11383 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11384 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11386 SmallVector<Constant*,2> CV1;
11388 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11389 APInt(64, 0x4330000000000000ULL))));
11391 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11392 APInt(64, 0x4530000000000000ULL))));
11393 Constant *C1 = ConstantVector::get(CV1);
11394 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11396 // Load the 64-bit value into an XMM register.
11397 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11399 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11400 MachinePointerInfo::getConstantPool(),
11401 false, false, false, 16);
11402 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11403 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11406 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11407 MachinePointerInfo::getConstantPool(),
11408 false, false, false, 16);
11409 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11410 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11413 if (Subtarget->hasSSE3()) {
11414 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11415 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11417 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11418 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11420 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11421 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11425 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11426 DAG.getIntPtrConstant(0));
11429 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11430 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11431 SelectionDAG &DAG) const {
11433 // FP constant to bias correct the final result.
11434 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11437 // Load the 32-bit value into an XMM register.
11438 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11441 // Zero out the upper parts of the register.
11442 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11444 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11445 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11446 DAG.getIntPtrConstant(0));
11448 // Or the load with the bias.
11449 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11450 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11451 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11452 MVT::v2f64, Load)),
11453 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11454 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11455 MVT::v2f64, Bias)));
11456 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11457 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11458 DAG.getIntPtrConstant(0));
11460 // Subtract the bias.
11461 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11463 // Handle final rounding.
11464 EVT DestVT = Op.getValueType();
11466 if (DestVT.bitsLT(MVT::f64))
11467 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11468 DAG.getIntPtrConstant(0));
11469 if (DestVT.bitsGT(MVT::f64))
11470 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11472 // Handle final rounding.
11476 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11477 const X86Subtarget &Subtarget) {
11478 // The algorithm is the following:
11479 // #ifdef __SSE4_1__
11480 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11481 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11482 // (uint4) 0x53000000, 0xaa);
11484 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11485 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11487 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11488 // return (float4) lo + fhi;
11491 SDValue V = Op->getOperand(0);
11492 EVT VecIntVT = V.getValueType();
11493 bool Is128 = VecIntVT == MVT::v4i32;
11494 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11495 // If we convert to something else than the supported type, e.g., to v4f64,
11497 if (VecFloatVT != Op->getValueType(0))
11500 unsigned NumElts = VecIntVT.getVectorNumElements();
11501 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11502 "Unsupported custom type");
11503 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11505 // In the #idef/#else code, we have in common:
11506 // - The vector of constants:
11512 // Create the splat vector for 0x4b000000.
11513 SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11514 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11515 CstLow, CstLow, CstLow, CstLow};
11516 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11517 makeArrayRef(&CstLowArray[0], NumElts));
11518 // Create the splat vector for 0x53000000.
11519 SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11520 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11521 CstHigh, CstHigh, CstHigh, CstHigh};
11522 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11523 makeArrayRef(&CstHighArray[0], NumElts));
11525 // Create the right shift.
11526 SDValue CstShift = DAG.getConstant(16, MVT::i32);
11527 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11528 CstShift, CstShift, CstShift, CstShift};
11529 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11530 makeArrayRef(&CstShiftArray[0], NumElts));
11531 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11534 if (Subtarget.hasSSE41()) {
11535 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11536 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11537 SDValue VecCstLowBitcast =
11538 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11539 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11540 // Low will be bitcasted right away, so do not bother bitcasting back to its
11542 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11543 VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11544 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11545 // (uint4) 0x53000000, 0xaa);
11546 SDValue VecCstHighBitcast =
11547 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11548 SDValue VecShiftBitcast =
11549 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11550 // High will be bitcasted right away, so do not bother bitcasting back to
11551 // its original type.
11552 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11553 VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11555 SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11556 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11557 CstMask, CstMask, CstMask);
11558 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11559 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11560 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11562 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11563 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11566 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11567 SDValue CstFAdd = DAG.getConstantFP(
11568 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11569 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11570 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11571 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11572 makeArrayRef(&CstFAddArray[0], NumElts));
11574 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11575 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11577 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11578 // return (float4) lo + fhi;
11579 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11580 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11583 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11584 SelectionDAG &DAG) const {
11585 SDValue N0 = Op.getOperand(0);
11586 MVT SVT = N0.getSimpleValueType();
11589 switch (SVT.SimpleTy) {
11591 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11596 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11597 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11598 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11602 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11604 llvm_unreachable(nullptr);
11607 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11608 SelectionDAG &DAG) const {
11609 SDValue N0 = Op.getOperand(0);
11612 if (Op.getValueType().isVector())
11613 return lowerUINT_TO_FP_vec(Op, DAG);
11615 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11616 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11617 // the optimization here.
11618 if (DAG.SignBitIsZero(N0))
11619 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11621 MVT SrcVT = N0.getSimpleValueType();
11622 MVT DstVT = Op.getSimpleValueType();
11623 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11624 return LowerUINT_TO_FP_i64(Op, DAG);
11625 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11626 return LowerUINT_TO_FP_i32(Op, DAG);
11627 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11630 // Make a 64-bit buffer, and use it to build an FILD.
11631 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11632 if (SrcVT == MVT::i32) {
11633 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11634 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11635 getPointerTy(), StackSlot, WordOff);
11636 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11637 StackSlot, MachinePointerInfo(),
11639 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11640 OffsetSlot, MachinePointerInfo(),
11642 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11646 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11647 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11648 StackSlot, MachinePointerInfo(),
11650 // For i64 source, we need to add the appropriate power of 2 if the input
11651 // was negative. This is the same as the optimization in
11652 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11653 // we must be careful to do the computation in x87 extended precision, not
11654 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11655 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11656 MachineMemOperand *MMO =
11657 DAG.getMachineFunction()
11658 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11659 MachineMemOperand::MOLoad, 8, 8);
11661 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11662 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11663 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11666 APInt FF(32, 0x5F800000ULL);
11668 // Check whether the sign bit is set.
11669 SDValue SignSet = DAG.getSetCC(dl,
11670 getSetCCResultType(*DAG.getContext(), MVT::i64),
11671 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11674 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11675 SDValue FudgePtr = DAG.getConstantPool(
11676 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11679 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11680 SDValue Zero = DAG.getIntPtrConstant(0);
11681 SDValue Four = DAG.getIntPtrConstant(4);
11682 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11684 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11686 // Load the value out, extending it from f32 to f80.
11687 // FIXME: Avoid the extend by constructing the right constant pool?
11688 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11689 FudgePtr, MachinePointerInfo::getConstantPool(),
11690 MVT::f32, false, false, false, 4);
11691 // Extend everything to 80 bits to force it to be done on x87.
11692 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11693 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11696 std::pair<SDValue,SDValue>
11697 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11698 bool IsSigned, bool IsReplace) const {
11701 EVT DstTy = Op.getValueType();
11703 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11704 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11708 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11709 DstTy.getSimpleVT() >= MVT::i16 &&
11710 "Unknown FP_TO_INT to lower!");
11712 // These are really Legal.
11713 if (DstTy == MVT::i32 &&
11714 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11715 return std::make_pair(SDValue(), SDValue());
11716 if (Subtarget->is64Bit() &&
11717 DstTy == MVT::i64 &&
11718 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11719 return std::make_pair(SDValue(), SDValue());
11721 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11722 // stack slot, or into the FTOL runtime function.
11723 MachineFunction &MF = DAG.getMachineFunction();
11724 unsigned MemSize = DstTy.getSizeInBits()/8;
11725 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11726 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11729 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11730 Opc = X86ISD::WIN_FTOL;
11732 switch (DstTy.getSimpleVT().SimpleTy) {
11733 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11734 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11735 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11736 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11739 SDValue Chain = DAG.getEntryNode();
11740 SDValue Value = Op.getOperand(0);
11741 EVT TheVT = Op.getOperand(0).getValueType();
11742 // FIXME This causes a redundant load/store if the SSE-class value is already
11743 // in memory, such as if it is on the callstack.
11744 if (isScalarFPTypeInSSEReg(TheVT)) {
11745 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11746 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11747 MachinePointerInfo::getFixedStack(SSFI),
11749 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11751 Chain, StackSlot, DAG.getValueType(TheVT)
11754 MachineMemOperand *MMO =
11755 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11756 MachineMemOperand::MOLoad, MemSize, MemSize);
11757 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11758 Chain = Value.getValue(1);
11759 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11760 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11763 MachineMemOperand *MMO =
11764 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11765 MachineMemOperand::MOStore, MemSize, MemSize);
11767 if (Opc != X86ISD::WIN_FTOL) {
11768 // Build the FP_TO_INT*_IN_MEM
11769 SDValue Ops[] = { Chain, Value, StackSlot };
11770 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11772 return std::make_pair(FIST, StackSlot);
11774 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11775 DAG.getVTList(MVT::Other, MVT::Glue),
11777 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11778 MVT::i32, ftol.getValue(1));
11779 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11780 MVT::i32, eax.getValue(2));
11781 SDValue Ops[] = { eax, edx };
11782 SDValue pair = IsReplace
11783 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11784 : DAG.getMergeValues(Ops, DL);
11785 return std::make_pair(pair, SDValue());
11789 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11790 const X86Subtarget *Subtarget) {
11791 MVT VT = Op->getSimpleValueType(0);
11792 SDValue In = Op->getOperand(0);
11793 MVT InVT = In.getSimpleValueType();
11796 // Optimize vectors in AVX mode:
11799 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11800 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11801 // Concat upper and lower parts.
11804 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11805 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11806 // Concat upper and lower parts.
11809 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11810 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11811 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11814 if (Subtarget->hasInt256())
11815 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11817 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11818 SDValue Undef = DAG.getUNDEF(InVT);
11819 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11820 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11821 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11823 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11824 VT.getVectorNumElements()/2);
11826 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11827 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11829 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11832 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11833 SelectionDAG &DAG) {
11834 MVT VT = Op->getSimpleValueType(0);
11835 SDValue In = Op->getOperand(0);
11836 MVT InVT = In.getSimpleValueType();
11838 unsigned int NumElts = VT.getVectorNumElements();
11839 if (NumElts != 8 && NumElts != 16)
11842 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11843 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11845 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11846 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11847 // Now we have only mask extension
11848 assert(InVT.getVectorElementType() == MVT::i1);
11849 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11850 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11851 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11852 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11853 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11854 MachinePointerInfo::getConstantPool(),
11855 false, false, false, Alignment);
11857 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11858 if (VT.is512BitVector())
11860 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11863 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11864 SelectionDAG &DAG) {
11865 if (Subtarget->hasFp256()) {
11866 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11874 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11875 SelectionDAG &DAG) {
11877 MVT VT = Op.getSimpleValueType();
11878 SDValue In = Op.getOperand(0);
11879 MVT SVT = In.getSimpleValueType();
11881 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11882 return LowerZERO_EXTEND_AVX512(Op, DAG);
11884 if (Subtarget->hasFp256()) {
11885 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11890 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11891 VT.getVectorNumElements() != SVT.getVectorNumElements());
11895 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11897 MVT VT = Op.getSimpleValueType();
11898 SDValue In = Op.getOperand(0);
11899 MVT InVT = In.getSimpleValueType();
11901 if (VT == MVT::i1) {
11902 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11903 "Invalid scalar TRUNCATE operation");
11904 if (InVT.getSizeInBits() >= 32)
11906 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11907 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11909 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11910 "Invalid TRUNCATE operation");
11912 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11913 if (VT.getVectorElementType().getSizeInBits() >=8)
11914 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11916 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11917 unsigned NumElts = InVT.getVectorNumElements();
11918 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11919 if (InVT.getSizeInBits() < 512) {
11920 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11921 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11925 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11926 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11927 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11928 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11929 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11930 MachinePointerInfo::getConstantPool(),
11931 false, false, false, Alignment);
11932 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11933 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11934 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11937 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11938 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11939 if (Subtarget->hasInt256()) {
11940 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11941 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11942 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11944 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11945 DAG.getIntPtrConstant(0));
11948 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11949 DAG.getIntPtrConstant(0));
11950 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11951 DAG.getIntPtrConstant(2));
11952 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11953 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11954 static const int ShufMask[] = {0, 2, 4, 6};
11955 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11958 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11959 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11960 if (Subtarget->hasInt256()) {
11961 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11963 SmallVector<SDValue,32> pshufbMask;
11964 for (unsigned i = 0; i < 2; ++i) {
11965 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11966 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11967 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11968 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11969 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11970 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11971 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11972 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11973 for (unsigned j = 0; j < 8; ++j)
11974 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11976 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11977 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11978 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11980 static const int ShufMask[] = {0, 2, -1, -1};
11981 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11983 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11984 DAG.getIntPtrConstant(0));
11985 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11988 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11989 DAG.getIntPtrConstant(0));
11991 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11992 DAG.getIntPtrConstant(4));
11994 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11995 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11997 // The PSHUFB mask:
11998 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11999 -1, -1, -1, -1, -1, -1, -1, -1};
12001 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12002 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12003 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12005 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12006 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12008 // The MOVLHPS Mask:
12009 static const int ShufMask2[] = {0, 1, 4, 5};
12010 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12011 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12014 // Handle truncation of V256 to V128 using shuffles.
12015 if (!VT.is128BitVector() || !InVT.is256BitVector())
12018 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12020 unsigned NumElems = VT.getVectorNumElements();
12021 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12023 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12024 // Prepare truncation shuffle mask
12025 for (unsigned i = 0; i != NumElems; ++i)
12026 MaskVec[i] = i * 2;
12027 SDValue V = DAG.getVectorShuffle(NVT, DL,
12028 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12029 DAG.getUNDEF(NVT), &MaskVec[0]);
12030 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12031 DAG.getIntPtrConstant(0));
12034 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12035 SelectionDAG &DAG) const {
12036 assert(!Op.getSimpleValueType().isVector());
12038 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12039 /*IsSigned=*/ true, /*IsReplace=*/ false);
12040 SDValue FIST = Vals.first, StackSlot = Vals.second;
12041 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12042 if (!FIST.getNode()) return Op;
12044 if (StackSlot.getNode())
12045 // Load the result.
12046 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12047 FIST, StackSlot, MachinePointerInfo(),
12048 false, false, false, 0);
12050 // The node is the result.
12054 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12055 SelectionDAG &DAG) const {
12056 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12057 /*IsSigned=*/ false, /*IsReplace=*/ false);
12058 SDValue FIST = Vals.first, StackSlot = Vals.second;
12059 assert(FIST.getNode() && "Unexpected failure");
12061 if (StackSlot.getNode())
12062 // Load the result.
12063 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12064 FIST, StackSlot, MachinePointerInfo(),
12065 false, false, false, 0);
12067 // The node is the result.
12071 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12073 MVT VT = Op.getSimpleValueType();
12074 SDValue In = Op.getOperand(0);
12075 MVT SVT = In.getSimpleValueType();
12077 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12079 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12080 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12081 In, DAG.getUNDEF(SVT)));
12084 /// The only differences between FABS and FNEG are the mask and the logic op.
12085 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12086 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12087 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12088 "Wrong opcode for lowering FABS or FNEG.");
12090 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12092 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12093 // into an FNABS. We'll lower the FABS after that if it is still in use.
12095 for (SDNode *User : Op->uses())
12096 if (User->getOpcode() == ISD::FNEG)
12099 SDValue Op0 = Op.getOperand(0);
12100 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12103 MVT VT = Op.getSimpleValueType();
12104 // Assume scalar op for initialization; update for vector if needed.
12105 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12106 // generate a 16-byte vector constant and logic op even for the scalar case.
12107 // Using a 16-byte mask allows folding the load of the mask with
12108 // the logic op, so it can save (~4 bytes) on code size.
12110 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12111 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12112 // decide if we should generate a 16-byte constant mask when we only need 4 or
12113 // 8 bytes for the scalar case.
12114 if (VT.isVector()) {
12115 EltVT = VT.getVectorElementType();
12116 NumElts = VT.getVectorNumElements();
12119 unsigned EltBits = EltVT.getSizeInBits();
12120 LLVMContext *Context = DAG.getContext();
12121 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12123 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12124 Constant *C = ConstantInt::get(*Context, MaskElt);
12125 C = ConstantVector::getSplat(NumElts, C);
12126 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12127 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12128 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12129 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12130 MachinePointerInfo::getConstantPool(),
12131 false, false, false, Alignment);
12133 if (VT.isVector()) {
12134 // For a vector, cast operands to a vector type, perform the logic op,
12135 // and cast the result back to the original value type.
12136 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12137 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12138 SDValue Operand = IsFNABS ?
12139 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12140 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12141 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12142 return DAG.getNode(ISD::BITCAST, dl, VT,
12143 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12146 // If not vector, then scalar.
12147 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12148 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12149 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12152 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12153 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12154 LLVMContext *Context = DAG.getContext();
12155 SDValue Op0 = Op.getOperand(0);
12156 SDValue Op1 = Op.getOperand(1);
12158 MVT VT = Op.getSimpleValueType();
12159 MVT SrcVT = Op1.getSimpleValueType();
12161 // If second operand is smaller, extend it first.
12162 if (SrcVT.bitsLT(VT)) {
12163 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12166 // And if it is bigger, shrink it first.
12167 if (SrcVT.bitsGT(VT)) {
12168 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12172 // At this point the operands and the result should have the same
12173 // type, and that won't be f80 since that is not custom lowered.
12175 const fltSemantics &Sem =
12176 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12177 const unsigned SizeInBits = VT.getSizeInBits();
12179 SmallVector<Constant *, 4> CV(
12180 VT == MVT::f64 ? 2 : 4,
12181 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12183 // First, clear all bits but the sign bit from the second operand (sign).
12184 CV[0] = ConstantFP::get(*Context,
12185 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12186 Constant *C = ConstantVector::get(CV);
12187 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12188 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12189 MachinePointerInfo::getConstantPool(),
12190 false, false, false, 16);
12191 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12193 // Next, clear the sign bit from the first operand (magnitude).
12194 // If it's a constant, we can clear it here.
12195 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12196 APFloat APF = Op0CN->getValueAPF();
12197 // If the magnitude is a positive zero, the sign bit alone is enough.
12198 if (APF.isPosZero())
12201 CV[0] = ConstantFP::get(*Context, APF);
12203 CV[0] = ConstantFP::get(
12205 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12207 C = ConstantVector::get(CV);
12208 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12209 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12210 MachinePointerInfo::getConstantPool(),
12211 false, false, false, 16);
12212 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12213 if (!isa<ConstantFPSDNode>(Op0))
12214 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12216 // OR the magnitude value with the sign bit.
12217 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12220 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12221 SDValue N0 = Op.getOperand(0);
12223 MVT VT = Op.getSimpleValueType();
12225 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12226 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12227 DAG.getConstant(1, VT));
12228 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12231 // Check whether an OR'd tree is PTEST-able.
12232 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12233 SelectionDAG &DAG) {
12234 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12236 if (!Subtarget->hasSSE41())
12239 if (!Op->hasOneUse())
12242 SDNode *N = Op.getNode();
12245 SmallVector<SDValue, 8> Opnds;
12246 DenseMap<SDValue, unsigned> VecInMap;
12247 SmallVector<SDValue, 8> VecIns;
12248 EVT VT = MVT::Other;
12250 // Recognize a special case where a vector is casted into wide integer to
12252 Opnds.push_back(N->getOperand(0));
12253 Opnds.push_back(N->getOperand(1));
12255 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12256 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12257 // BFS traverse all OR'd operands.
12258 if (I->getOpcode() == ISD::OR) {
12259 Opnds.push_back(I->getOperand(0));
12260 Opnds.push_back(I->getOperand(1));
12261 // Re-evaluate the number of nodes to be traversed.
12262 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12266 // Quit if a non-EXTRACT_VECTOR_ELT
12267 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12270 // Quit if without a constant index.
12271 SDValue Idx = I->getOperand(1);
12272 if (!isa<ConstantSDNode>(Idx))
12275 SDValue ExtractedFromVec = I->getOperand(0);
12276 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12277 if (M == VecInMap.end()) {
12278 VT = ExtractedFromVec.getValueType();
12279 // Quit if not 128/256-bit vector.
12280 if (!VT.is128BitVector() && !VT.is256BitVector())
12282 // Quit if not the same type.
12283 if (VecInMap.begin() != VecInMap.end() &&
12284 VT != VecInMap.begin()->first.getValueType())
12286 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12287 VecIns.push_back(ExtractedFromVec);
12289 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12292 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12293 "Not extracted from 128-/256-bit vector.");
12295 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12297 for (DenseMap<SDValue, unsigned>::const_iterator
12298 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12299 // Quit if not all elements are used.
12300 if (I->second != FullMask)
12304 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12306 // Cast all vectors into TestVT for PTEST.
12307 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12308 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12310 // If more than one full vectors are evaluated, OR them first before PTEST.
12311 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12312 // Each iteration will OR 2 nodes and append the result until there is only
12313 // 1 node left, i.e. the final OR'd value of all vectors.
12314 SDValue LHS = VecIns[Slot];
12315 SDValue RHS = VecIns[Slot + 1];
12316 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12319 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12320 VecIns.back(), VecIns.back());
12323 /// \brief return true if \c Op has a use that doesn't just read flags.
12324 static bool hasNonFlagsUse(SDValue Op) {
12325 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12327 SDNode *User = *UI;
12328 unsigned UOpNo = UI.getOperandNo();
12329 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12330 // Look pass truncate.
12331 UOpNo = User->use_begin().getOperandNo();
12332 User = *User->use_begin();
12335 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12336 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12342 /// Emit nodes that will be selected as "test Op0,Op0", or something
12344 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12345 SelectionDAG &DAG) const {
12346 if (Op.getValueType() == MVT::i1) {
12347 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12348 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12349 DAG.getConstant(0, MVT::i8));
12351 // CF and OF aren't always set the way we want. Determine which
12352 // of these we need.
12353 bool NeedCF = false;
12354 bool NeedOF = false;
12357 case X86::COND_A: case X86::COND_AE:
12358 case X86::COND_B: case X86::COND_BE:
12361 case X86::COND_G: case X86::COND_GE:
12362 case X86::COND_L: case X86::COND_LE:
12363 case X86::COND_O: case X86::COND_NO: {
12364 // Check if we really need to set the
12365 // Overflow flag. If NoSignedWrap is present
12366 // that is not actually needed.
12367 switch (Op->getOpcode()) {
12372 const BinaryWithFlagsSDNode *BinNode =
12373 cast<BinaryWithFlagsSDNode>(Op.getNode());
12374 if (BinNode->hasNoSignedWrap())
12384 // See if we can use the EFLAGS value from the operand instead of
12385 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12386 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12387 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12388 // Emit a CMP with 0, which is the TEST pattern.
12389 //if (Op.getValueType() == MVT::i1)
12390 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12391 // DAG.getConstant(0, MVT::i1));
12392 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12393 DAG.getConstant(0, Op.getValueType()));
12395 unsigned Opcode = 0;
12396 unsigned NumOperands = 0;
12398 // Truncate operations may prevent the merge of the SETCC instruction
12399 // and the arithmetic instruction before it. Attempt to truncate the operands
12400 // of the arithmetic instruction and use a reduced bit-width instruction.
12401 bool NeedTruncation = false;
12402 SDValue ArithOp = Op;
12403 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12404 SDValue Arith = Op->getOperand(0);
12405 // Both the trunc and the arithmetic op need to have one user each.
12406 if (Arith->hasOneUse())
12407 switch (Arith.getOpcode()) {
12414 NeedTruncation = true;
12420 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12421 // which may be the result of a CAST. We use the variable 'Op', which is the
12422 // non-casted variable when we check for possible users.
12423 switch (ArithOp.getOpcode()) {
12425 // Due to an isel shortcoming, be conservative if this add is likely to be
12426 // selected as part of a load-modify-store instruction. When the root node
12427 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12428 // uses of other nodes in the match, such as the ADD in this case. This
12429 // leads to the ADD being left around and reselected, with the result being
12430 // two adds in the output. Alas, even if none our users are stores, that
12431 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12432 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12433 // climbing the DAG back to the root, and it doesn't seem to be worth the
12435 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12436 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12437 if (UI->getOpcode() != ISD::CopyToReg &&
12438 UI->getOpcode() != ISD::SETCC &&
12439 UI->getOpcode() != ISD::STORE)
12442 if (ConstantSDNode *C =
12443 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12444 // An add of one will be selected as an INC.
12445 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12446 Opcode = X86ISD::INC;
12451 // An add of negative one (subtract of one) will be selected as a DEC.
12452 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12453 Opcode = X86ISD::DEC;
12459 // Otherwise use a regular EFLAGS-setting add.
12460 Opcode = X86ISD::ADD;
12465 // If we have a constant logical shift that's only used in a comparison
12466 // against zero turn it into an equivalent AND. This allows turning it into
12467 // a TEST instruction later.
12468 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12469 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12470 EVT VT = Op.getValueType();
12471 unsigned BitWidth = VT.getSizeInBits();
12472 unsigned ShAmt = Op->getConstantOperandVal(1);
12473 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12475 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12476 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12477 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12478 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12480 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12481 DAG.getConstant(Mask, VT));
12482 DAG.ReplaceAllUsesWith(Op, New);
12488 // If the primary and result isn't used, don't bother using X86ISD::AND,
12489 // because a TEST instruction will be better.
12490 if (!hasNonFlagsUse(Op))
12496 // Due to the ISEL shortcoming noted above, be conservative if this op is
12497 // likely to be selected as part of a load-modify-store instruction.
12498 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12499 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12500 if (UI->getOpcode() == ISD::STORE)
12503 // Otherwise use a regular EFLAGS-setting instruction.
12504 switch (ArithOp.getOpcode()) {
12505 default: llvm_unreachable("unexpected operator!");
12506 case ISD::SUB: Opcode = X86ISD::SUB; break;
12507 case ISD::XOR: Opcode = X86ISD::XOR; break;
12508 case ISD::AND: Opcode = X86ISD::AND; break;
12510 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12511 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12512 if (EFLAGS.getNode())
12515 Opcode = X86ISD::OR;
12529 return SDValue(Op.getNode(), 1);
12535 // If we found that truncation is beneficial, perform the truncation and
12537 if (NeedTruncation) {
12538 EVT VT = Op.getValueType();
12539 SDValue WideVal = Op->getOperand(0);
12540 EVT WideVT = WideVal.getValueType();
12541 unsigned ConvertedOp = 0;
12542 // Use a target machine opcode to prevent further DAGCombine
12543 // optimizations that may separate the arithmetic operations
12544 // from the setcc node.
12545 switch (WideVal.getOpcode()) {
12547 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12548 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12549 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12550 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12551 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12556 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12557 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12558 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12559 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12565 // Emit a CMP with 0, which is the TEST pattern.
12566 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12567 DAG.getConstant(0, Op.getValueType()));
12569 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12570 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12572 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12573 DAG.ReplaceAllUsesWith(Op, New);
12574 return SDValue(New.getNode(), 1);
12577 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12579 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12580 SDLoc dl, SelectionDAG &DAG) const {
12581 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12582 if (C->getAPIntValue() == 0)
12583 return EmitTest(Op0, X86CC, dl, DAG);
12585 if (Op0.getValueType() == MVT::i1)
12586 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12589 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12590 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12591 // Do the comparison at i32 if it's smaller, besides the Atom case.
12592 // This avoids subregister aliasing issues. Keep the smaller reference
12593 // if we're optimizing for size, however, as that'll allow better folding
12594 // of memory operations.
12595 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12596 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12597 Attribute::MinSize) &&
12598 !Subtarget->isAtom()) {
12599 unsigned ExtendOp =
12600 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12601 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12602 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12604 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12605 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12606 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12608 return SDValue(Sub.getNode(), 1);
12610 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12613 /// Convert a comparison if required by the subtarget.
12614 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12615 SelectionDAG &DAG) const {
12616 // If the subtarget does not support the FUCOMI instruction, floating-point
12617 // comparisons have to be converted.
12618 if (Subtarget->hasCMov() ||
12619 Cmp.getOpcode() != X86ISD::CMP ||
12620 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12621 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12624 // The instruction selector will select an FUCOM instruction instead of
12625 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12626 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12627 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12629 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12630 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12631 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12632 DAG.getConstant(8, MVT::i8));
12633 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12634 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12637 /// The minimum architected relative accuracy is 2^-12. We need one
12638 /// Newton-Raphson step to have a good float result (24 bits of precision).
12639 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12640 DAGCombinerInfo &DCI,
12641 unsigned &RefinementSteps,
12642 bool &UseOneConstNR) const {
12643 // FIXME: We should use instruction latency models to calculate the cost of
12644 // each potential sequence, but this is very hard to do reliably because
12645 // at least Intel's Core* chips have variable timing based on the number of
12646 // significant digits in the divisor and/or sqrt operand.
12647 if (!Subtarget->useSqrtEst())
12650 EVT VT = Op.getValueType();
12652 // SSE1 has rsqrtss and rsqrtps.
12653 // TODO: Add support for AVX512 (v16f32).
12654 // It is likely not profitable to do this for f64 because a double-precision
12655 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12656 // instructions: convert to single, rsqrtss, convert back to double, refine
12657 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12658 // along with FMA, this could be a throughput win.
12659 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12660 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12661 RefinementSteps = 1;
12662 UseOneConstNR = false;
12663 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12668 /// The minimum architected relative accuracy is 2^-12. We need one
12669 /// Newton-Raphson step to have a good float result (24 bits of precision).
12670 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12671 DAGCombinerInfo &DCI,
12672 unsigned &RefinementSteps) const {
12673 // FIXME: We should use instruction latency models to calculate the cost of
12674 // each potential sequence, but this is very hard to do reliably because
12675 // at least Intel's Core* chips have variable timing based on the number of
12676 // significant digits in the divisor.
12677 if (!Subtarget->useReciprocalEst())
12680 EVT VT = Op.getValueType();
12682 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12683 // TODO: Add support for AVX512 (v16f32).
12684 // It is likely not profitable to do this for f64 because a double-precision
12685 // reciprocal estimate with refinement on x86 prior to FMA requires
12686 // 15 instructions: convert to single, rcpss, convert back to double, refine
12687 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12688 // along with FMA, this could be a throughput win.
12689 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12690 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12691 RefinementSteps = ReciprocalEstimateRefinementSteps;
12692 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12697 static bool isAllOnes(SDValue V) {
12698 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12699 return C && C->isAllOnesValue();
12702 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12703 /// if it's possible.
12704 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12705 SDLoc dl, SelectionDAG &DAG) const {
12706 SDValue Op0 = And.getOperand(0);
12707 SDValue Op1 = And.getOperand(1);
12708 if (Op0.getOpcode() == ISD::TRUNCATE)
12709 Op0 = Op0.getOperand(0);
12710 if (Op1.getOpcode() == ISD::TRUNCATE)
12711 Op1 = Op1.getOperand(0);
12714 if (Op1.getOpcode() == ISD::SHL)
12715 std::swap(Op0, Op1);
12716 if (Op0.getOpcode() == ISD::SHL) {
12717 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12718 if (And00C->getZExtValue() == 1) {
12719 // If we looked past a truncate, check that it's only truncating away
12721 unsigned BitWidth = Op0.getValueSizeInBits();
12722 unsigned AndBitWidth = And.getValueSizeInBits();
12723 if (BitWidth > AndBitWidth) {
12725 DAG.computeKnownBits(Op0, Zeros, Ones);
12726 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12730 RHS = Op0.getOperand(1);
12732 } else if (Op1.getOpcode() == ISD::Constant) {
12733 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12734 uint64_t AndRHSVal = AndRHS->getZExtValue();
12735 SDValue AndLHS = Op0;
12737 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12738 LHS = AndLHS.getOperand(0);
12739 RHS = AndLHS.getOperand(1);
12742 // Use BT if the immediate can't be encoded in a TEST instruction.
12743 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12745 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12749 if (LHS.getNode()) {
12750 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12751 // instruction. Since the shift amount is in-range-or-undefined, we know
12752 // that doing a bittest on the i32 value is ok. We extend to i32 because
12753 // the encoding for the i16 version is larger than the i32 version.
12754 // Also promote i16 to i32 for performance / code size reason.
12755 if (LHS.getValueType() == MVT::i8 ||
12756 LHS.getValueType() == MVT::i16)
12757 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12759 // If the operand types disagree, extend the shift amount to match. Since
12760 // BT ignores high bits (like shifts) we can use anyextend.
12761 if (LHS.getValueType() != RHS.getValueType())
12762 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12764 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12765 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12766 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12767 DAG.getConstant(Cond, MVT::i8), BT);
12773 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12775 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12780 // SSE Condition code mapping:
12789 switch (SetCCOpcode) {
12790 default: llvm_unreachable("Unexpected SETCC condition");
12792 case ISD::SETEQ: SSECC = 0; break;
12794 case ISD::SETGT: Swap = true; // Fallthrough
12796 case ISD::SETOLT: SSECC = 1; break;
12798 case ISD::SETGE: Swap = true; // Fallthrough
12800 case ISD::SETOLE: SSECC = 2; break;
12801 case ISD::SETUO: SSECC = 3; break;
12803 case ISD::SETNE: SSECC = 4; break;
12804 case ISD::SETULE: Swap = true; // Fallthrough
12805 case ISD::SETUGE: SSECC = 5; break;
12806 case ISD::SETULT: Swap = true; // Fallthrough
12807 case ISD::SETUGT: SSECC = 6; break;
12808 case ISD::SETO: SSECC = 7; break;
12810 case ISD::SETONE: SSECC = 8; break;
12813 std::swap(Op0, Op1);
12818 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12819 // ones, and then concatenate the result back.
12820 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12821 MVT VT = Op.getSimpleValueType();
12823 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12824 "Unsupported value type for operation");
12826 unsigned NumElems = VT.getVectorNumElements();
12828 SDValue CC = Op.getOperand(2);
12830 // Extract the LHS vectors
12831 SDValue LHS = Op.getOperand(0);
12832 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12833 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12835 // Extract the RHS vectors
12836 SDValue RHS = Op.getOperand(1);
12837 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12838 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12840 // Issue the operation on the smaller types and concatenate the result back
12841 MVT EltVT = VT.getVectorElementType();
12842 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12843 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12844 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12845 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12848 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12849 const X86Subtarget *Subtarget) {
12850 SDValue Op0 = Op.getOperand(0);
12851 SDValue Op1 = Op.getOperand(1);
12852 SDValue CC = Op.getOperand(2);
12853 MVT VT = Op.getSimpleValueType();
12856 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12857 Op.getValueType().getScalarType() == MVT::i1 &&
12858 "Cannot set masked compare for this operation");
12860 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12862 bool Unsigned = false;
12865 switch (SetCCOpcode) {
12866 default: llvm_unreachable("Unexpected SETCC condition");
12867 case ISD::SETNE: SSECC = 4; break;
12868 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12869 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12870 case ISD::SETLT: Swap = true; //fall-through
12871 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12872 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12873 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12874 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12875 case ISD::SETULE: Unsigned = true; //fall-through
12876 case ISD::SETLE: SSECC = 2; break;
12880 std::swap(Op0, Op1);
12882 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12883 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12884 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12885 DAG.getConstant(SSECC, MVT::i8));
12888 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12889 /// operand \p Op1. If non-trivial (for example because it's not constant)
12890 /// return an empty value.
12891 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12893 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12897 MVT VT = Op1.getSimpleValueType();
12898 MVT EVT = VT.getVectorElementType();
12899 unsigned n = VT.getVectorNumElements();
12900 SmallVector<SDValue, 8> ULTOp1;
12902 for (unsigned i = 0; i < n; ++i) {
12903 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12904 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12907 // Avoid underflow.
12908 APInt Val = Elt->getAPIntValue();
12912 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12915 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12918 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12919 SelectionDAG &DAG) {
12920 SDValue Op0 = Op.getOperand(0);
12921 SDValue Op1 = Op.getOperand(1);
12922 SDValue CC = Op.getOperand(2);
12923 MVT VT = Op.getSimpleValueType();
12924 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12925 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12930 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12931 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12934 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12935 unsigned Opc = X86ISD::CMPP;
12936 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12937 assert(VT.getVectorNumElements() <= 16);
12938 Opc = X86ISD::CMPM;
12940 // In the two special cases we can't handle, emit two comparisons.
12943 unsigned CombineOpc;
12944 if (SetCCOpcode == ISD::SETUEQ) {
12945 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12947 assert(SetCCOpcode == ISD::SETONE);
12948 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12951 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12952 DAG.getConstant(CC0, MVT::i8));
12953 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12954 DAG.getConstant(CC1, MVT::i8));
12955 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12957 // Handle all other FP comparisons here.
12958 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12959 DAG.getConstant(SSECC, MVT::i8));
12962 // Break 256-bit integer vector compare into smaller ones.
12963 if (VT.is256BitVector() && !Subtarget->hasInt256())
12964 return Lower256IntVSETCC(Op, DAG);
12966 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12967 EVT OpVT = Op1.getValueType();
12968 if (Subtarget->hasAVX512()) {
12969 if (Op1.getValueType().is512BitVector() ||
12970 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12971 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12972 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12974 // In AVX-512 architecture setcc returns mask with i1 elements,
12975 // But there is no compare instruction for i8 and i16 elements in KNL.
12976 // We are not talking about 512-bit operands in this case, these
12977 // types are illegal.
12979 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12980 OpVT.getVectorElementType().getSizeInBits() >= 8))
12981 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12982 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12985 // We are handling one of the integer comparisons here. Since SSE only has
12986 // GT and EQ comparisons for integer, swapping operands and multiple
12987 // operations may be required for some comparisons.
12989 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12990 bool Subus = false;
12992 switch (SetCCOpcode) {
12993 default: llvm_unreachable("Unexpected SETCC condition");
12994 case ISD::SETNE: Invert = true;
12995 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12996 case ISD::SETLT: Swap = true;
12997 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12998 case ISD::SETGE: Swap = true;
12999 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13000 Invert = true; break;
13001 case ISD::SETULT: Swap = true;
13002 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13003 FlipSigns = true; break;
13004 case ISD::SETUGE: Swap = true;
13005 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13006 FlipSigns = true; Invert = true; break;
13009 // Special case: Use min/max operations for SETULE/SETUGE
13010 MVT VET = VT.getVectorElementType();
13012 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13013 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13016 switch (SetCCOpcode) {
13018 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13019 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13022 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13025 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13026 if (!MinMax && hasSubus) {
13027 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13029 // t = psubus Op0, Op1
13030 // pcmpeq t, <0..0>
13031 switch (SetCCOpcode) {
13033 case ISD::SETULT: {
13034 // If the comparison is against a constant we can turn this into a
13035 // setule. With psubus, setule does not require a swap. This is
13036 // beneficial because the constant in the register is no longer
13037 // destructed as the destination so it can be hoisted out of a loop.
13038 // Only do this pre-AVX since vpcmp* is no longer destructive.
13039 if (Subtarget->hasAVX())
13041 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13042 if (ULEOp1.getNode()) {
13044 Subus = true; Invert = false; Swap = false;
13048 // Psubus is better than flip-sign because it requires no inversion.
13049 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13050 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13054 Opc = X86ISD::SUBUS;
13060 std::swap(Op0, Op1);
13062 // Check that the operation in question is available (most are plain SSE2,
13063 // but PCMPGTQ and PCMPEQQ have different requirements).
13064 if (VT == MVT::v2i64) {
13065 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13066 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13068 // First cast everything to the right type.
13069 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13070 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13072 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13073 // bits of the inputs before performing those operations. The lower
13074 // compare is always unsigned.
13077 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13079 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13080 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13081 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13082 Sign, Zero, Sign, Zero);
13084 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13085 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13087 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13088 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13089 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13091 // Create masks for only the low parts/high parts of the 64 bit integers.
13092 static const int MaskHi[] = { 1, 1, 3, 3 };
13093 static const int MaskLo[] = { 0, 0, 2, 2 };
13094 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13095 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13096 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13098 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13099 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13102 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13104 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13107 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13108 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13109 // pcmpeqd + pshufd + pand.
13110 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13112 // First cast everything to the right type.
13113 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13114 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13117 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13119 // Make sure the lower and upper halves are both all-ones.
13120 static const int Mask[] = { 1, 0, 3, 2 };
13121 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13122 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13125 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13127 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13131 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13132 // bits of the inputs before performing those operations.
13134 EVT EltVT = VT.getVectorElementType();
13135 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13136 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13137 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13140 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13142 // If the logical-not of the result is required, perform that now.
13144 Result = DAG.getNOT(dl, Result, VT);
13147 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13150 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13151 getZeroVector(VT, Subtarget, DAG, dl));
13156 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13158 MVT VT = Op.getSimpleValueType();
13160 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13162 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13163 && "SetCC type must be 8-bit or 1-bit integer");
13164 SDValue Op0 = Op.getOperand(0);
13165 SDValue Op1 = Op.getOperand(1);
13167 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13169 // Optimize to BT if possible.
13170 // Lower (X & (1 << N)) == 0 to BT(X, N).
13171 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13172 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13173 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13174 Op1.getOpcode() == ISD::Constant &&
13175 cast<ConstantSDNode>(Op1)->isNullValue() &&
13176 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13177 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13178 if (NewSetCC.getNode()) {
13180 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13185 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13187 if (Op1.getOpcode() == ISD::Constant &&
13188 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13189 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13190 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13192 // If the input is a setcc, then reuse the input setcc or use a new one with
13193 // the inverted condition.
13194 if (Op0.getOpcode() == X86ISD::SETCC) {
13195 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13196 bool Invert = (CC == ISD::SETNE) ^
13197 cast<ConstantSDNode>(Op1)->isNullValue();
13201 CCode = X86::GetOppositeBranchCondition(CCode);
13202 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13203 DAG.getConstant(CCode, MVT::i8),
13204 Op0.getOperand(1));
13206 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13210 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13211 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13212 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13214 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13215 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13218 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13219 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13220 if (X86CC == X86::COND_INVALID)
13223 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13224 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13225 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13226 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13228 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13232 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13233 static bool isX86LogicalCmp(SDValue Op) {
13234 unsigned Opc = Op.getNode()->getOpcode();
13235 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13236 Opc == X86ISD::SAHF)
13238 if (Op.getResNo() == 1 &&
13239 (Opc == X86ISD::ADD ||
13240 Opc == X86ISD::SUB ||
13241 Opc == X86ISD::ADC ||
13242 Opc == X86ISD::SBB ||
13243 Opc == X86ISD::SMUL ||
13244 Opc == X86ISD::UMUL ||
13245 Opc == X86ISD::INC ||
13246 Opc == X86ISD::DEC ||
13247 Opc == X86ISD::OR ||
13248 Opc == X86ISD::XOR ||
13249 Opc == X86ISD::AND))
13252 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13258 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13259 if (V.getOpcode() != ISD::TRUNCATE)
13262 SDValue VOp0 = V.getOperand(0);
13263 unsigned InBits = VOp0.getValueSizeInBits();
13264 unsigned Bits = V.getValueSizeInBits();
13265 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13268 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13269 bool addTest = true;
13270 SDValue Cond = Op.getOperand(0);
13271 SDValue Op1 = Op.getOperand(1);
13272 SDValue Op2 = Op.getOperand(2);
13274 EVT VT = Op1.getValueType();
13277 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13278 // are available or VBLENDV if AVX is available.
13279 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13280 if (Cond.getOpcode() == ISD::SETCC &&
13281 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13282 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13283 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13284 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13285 int SSECC = translateX86FSETCC(
13286 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13289 if (Subtarget->hasAVX512()) {
13290 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13291 DAG.getConstant(SSECC, MVT::i8));
13292 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13295 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13296 DAG.getConstant(SSECC, MVT::i8));
13298 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13299 // of 3 logic instructions for size savings and potentially speed.
13300 // Unfortunately, there is no scalar form of VBLENDV.
13302 // If either operand is a constant, don't try this. We can expect to
13303 // optimize away at least one of the logic instructions later in that
13304 // case, so that sequence would be faster than a variable blend.
13306 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13307 // uses XMM0 as the selection register. That may need just as many
13308 // instructions as the AND/ANDN/OR sequence due to register moves, so
13311 if (Subtarget->hasAVX() &&
13312 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13314 // Convert to vectors, do a VSELECT, and convert back to scalar.
13315 // All of the conversions should be optimized away.
13317 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13318 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13319 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13320 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13322 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13323 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13325 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13327 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13328 VSel, DAG.getIntPtrConstant(0));
13330 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13331 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13332 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13336 if (Cond.getOpcode() == ISD::SETCC) {
13337 SDValue NewCond = LowerSETCC(Cond, DAG);
13338 if (NewCond.getNode())
13342 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13343 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13344 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13345 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13346 if (Cond.getOpcode() == X86ISD::SETCC &&
13347 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13348 isZero(Cond.getOperand(1).getOperand(1))) {
13349 SDValue Cmp = Cond.getOperand(1);
13351 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13353 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13354 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13355 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13357 SDValue CmpOp0 = Cmp.getOperand(0);
13358 // Apply further optimizations for special cases
13359 // (select (x != 0), -1, 0) -> neg & sbb
13360 // (select (x == 0), 0, -1) -> neg & sbb
13361 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13362 if (YC->isNullValue() &&
13363 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13364 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13365 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13366 DAG.getConstant(0, CmpOp0.getValueType()),
13368 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13369 DAG.getConstant(X86::COND_B, MVT::i8),
13370 SDValue(Neg.getNode(), 1));
13374 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13375 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13376 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13378 SDValue Res = // Res = 0 or -1.
13379 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13380 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13382 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13383 Res = DAG.getNOT(DL, Res, Res.getValueType());
13385 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13386 if (!N2C || !N2C->isNullValue())
13387 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13392 // Look past (and (setcc_carry (cmp ...)), 1).
13393 if (Cond.getOpcode() == ISD::AND &&
13394 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13395 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13396 if (C && C->getAPIntValue() == 1)
13397 Cond = Cond.getOperand(0);
13400 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13401 // setting operand in place of the X86ISD::SETCC.
13402 unsigned CondOpcode = Cond.getOpcode();
13403 if (CondOpcode == X86ISD::SETCC ||
13404 CondOpcode == X86ISD::SETCC_CARRY) {
13405 CC = Cond.getOperand(0);
13407 SDValue Cmp = Cond.getOperand(1);
13408 unsigned Opc = Cmp.getOpcode();
13409 MVT VT = Op.getSimpleValueType();
13411 bool IllegalFPCMov = false;
13412 if (VT.isFloatingPoint() && !VT.isVector() &&
13413 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13414 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13416 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13417 Opc == X86ISD::BT) { // FIXME
13421 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13422 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13423 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13424 Cond.getOperand(0).getValueType() != MVT::i8)) {
13425 SDValue LHS = Cond.getOperand(0);
13426 SDValue RHS = Cond.getOperand(1);
13427 unsigned X86Opcode;
13430 switch (CondOpcode) {
13431 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13432 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13433 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13434 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13435 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13436 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13437 default: llvm_unreachable("unexpected overflowing operator");
13439 if (CondOpcode == ISD::UMULO)
13440 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13443 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13445 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13447 if (CondOpcode == ISD::UMULO)
13448 Cond = X86Op.getValue(2);
13450 Cond = X86Op.getValue(1);
13452 CC = DAG.getConstant(X86Cond, MVT::i8);
13457 // Look pass the truncate if the high bits are known zero.
13458 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13459 Cond = Cond.getOperand(0);
13461 // We know the result of AND is compared against zero. Try to match
13463 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13464 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13465 if (NewSetCC.getNode()) {
13466 CC = NewSetCC.getOperand(0);
13467 Cond = NewSetCC.getOperand(1);
13474 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13475 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13478 // a < b ? -1 : 0 -> RES = ~setcc_carry
13479 // a < b ? 0 : -1 -> RES = setcc_carry
13480 // a >= b ? -1 : 0 -> RES = setcc_carry
13481 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13482 if (Cond.getOpcode() == X86ISD::SUB) {
13483 Cond = ConvertCmpIfNecessary(Cond, DAG);
13484 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13486 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13487 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13488 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13489 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13490 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13491 return DAG.getNOT(DL, Res, Res.getValueType());
13496 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13497 // widen the cmov and push the truncate through. This avoids introducing a new
13498 // branch during isel and doesn't add any extensions.
13499 if (Op.getValueType() == MVT::i8 &&
13500 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13501 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13502 if (T1.getValueType() == T2.getValueType() &&
13503 // Blacklist CopyFromReg to avoid partial register stalls.
13504 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13505 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13506 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13507 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13511 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13512 // condition is true.
13513 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13514 SDValue Ops[] = { Op2, Op1, CC, Cond };
13515 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13518 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13519 SelectionDAG &DAG) {
13520 MVT VT = Op->getSimpleValueType(0);
13521 SDValue In = Op->getOperand(0);
13522 MVT InVT = In.getSimpleValueType();
13523 MVT VTElt = VT.getVectorElementType();
13524 MVT InVTElt = InVT.getVectorElementType();
13528 if ((InVTElt == MVT::i1) &&
13529 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13530 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13532 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13533 VTElt.getSizeInBits() <= 16)) ||
13535 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13536 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13538 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13539 VTElt.getSizeInBits() >= 32))))
13540 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13542 unsigned int NumElts = VT.getVectorNumElements();
13544 if (NumElts != 8 && NumElts != 16)
13547 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13548 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13549 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13550 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13553 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13554 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13556 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13557 Constant *C = ConstantInt::get(*DAG.getContext(),
13558 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13560 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13561 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13562 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13563 MachinePointerInfo::getConstantPool(),
13564 false, false, false, Alignment);
13565 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13566 if (VT.is512BitVector())
13568 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13571 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13572 SelectionDAG &DAG) {
13573 MVT VT = Op->getSimpleValueType(0);
13574 SDValue In = Op->getOperand(0);
13575 MVT InVT = In.getSimpleValueType();
13578 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13579 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13581 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13582 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13583 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13586 if (Subtarget->hasInt256())
13587 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13589 // Optimize vectors in AVX mode
13590 // Sign extend v8i16 to v8i32 and
13593 // Divide input vector into two parts
13594 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13595 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13596 // concat the vectors to original VT
13598 unsigned NumElems = InVT.getVectorNumElements();
13599 SDValue Undef = DAG.getUNDEF(InVT);
13601 SmallVector<int,8> ShufMask1(NumElems, -1);
13602 for (unsigned i = 0; i != NumElems/2; ++i)
13605 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13607 SmallVector<int,8> ShufMask2(NumElems, -1);
13608 for (unsigned i = 0; i != NumElems/2; ++i)
13609 ShufMask2[i] = i + NumElems/2;
13611 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13613 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13614 VT.getVectorNumElements()/2);
13616 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13617 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13619 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13622 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13623 // may emit an illegal shuffle but the expansion is still better than scalar
13624 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13625 // we'll emit a shuffle and a arithmetic shift.
13626 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13627 // TODO: It is possible to support ZExt by zeroing the undef values during
13628 // the shuffle phase or after the shuffle.
13629 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13630 SelectionDAG &DAG) {
13631 MVT RegVT = Op.getSimpleValueType();
13632 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13633 assert(RegVT.isInteger() &&
13634 "We only custom lower integer vector sext loads.");
13636 // Nothing useful we can do without SSE2 shuffles.
13637 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13639 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13641 EVT MemVT = Ld->getMemoryVT();
13642 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13643 unsigned RegSz = RegVT.getSizeInBits();
13645 ISD::LoadExtType Ext = Ld->getExtensionType();
13647 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13648 && "Only anyext and sext are currently implemented.");
13649 assert(MemVT != RegVT && "Cannot extend to the same type");
13650 assert(MemVT.isVector() && "Must load a vector from memory");
13652 unsigned NumElems = RegVT.getVectorNumElements();
13653 unsigned MemSz = MemVT.getSizeInBits();
13654 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13656 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13657 // The only way in which we have a legal 256-bit vector result but not the
13658 // integer 256-bit operations needed to directly lower a sextload is if we
13659 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13660 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13661 // correctly legalized. We do this late to allow the canonical form of
13662 // sextload to persist throughout the rest of the DAG combiner -- it wants
13663 // to fold together any extensions it can, and so will fuse a sign_extend
13664 // of an sextload into a sextload targeting a wider value.
13666 if (MemSz == 128) {
13667 // Just switch this to a normal load.
13668 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13669 "it must be a legal 128-bit vector "
13671 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13672 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13673 Ld->isInvariant(), Ld->getAlignment());
13675 assert(MemSz < 128 &&
13676 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13677 // Do an sext load to a 128-bit vector type. We want to use the same
13678 // number of elements, but elements half as wide. This will end up being
13679 // recursively lowered by this routine, but will succeed as we definitely
13680 // have all the necessary features if we're using AVX1.
13682 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13683 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13685 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13686 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13687 Ld->isNonTemporal(), Ld->isInvariant(),
13688 Ld->getAlignment());
13691 // Replace chain users with the new chain.
13692 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13693 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13695 // Finally, do a normal sign-extend to the desired register.
13696 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13699 // All sizes must be a power of two.
13700 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13701 "Non-power-of-two elements are not custom lowered!");
13703 // Attempt to load the original value using scalar loads.
13704 // Find the largest scalar type that divides the total loaded size.
13705 MVT SclrLoadTy = MVT::i8;
13706 for (MVT Tp : MVT::integer_valuetypes()) {
13707 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13712 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13713 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13715 SclrLoadTy = MVT::f64;
13717 // Calculate the number of scalar loads that we need to perform
13718 // in order to load our vector from memory.
13719 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13721 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13722 "Can only lower sext loads with a single scalar load!");
13724 unsigned loadRegZize = RegSz;
13725 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13728 // Represent our vector as a sequence of elements which are the
13729 // largest scalar that we can load.
13730 EVT LoadUnitVecVT = EVT::getVectorVT(
13731 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13733 // Represent the data using the same element type that is stored in
13734 // memory. In practice, we ''widen'' MemVT.
13736 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13737 loadRegZize / MemVT.getScalarType().getSizeInBits());
13739 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13740 "Invalid vector type");
13742 // We can't shuffle using an illegal type.
13743 assert(TLI.isTypeLegal(WideVecVT) &&
13744 "We only lower types that form legal widened vector types");
13746 SmallVector<SDValue, 8> Chains;
13747 SDValue Ptr = Ld->getBasePtr();
13748 SDValue Increment =
13749 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13750 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13752 for (unsigned i = 0; i < NumLoads; ++i) {
13753 // Perform a single load.
13754 SDValue ScalarLoad =
13755 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13756 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13757 Ld->getAlignment());
13758 Chains.push_back(ScalarLoad.getValue(1));
13759 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13760 // another round of DAGCombining.
13762 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13764 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13765 ScalarLoad, DAG.getIntPtrConstant(i));
13767 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13770 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13772 // Bitcast the loaded value to a vector of the original element type, in
13773 // the size of the target vector type.
13774 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13775 unsigned SizeRatio = RegSz / MemSz;
13777 if (Ext == ISD::SEXTLOAD) {
13778 // If we have SSE4.1, we can directly emit a VSEXT node.
13779 if (Subtarget->hasSSE41()) {
13780 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13781 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13785 // Otherwise we'll shuffle the small elements in the high bits of the
13786 // larger type and perform an arithmetic shift. If the shift is not legal
13787 // it's better to scalarize.
13788 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13789 "We can't implement a sext load without an arithmetic right shift!");
13791 // Redistribute the loaded elements into the different locations.
13792 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13793 for (unsigned i = 0; i != NumElems; ++i)
13794 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13796 SDValue Shuff = DAG.getVectorShuffle(
13797 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13799 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13801 // Build the arithmetic shift.
13802 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13803 MemVT.getVectorElementType().getSizeInBits();
13805 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13807 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13811 // Redistribute the loaded elements into the different locations.
13812 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13813 for (unsigned i = 0; i != NumElems; ++i)
13814 ShuffleVec[i * SizeRatio] = i;
13816 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13817 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13819 // Bitcast to the requested type.
13820 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13821 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13825 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13826 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13827 // from the AND / OR.
13828 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13829 Opc = Op.getOpcode();
13830 if (Opc != ISD::OR && Opc != ISD::AND)
13832 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13833 Op.getOperand(0).hasOneUse() &&
13834 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13835 Op.getOperand(1).hasOneUse());
13838 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13839 // 1 and that the SETCC node has a single use.
13840 static bool isXor1OfSetCC(SDValue Op) {
13841 if (Op.getOpcode() != ISD::XOR)
13843 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13844 if (N1C && N1C->getAPIntValue() == 1) {
13845 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13846 Op.getOperand(0).hasOneUse();
13851 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13852 bool addTest = true;
13853 SDValue Chain = Op.getOperand(0);
13854 SDValue Cond = Op.getOperand(1);
13855 SDValue Dest = Op.getOperand(2);
13858 bool Inverted = false;
13860 if (Cond.getOpcode() == ISD::SETCC) {
13861 // Check for setcc([su]{add,sub,mul}o == 0).
13862 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13863 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13864 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13865 Cond.getOperand(0).getResNo() == 1 &&
13866 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13867 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13868 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13869 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13870 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13871 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13873 Cond = Cond.getOperand(0);
13875 SDValue NewCond = LowerSETCC(Cond, DAG);
13876 if (NewCond.getNode())
13881 // FIXME: LowerXALUO doesn't handle these!!
13882 else if (Cond.getOpcode() == X86ISD::ADD ||
13883 Cond.getOpcode() == X86ISD::SUB ||
13884 Cond.getOpcode() == X86ISD::SMUL ||
13885 Cond.getOpcode() == X86ISD::UMUL)
13886 Cond = LowerXALUO(Cond, DAG);
13889 // Look pass (and (setcc_carry (cmp ...)), 1).
13890 if (Cond.getOpcode() == ISD::AND &&
13891 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13892 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13893 if (C && C->getAPIntValue() == 1)
13894 Cond = Cond.getOperand(0);
13897 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13898 // setting operand in place of the X86ISD::SETCC.
13899 unsigned CondOpcode = Cond.getOpcode();
13900 if (CondOpcode == X86ISD::SETCC ||
13901 CondOpcode == X86ISD::SETCC_CARRY) {
13902 CC = Cond.getOperand(0);
13904 SDValue Cmp = Cond.getOperand(1);
13905 unsigned Opc = Cmp.getOpcode();
13906 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13907 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13911 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13915 // These can only come from an arithmetic instruction with overflow,
13916 // e.g. SADDO, UADDO.
13917 Cond = Cond.getNode()->getOperand(1);
13923 CondOpcode = Cond.getOpcode();
13924 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13925 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13926 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13927 Cond.getOperand(0).getValueType() != MVT::i8)) {
13928 SDValue LHS = Cond.getOperand(0);
13929 SDValue RHS = Cond.getOperand(1);
13930 unsigned X86Opcode;
13933 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13934 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13936 switch (CondOpcode) {
13937 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13941 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13944 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13945 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13947 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13949 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13952 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13953 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13954 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13955 default: llvm_unreachable("unexpected overflowing operator");
13958 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13959 if (CondOpcode == ISD::UMULO)
13960 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13963 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13965 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13967 if (CondOpcode == ISD::UMULO)
13968 Cond = X86Op.getValue(2);
13970 Cond = X86Op.getValue(1);
13972 CC = DAG.getConstant(X86Cond, MVT::i8);
13976 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13977 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13978 if (CondOpc == ISD::OR) {
13979 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13980 // two branches instead of an explicit OR instruction with a
13982 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13983 isX86LogicalCmp(Cmp)) {
13984 CC = Cond.getOperand(0).getOperand(0);
13985 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13986 Chain, Dest, CC, Cmp);
13987 CC = Cond.getOperand(1).getOperand(0);
13991 } else { // ISD::AND
13992 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13993 // two branches instead of an explicit AND instruction with a
13994 // separate test. However, we only do this if this block doesn't
13995 // have a fall-through edge, because this requires an explicit
13996 // jmp when the condition is false.
13997 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13998 isX86LogicalCmp(Cmp) &&
13999 Op.getNode()->hasOneUse()) {
14000 X86::CondCode CCode =
14001 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14002 CCode = X86::GetOppositeBranchCondition(CCode);
14003 CC = DAG.getConstant(CCode, MVT::i8);
14004 SDNode *User = *Op.getNode()->use_begin();
14005 // Look for an unconditional branch following this conditional branch.
14006 // We need this because we need to reverse the successors in order
14007 // to implement FCMP_OEQ.
14008 if (User->getOpcode() == ISD::BR) {
14009 SDValue FalseBB = User->getOperand(1);
14011 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14012 assert(NewBR == User);
14016 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14017 Chain, Dest, CC, Cmp);
14018 X86::CondCode CCode =
14019 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14020 CCode = X86::GetOppositeBranchCondition(CCode);
14021 CC = DAG.getConstant(CCode, MVT::i8);
14027 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14028 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14029 // It should be transformed during dag combiner except when the condition
14030 // is set by a arithmetics with overflow node.
14031 X86::CondCode CCode =
14032 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14033 CCode = X86::GetOppositeBranchCondition(CCode);
14034 CC = DAG.getConstant(CCode, MVT::i8);
14035 Cond = Cond.getOperand(0).getOperand(1);
14037 } else if (Cond.getOpcode() == ISD::SETCC &&
14038 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14039 // For FCMP_OEQ, we can emit
14040 // two branches instead of an explicit AND instruction with a
14041 // separate test. However, we only do this if this block doesn't
14042 // have a fall-through edge, because this requires an explicit
14043 // jmp when the condition is false.
14044 if (Op.getNode()->hasOneUse()) {
14045 SDNode *User = *Op.getNode()->use_begin();
14046 // Look for an unconditional branch following this conditional branch.
14047 // We need this because we need to reverse the successors in order
14048 // to implement FCMP_OEQ.
14049 if (User->getOpcode() == ISD::BR) {
14050 SDValue FalseBB = User->getOperand(1);
14052 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14053 assert(NewBR == User);
14057 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14058 Cond.getOperand(0), Cond.getOperand(1));
14059 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14060 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14061 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14062 Chain, Dest, CC, Cmp);
14063 CC = DAG.getConstant(X86::COND_P, MVT::i8);
14068 } else if (Cond.getOpcode() == ISD::SETCC &&
14069 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14070 // For FCMP_UNE, we can emit
14071 // two branches instead of an explicit AND instruction with a
14072 // separate test. However, we only do this if this block doesn't
14073 // have a fall-through edge, because this requires an explicit
14074 // jmp when the condition is false.
14075 if (Op.getNode()->hasOneUse()) {
14076 SDNode *User = *Op.getNode()->use_begin();
14077 // Look for an unconditional branch following this conditional branch.
14078 // We need this because we need to reverse the successors in order
14079 // to implement FCMP_UNE.
14080 if (User->getOpcode() == ISD::BR) {
14081 SDValue FalseBB = User->getOperand(1);
14083 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14084 assert(NewBR == User);
14087 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14088 Cond.getOperand(0), Cond.getOperand(1));
14089 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14090 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14091 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14092 Chain, Dest, CC, Cmp);
14093 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14103 // Look pass the truncate if the high bits are known zero.
14104 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14105 Cond = Cond.getOperand(0);
14107 // We know the result of AND is compared against zero. Try to match
14109 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14110 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14111 if (NewSetCC.getNode()) {
14112 CC = NewSetCC.getOperand(0);
14113 Cond = NewSetCC.getOperand(1);
14120 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14121 CC = DAG.getConstant(X86Cond, MVT::i8);
14122 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14124 Cond = ConvertCmpIfNecessary(Cond, DAG);
14125 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14126 Chain, Dest, CC, Cond);
14129 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14130 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14131 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14132 // that the guard pages used by the OS virtual memory manager are allocated in
14133 // correct sequence.
14135 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14136 SelectionDAG &DAG) const {
14137 MachineFunction &MF = DAG.getMachineFunction();
14138 bool SplitStack = MF.shouldSplitStack();
14139 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14144 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14145 SDNode* Node = Op.getNode();
14147 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14148 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14149 " not tell us which reg is the stack pointer!");
14150 EVT VT = Node->getValueType(0);
14151 SDValue Tmp1 = SDValue(Node, 0);
14152 SDValue Tmp2 = SDValue(Node, 1);
14153 SDValue Tmp3 = Node->getOperand(2);
14154 SDValue Chain = Tmp1.getOperand(0);
14156 // Chain the dynamic stack allocation so that it doesn't modify the stack
14157 // pointer when other instructions are using the stack.
14158 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14161 SDValue Size = Tmp2.getOperand(1);
14162 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14163 Chain = SP.getValue(1);
14164 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14165 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14166 unsigned StackAlign = TFI.getStackAlignment();
14167 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14168 if (Align > StackAlign)
14169 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14170 DAG.getConstant(-(uint64_t)Align, VT));
14171 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14173 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14174 DAG.getIntPtrConstant(0, true), SDValue(),
14177 SDValue Ops[2] = { Tmp1, Tmp2 };
14178 return DAG.getMergeValues(Ops, dl);
14182 SDValue Chain = Op.getOperand(0);
14183 SDValue Size = Op.getOperand(1);
14184 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14185 EVT VT = Op.getNode()->getValueType(0);
14187 bool Is64Bit = Subtarget->is64Bit();
14188 EVT SPTy = getPointerTy();
14191 MachineRegisterInfo &MRI = MF.getRegInfo();
14194 // The 64 bit implementation of segmented stacks needs to clobber both r10
14195 // r11. This makes it impossible to use it along with nested parameters.
14196 const Function *F = MF.getFunction();
14198 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14200 if (I->hasNestAttr())
14201 report_fatal_error("Cannot use segmented stacks with functions that "
14202 "have nested arguments.");
14205 const TargetRegisterClass *AddrRegClass =
14206 getRegClassFor(getPointerTy());
14207 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14208 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14209 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14210 DAG.getRegister(Vreg, SPTy));
14211 SDValue Ops1[2] = { Value, Chain };
14212 return DAG.getMergeValues(Ops1, dl);
14215 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14217 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14218 Flag = Chain.getValue(1);
14219 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14221 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14223 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14224 unsigned SPReg = RegInfo->getStackRegister();
14225 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14226 Chain = SP.getValue(1);
14229 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14230 DAG.getConstant(-(uint64_t)Align, VT));
14231 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14234 SDValue Ops1[2] = { SP, Chain };
14235 return DAG.getMergeValues(Ops1, dl);
14239 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14240 MachineFunction &MF = DAG.getMachineFunction();
14241 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14243 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14246 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14247 // vastart just stores the address of the VarArgsFrameIndex slot into the
14248 // memory location argument.
14249 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14251 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14252 MachinePointerInfo(SV), false, false, 0);
14256 // gp_offset (0 - 6 * 8)
14257 // fp_offset (48 - 48 + 8 * 16)
14258 // overflow_arg_area (point to parameters coming in memory).
14260 SmallVector<SDValue, 8> MemOps;
14261 SDValue FIN = Op.getOperand(1);
14263 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14264 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14266 FIN, MachinePointerInfo(SV), false, false, 0);
14267 MemOps.push_back(Store);
14270 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14271 FIN, DAG.getIntPtrConstant(4));
14272 Store = DAG.getStore(Op.getOperand(0), DL,
14273 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14275 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14276 MemOps.push_back(Store);
14278 // Store ptr to overflow_arg_area
14279 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14280 FIN, DAG.getIntPtrConstant(4));
14281 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14283 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14284 MachinePointerInfo(SV, 8),
14286 MemOps.push_back(Store);
14288 // Store ptr to reg_save_area.
14289 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14290 FIN, DAG.getIntPtrConstant(8));
14291 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14293 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14294 MachinePointerInfo(SV, 16), false, false, 0);
14295 MemOps.push_back(Store);
14296 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14299 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14300 assert(Subtarget->is64Bit() &&
14301 "LowerVAARG only handles 64-bit va_arg!");
14302 assert((Subtarget->isTargetLinux() ||
14303 Subtarget->isTargetDarwin()) &&
14304 "Unhandled target in LowerVAARG");
14305 assert(Op.getNode()->getNumOperands() == 4);
14306 SDValue Chain = Op.getOperand(0);
14307 SDValue SrcPtr = Op.getOperand(1);
14308 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14309 unsigned Align = Op.getConstantOperandVal(3);
14312 EVT ArgVT = Op.getNode()->getValueType(0);
14313 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14314 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14317 // Decide which area this value should be read from.
14318 // TODO: Implement the AMD64 ABI in its entirety. This simple
14319 // selection mechanism works only for the basic types.
14320 if (ArgVT == MVT::f80) {
14321 llvm_unreachable("va_arg for f80 not yet implemented");
14322 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14323 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14324 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14325 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14327 llvm_unreachable("Unhandled argument type in LowerVAARG");
14330 if (ArgMode == 2) {
14331 // Sanity Check: Make sure using fp_offset makes sense.
14332 assert(!DAG.getTarget().Options.UseSoftFloat &&
14333 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14334 Attribute::NoImplicitFloat)) &&
14335 Subtarget->hasSSE1());
14338 // Insert VAARG_64 node into the DAG
14339 // VAARG_64 returns two values: Variable Argument Address, Chain
14340 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14341 DAG.getConstant(ArgMode, MVT::i8),
14342 DAG.getConstant(Align, MVT::i32)};
14343 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14344 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14345 VTs, InstOps, MVT::i64,
14346 MachinePointerInfo(SV),
14348 /*Volatile=*/false,
14350 /*WriteMem=*/true);
14351 Chain = VAARG.getValue(1);
14353 // Load the next argument and return it
14354 return DAG.getLoad(ArgVT, dl,
14357 MachinePointerInfo(),
14358 false, false, false, 0);
14361 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14362 SelectionDAG &DAG) {
14363 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14364 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14365 SDValue Chain = Op.getOperand(0);
14366 SDValue DstPtr = Op.getOperand(1);
14367 SDValue SrcPtr = Op.getOperand(2);
14368 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14369 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14372 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14373 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14375 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14378 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14379 // amount is a constant. Takes immediate version of shift as input.
14380 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14381 SDValue SrcOp, uint64_t ShiftAmt,
14382 SelectionDAG &DAG) {
14383 MVT ElementType = VT.getVectorElementType();
14385 // Fold this packed shift into its first operand if ShiftAmt is 0.
14389 // Check for ShiftAmt >= element width
14390 if (ShiftAmt >= ElementType.getSizeInBits()) {
14391 if (Opc == X86ISD::VSRAI)
14392 ShiftAmt = ElementType.getSizeInBits() - 1;
14394 return DAG.getConstant(0, VT);
14397 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14398 && "Unknown target vector shift-by-constant node");
14400 // Fold this packed vector shift into a build vector if SrcOp is a
14401 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14402 if (VT == SrcOp.getSimpleValueType() &&
14403 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14404 SmallVector<SDValue, 8> Elts;
14405 unsigned NumElts = SrcOp->getNumOperands();
14406 ConstantSDNode *ND;
14409 default: llvm_unreachable(nullptr);
14410 case X86ISD::VSHLI:
14411 for (unsigned i=0; i!=NumElts; ++i) {
14412 SDValue CurrentOp = SrcOp->getOperand(i);
14413 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14414 Elts.push_back(CurrentOp);
14417 ND = cast<ConstantSDNode>(CurrentOp);
14418 const APInt &C = ND->getAPIntValue();
14419 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14422 case X86ISD::VSRLI:
14423 for (unsigned i=0; i!=NumElts; ++i) {
14424 SDValue CurrentOp = SrcOp->getOperand(i);
14425 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14426 Elts.push_back(CurrentOp);
14429 ND = cast<ConstantSDNode>(CurrentOp);
14430 const APInt &C = ND->getAPIntValue();
14431 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14434 case X86ISD::VSRAI:
14435 for (unsigned i=0; i!=NumElts; ++i) {
14436 SDValue CurrentOp = SrcOp->getOperand(i);
14437 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14438 Elts.push_back(CurrentOp);
14441 ND = cast<ConstantSDNode>(CurrentOp);
14442 const APInt &C = ND->getAPIntValue();
14443 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14448 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14451 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14454 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14455 // may or may not be a constant. Takes immediate version of shift as input.
14456 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14457 SDValue SrcOp, SDValue ShAmt,
14458 SelectionDAG &DAG) {
14459 MVT SVT = ShAmt.getSimpleValueType();
14460 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14462 // Catch shift-by-constant.
14463 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14464 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14465 CShAmt->getZExtValue(), DAG);
14467 // Change opcode to non-immediate version
14469 default: llvm_unreachable("Unknown target vector shift node");
14470 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14471 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14472 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14475 const X86Subtarget &Subtarget =
14476 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14477 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14478 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14479 // Let the shuffle legalizer expand this shift amount node.
14480 SDValue Op0 = ShAmt.getOperand(0);
14481 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14482 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14484 // Need to build a vector containing shift amount.
14485 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14486 SmallVector<SDValue, 4> ShOps;
14487 ShOps.push_back(ShAmt);
14488 if (SVT == MVT::i32) {
14489 ShOps.push_back(DAG.getConstant(0, SVT));
14490 ShOps.push_back(DAG.getUNDEF(SVT));
14492 ShOps.push_back(DAG.getUNDEF(SVT));
14494 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14495 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14498 // The return type has to be a 128-bit type with the same element
14499 // type as the input type.
14500 MVT EltVT = VT.getVectorElementType();
14501 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14503 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14504 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14507 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14508 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14509 /// necessary casting for \p Mask when lowering masking intrinsics.
14510 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14511 SDValue PreservedSrc,
14512 const X86Subtarget *Subtarget,
14513 SelectionDAG &DAG) {
14514 EVT VT = Op.getValueType();
14515 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14516 MVT::i1, VT.getVectorNumElements());
14517 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14518 Mask.getValueType().getSizeInBits());
14521 assert(MaskVT.isSimple() && "invalid mask type");
14523 if (isAllOnes(Mask))
14526 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14527 // are extracted by EXTRACT_SUBVECTOR.
14528 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14529 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14530 DAG.getIntPtrConstant(0));
14532 switch (Op.getOpcode()) {
14534 case X86ISD::PCMPEQM:
14535 case X86ISD::PCMPGTM:
14537 case X86ISD::CMPMU:
14538 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14540 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14541 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14542 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14545 /// \brief Creates an SDNode for a predicated scalar operation.
14546 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14547 /// The mask is comming as MVT::i8 and it should be truncated
14548 /// to MVT::i1 while lowering masking intrinsics.
14549 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14550 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14551 /// a scalar instruction.
14552 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14553 SDValue PreservedSrc,
14554 const X86Subtarget *Subtarget,
14555 SelectionDAG &DAG) {
14556 if (isAllOnes(Mask))
14559 EVT VT = Op.getValueType();
14561 // The mask should be of type MVT::i1
14562 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14564 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14565 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14566 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14569 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14570 SelectionDAG &DAG) {
14572 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14573 EVT VT = Op.getValueType();
14574 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14576 switch(IntrData->Type) {
14577 case INTR_TYPE_1OP:
14578 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14579 case INTR_TYPE_2OP:
14580 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14582 case INTR_TYPE_3OP:
14583 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14584 Op.getOperand(2), Op.getOperand(3));
14585 case INTR_TYPE_1OP_MASK_RM: {
14586 SDValue Src = Op.getOperand(1);
14587 SDValue Src0 = Op.getOperand(2);
14588 SDValue Mask = Op.getOperand(3);
14589 SDValue RoundingMode = Op.getOperand(4);
14590 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14592 Mask, Src0, Subtarget, DAG);
14594 case INTR_TYPE_SCALAR_MASK_RM: {
14595 SDValue Src1 = Op.getOperand(1);
14596 SDValue Src2 = Op.getOperand(2);
14597 SDValue Src0 = Op.getOperand(3);
14598 SDValue Mask = Op.getOperand(4);
14599 // There are 2 kinds of intrinsics in this group:
14600 // (1) With supress-all-exceptions (sae) - 6 operands
14601 // (2) With rounding mode and sae - 7 operands.
14602 if (Op.getNumOperands() == 6) {
14603 SDValue Sae = Op.getOperand(5);
14604 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14606 Mask, Src0, Subtarget, DAG);
14608 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14609 SDValue RoundingMode = Op.getOperand(5);
14610 SDValue Sae = Op.getOperand(6);
14611 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14612 RoundingMode, Sae),
14613 Mask, Src0, Subtarget, DAG);
14615 case INTR_TYPE_2OP_MASK: {
14616 SDValue Src1 = Op.getOperand(1);
14617 SDValue Src2 = Op.getOperand(2);
14618 SDValue PassThru = Op.getOperand(3);
14619 SDValue Mask = Op.getOperand(4);
14620 // We specify 2 possible opcodes for intrinsics with rounding modes.
14621 // First, we check if the intrinsic may have non-default rounding mode,
14622 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14623 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14624 if (IntrWithRoundingModeOpcode != 0) {
14625 SDValue Rnd = Op.getOperand(5);
14626 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14627 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14628 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14629 dl, Op.getValueType(),
14631 Mask, PassThru, Subtarget, DAG);
14634 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14636 Mask, PassThru, Subtarget, DAG);
14638 case FMA_OP_MASK: {
14639 SDValue Src1 = Op.getOperand(1);
14640 SDValue Src2 = Op.getOperand(2);
14641 SDValue Src3 = Op.getOperand(3);
14642 SDValue Mask = Op.getOperand(4);
14643 // We specify 2 possible opcodes for intrinsics with rounding modes.
14644 // First, we check if the intrinsic may have non-default rounding mode,
14645 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14646 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14647 if (IntrWithRoundingModeOpcode != 0) {
14648 SDValue Rnd = Op.getOperand(5);
14649 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14650 X86::STATIC_ROUNDING::CUR_DIRECTION)
14651 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14652 dl, Op.getValueType(),
14653 Src1, Src2, Src3, Rnd),
14654 Mask, Src1, Subtarget, DAG);
14656 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14657 dl, Op.getValueType(),
14659 Mask, Src1, Subtarget, DAG);
14662 case CMP_MASK_CC: {
14663 // Comparison intrinsics with masks.
14664 // Example of transformation:
14665 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14666 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14668 // (v8i1 (insert_subvector undef,
14669 // (v2i1 (and (PCMPEQM %a, %b),
14670 // (extract_subvector
14671 // (v8i1 (bitcast %mask)), 0))), 0))))
14672 EVT VT = Op.getOperand(1).getValueType();
14673 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14674 VT.getVectorNumElements());
14675 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14676 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14677 Mask.getValueType().getSizeInBits());
14679 if (IntrData->Type == CMP_MASK_CC) {
14680 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14681 Op.getOperand(2), Op.getOperand(3));
14683 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14684 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14687 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14688 DAG.getTargetConstant(0, MaskVT),
14690 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14691 DAG.getUNDEF(BitcastVT), CmpMask,
14692 DAG.getIntPtrConstant(0));
14693 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14695 case COMI: { // Comparison intrinsics
14696 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14697 SDValue LHS = Op.getOperand(1);
14698 SDValue RHS = Op.getOperand(2);
14699 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14700 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14701 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14702 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14703 DAG.getConstant(X86CC, MVT::i8), Cond);
14704 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14707 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14708 Op.getOperand(1), Op.getOperand(2), DAG);
14710 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14711 Op.getSimpleValueType(),
14713 Op.getOperand(2), DAG),
14714 Op.getOperand(4), Op.getOperand(3), Subtarget,
14716 case COMPRESS_EXPAND_IN_REG: {
14717 SDValue Mask = Op.getOperand(3);
14718 SDValue DataToCompress = Op.getOperand(1);
14719 SDValue PassThru = Op.getOperand(2);
14720 if (isAllOnes(Mask)) // return data as is
14721 return Op.getOperand(1);
14722 EVT VT = Op.getValueType();
14723 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14724 VT.getVectorNumElements());
14725 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14726 Mask.getValueType().getSizeInBits());
14728 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14729 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14730 DAG.getIntPtrConstant(0));
14732 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14736 SDValue Mask = Op.getOperand(3);
14737 EVT VT = Op.getValueType();
14738 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14739 VT.getVectorNumElements());
14740 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14741 Mask.getValueType().getSizeInBits());
14743 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14744 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14745 DAG.getIntPtrConstant(0));
14746 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14755 default: return SDValue(); // Don't custom lower most intrinsics.
14757 case Intrinsic::x86_avx2_permd:
14758 case Intrinsic::x86_avx2_permps:
14759 // Operands intentionally swapped. Mask is last operand to intrinsic,
14760 // but second operand for node/instruction.
14761 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14762 Op.getOperand(2), Op.getOperand(1));
14764 case Intrinsic::x86_avx512_mask_valign_q_512:
14765 case Intrinsic::x86_avx512_mask_valign_d_512:
14766 // Vector source operands are swapped.
14767 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14768 Op.getValueType(), Op.getOperand(2),
14771 Op.getOperand(5), Op.getOperand(4),
14774 // ptest and testp intrinsics. The intrinsic these come from are designed to
14775 // return an integer value, not just an instruction so lower it to the ptest
14776 // or testp pattern and a setcc for the result.
14777 case Intrinsic::x86_sse41_ptestz:
14778 case Intrinsic::x86_sse41_ptestc:
14779 case Intrinsic::x86_sse41_ptestnzc:
14780 case Intrinsic::x86_avx_ptestz_256:
14781 case Intrinsic::x86_avx_ptestc_256:
14782 case Intrinsic::x86_avx_ptestnzc_256:
14783 case Intrinsic::x86_avx_vtestz_ps:
14784 case Intrinsic::x86_avx_vtestc_ps:
14785 case Intrinsic::x86_avx_vtestnzc_ps:
14786 case Intrinsic::x86_avx_vtestz_pd:
14787 case Intrinsic::x86_avx_vtestc_pd:
14788 case Intrinsic::x86_avx_vtestnzc_pd:
14789 case Intrinsic::x86_avx_vtestz_ps_256:
14790 case Intrinsic::x86_avx_vtestc_ps_256:
14791 case Intrinsic::x86_avx_vtestnzc_ps_256:
14792 case Intrinsic::x86_avx_vtestz_pd_256:
14793 case Intrinsic::x86_avx_vtestc_pd_256:
14794 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14795 bool IsTestPacked = false;
14798 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14799 case Intrinsic::x86_avx_vtestz_ps:
14800 case Intrinsic::x86_avx_vtestz_pd:
14801 case Intrinsic::x86_avx_vtestz_ps_256:
14802 case Intrinsic::x86_avx_vtestz_pd_256:
14803 IsTestPacked = true; // Fallthrough
14804 case Intrinsic::x86_sse41_ptestz:
14805 case Intrinsic::x86_avx_ptestz_256:
14807 X86CC = X86::COND_E;
14809 case Intrinsic::x86_avx_vtestc_ps:
14810 case Intrinsic::x86_avx_vtestc_pd:
14811 case Intrinsic::x86_avx_vtestc_ps_256:
14812 case Intrinsic::x86_avx_vtestc_pd_256:
14813 IsTestPacked = true; // Fallthrough
14814 case Intrinsic::x86_sse41_ptestc:
14815 case Intrinsic::x86_avx_ptestc_256:
14817 X86CC = X86::COND_B;
14819 case Intrinsic::x86_avx_vtestnzc_ps:
14820 case Intrinsic::x86_avx_vtestnzc_pd:
14821 case Intrinsic::x86_avx_vtestnzc_ps_256:
14822 case Intrinsic::x86_avx_vtestnzc_pd_256:
14823 IsTestPacked = true; // Fallthrough
14824 case Intrinsic::x86_sse41_ptestnzc:
14825 case Intrinsic::x86_avx_ptestnzc_256:
14827 X86CC = X86::COND_A;
14831 SDValue LHS = Op.getOperand(1);
14832 SDValue RHS = Op.getOperand(2);
14833 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14834 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14835 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14836 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14837 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14839 case Intrinsic::x86_avx512_kortestz_w:
14840 case Intrinsic::x86_avx512_kortestc_w: {
14841 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14842 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14843 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14844 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14845 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14846 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14847 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14850 case Intrinsic::x86_sse42_pcmpistria128:
14851 case Intrinsic::x86_sse42_pcmpestria128:
14852 case Intrinsic::x86_sse42_pcmpistric128:
14853 case Intrinsic::x86_sse42_pcmpestric128:
14854 case Intrinsic::x86_sse42_pcmpistrio128:
14855 case Intrinsic::x86_sse42_pcmpestrio128:
14856 case Intrinsic::x86_sse42_pcmpistris128:
14857 case Intrinsic::x86_sse42_pcmpestris128:
14858 case Intrinsic::x86_sse42_pcmpistriz128:
14859 case Intrinsic::x86_sse42_pcmpestriz128: {
14863 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14864 case Intrinsic::x86_sse42_pcmpistria128:
14865 Opcode = X86ISD::PCMPISTRI;
14866 X86CC = X86::COND_A;
14868 case Intrinsic::x86_sse42_pcmpestria128:
14869 Opcode = X86ISD::PCMPESTRI;
14870 X86CC = X86::COND_A;
14872 case Intrinsic::x86_sse42_pcmpistric128:
14873 Opcode = X86ISD::PCMPISTRI;
14874 X86CC = X86::COND_B;
14876 case Intrinsic::x86_sse42_pcmpestric128:
14877 Opcode = X86ISD::PCMPESTRI;
14878 X86CC = X86::COND_B;
14880 case Intrinsic::x86_sse42_pcmpistrio128:
14881 Opcode = X86ISD::PCMPISTRI;
14882 X86CC = X86::COND_O;
14884 case Intrinsic::x86_sse42_pcmpestrio128:
14885 Opcode = X86ISD::PCMPESTRI;
14886 X86CC = X86::COND_O;
14888 case Intrinsic::x86_sse42_pcmpistris128:
14889 Opcode = X86ISD::PCMPISTRI;
14890 X86CC = X86::COND_S;
14892 case Intrinsic::x86_sse42_pcmpestris128:
14893 Opcode = X86ISD::PCMPESTRI;
14894 X86CC = X86::COND_S;
14896 case Intrinsic::x86_sse42_pcmpistriz128:
14897 Opcode = X86ISD::PCMPISTRI;
14898 X86CC = X86::COND_E;
14900 case Intrinsic::x86_sse42_pcmpestriz128:
14901 Opcode = X86ISD::PCMPESTRI;
14902 X86CC = X86::COND_E;
14905 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14906 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14907 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14908 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14909 DAG.getConstant(X86CC, MVT::i8),
14910 SDValue(PCMP.getNode(), 1));
14911 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14914 case Intrinsic::x86_sse42_pcmpistri128:
14915 case Intrinsic::x86_sse42_pcmpestri128: {
14917 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14918 Opcode = X86ISD::PCMPISTRI;
14920 Opcode = X86ISD::PCMPESTRI;
14922 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14923 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14924 return DAG.getNode(Opcode, dl, VTs, NewOps);
14929 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14930 SDValue Src, SDValue Mask, SDValue Base,
14931 SDValue Index, SDValue ScaleOp, SDValue Chain,
14932 const X86Subtarget * Subtarget) {
14934 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14935 assert(C && "Invalid scale type");
14936 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14937 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14938 Index.getSimpleValueType().getVectorNumElements());
14940 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14942 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14944 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14945 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14946 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14947 SDValue Segment = DAG.getRegister(0, MVT::i32);
14948 if (Src.getOpcode() == ISD::UNDEF)
14949 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14950 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14951 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14952 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14953 return DAG.getMergeValues(RetOps, dl);
14956 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14957 SDValue Src, SDValue Mask, SDValue Base,
14958 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14960 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14961 assert(C && "Invalid scale type");
14962 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14963 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14964 SDValue Segment = DAG.getRegister(0, MVT::i32);
14965 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14966 Index.getSimpleValueType().getVectorNumElements());
14968 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14970 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14972 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14973 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14974 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14975 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14976 return SDValue(Res, 1);
14979 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14980 SDValue Mask, SDValue Base, SDValue Index,
14981 SDValue ScaleOp, SDValue Chain) {
14983 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14984 assert(C && "Invalid scale type");
14985 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14986 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14987 SDValue Segment = DAG.getRegister(0, MVT::i32);
14989 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14991 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14993 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14995 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14996 //SDVTList VTs = DAG.getVTList(MVT::Other);
14997 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14998 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14999 return SDValue(Res, 0);
15002 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15003 // read performance monitor counters (x86_rdpmc).
15004 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15005 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15006 SmallVectorImpl<SDValue> &Results) {
15007 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15008 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15011 // The ECX register is used to select the index of the performance counter
15013 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15015 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15017 // Reads the content of a 64-bit performance counter and returns it in the
15018 // registers EDX:EAX.
15019 if (Subtarget->is64Bit()) {
15020 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15021 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15024 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15025 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15028 Chain = HI.getValue(1);
15030 if (Subtarget->is64Bit()) {
15031 // The EAX register is loaded with the low-order 32 bits. The EDX register
15032 // is loaded with the supported high-order bits of the counter.
15033 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15034 DAG.getConstant(32, MVT::i8));
15035 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15036 Results.push_back(Chain);
15040 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15041 SDValue Ops[] = { LO, HI };
15042 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15043 Results.push_back(Pair);
15044 Results.push_back(Chain);
15047 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15048 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15049 // also used to custom lower READCYCLECOUNTER nodes.
15050 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15051 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15052 SmallVectorImpl<SDValue> &Results) {
15053 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15054 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15057 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15058 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15059 // and the EAX register is loaded with the low-order 32 bits.
15060 if (Subtarget->is64Bit()) {
15061 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15062 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15065 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15066 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15069 SDValue Chain = HI.getValue(1);
15071 if (Opcode == X86ISD::RDTSCP_DAG) {
15072 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15074 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15075 // the ECX register. Add 'ecx' explicitly to the chain.
15076 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15078 // Explicitly store the content of ECX at the location passed in input
15079 // to the 'rdtscp' intrinsic.
15080 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15081 MachinePointerInfo(), false, false, 0);
15084 if (Subtarget->is64Bit()) {
15085 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15086 // the EAX register is loaded with the low-order 32 bits.
15087 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15088 DAG.getConstant(32, MVT::i8));
15089 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15090 Results.push_back(Chain);
15094 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15095 SDValue Ops[] = { LO, HI };
15096 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15097 Results.push_back(Pair);
15098 Results.push_back(Chain);
15101 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15102 SelectionDAG &DAG) {
15103 SmallVector<SDValue, 2> Results;
15105 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15107 return DAG.getMergeValues(Results, DL);
15111 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15112 SelectionDAG &DAG) {
15113 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15115 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15120 switch(IntrData->Type) {
15122 llvm_unreachable("Unknown Intrinsic Type");
15126 // Emit the node with the right value type.
15127 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15128 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15130 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15131 // Otherwise return the value from Rand, which is always 0, casted to i32.
15132 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15133 DAG.getConstant(1, Op->getValueType(1)),
15134 DAG.getConstant(X86::COND_B, MVT::i32),
15135 SDValue(Result.getNode(), 1) };
15136 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15137 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15140 // Return { result, isValid, chain }.
15141 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15142 SDValue(Result.getNode(), 2));
15145 //gather(v1, mask, index, base, scale);
15146 SDValue Chain = Op.getOperand(0);
15147 SDValue Src = Op.getOperand(2);
15148 SDValue Base = Op.getOperand(3);
15149 SDValue Index = Op.getOperand(4);
15150 SDValue Mask = Op.getOperand(5);
15151 SDValue Scale = Op.getOperand(6);
15152 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15156 //scatter(base, mask, index, v1, scale);
15157 SDValue Chain = Op.getOperand(0);
15158 SDValue Base = Op.getOperand(2);
15159 SDValue Mask = Op.getOperand(3);
15160 SDValue Index = Op.getOperand(4);
15161 SDValue Src = Op.getOperand(5);
15162 SDValue Scale = Op.getOperand(6);
15163 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15166 SDValue Hint = Op.getOperand(6);
15168 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15169 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15170 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15171 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15172 SDValue Chain = Op.getOperand(0);
15173 SDValue Mask = Op.getOperand(2);
15174 SDValue Index = Op.getOperand(3);
15175 SDValue Base = Op.getOperand(4);
15176 SDValue Scale = Op.getOperand(5);
15177 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15179 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15181 SmallVector<SDValue, 2> Results;
15182 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15183 return DAG.getMergeValues(Results, dl);
15185 // Read Performance Monitoring Counters.
15187 SmallVector<SDValue, 2> Results;
15188 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15189 return DAG.getMergeValues(Results, dl);
15191 // XTEST intrinsics.
15193 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15194 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15195 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15196 DAG.getConstant(X86::COND_NE, MVT::i8),
15198 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15199 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15200 Ret, SDValue(InTrans.getNode(), 1));
15204 SmallVector<SDValue, 2> Results;
15205 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15206 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15207 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15208 DAG.getConstant(-1, MVT::i8));
15209 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15210 Op.getOperand(4), GenCF.getValue(1));
15211 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15212 Op.getOperand(5), MachinePointerInfo(),
15214 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15215 DAG.getConstant(X86::COND_B, MVT::i8),
15217 Results.push_back(SetCC);
15218 Results.push_back(Store);
15219 return DAG.getMergeValues(Results, dl);
15221 case COMPRESS_TO_MEM: {
15223 SDValue Mask = Op.getOperand(4);
15224 SDValue DataToCompress = Op.getOperand(3);
15225 SDValue Addr = Op.getOperand(2);
15226 SDValue Chain = Op.getOperand(0);
15228 if (isAllOnes(Mask)) // return just a store
15229 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15230 MachinePointerInfo(), false, false, 0);
15232 EVT VT = DataToCompress.getValueType();
15233 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15234 VT.getVectorNumElements());
15235 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15236 Mask.getValueType().getSizeInBits());
15237 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15238 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15239 DAG.getIntPtrConstant(0));
15241 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15242 DataToCompress, DAG.getUNDEF(VT));
15243 return DAG.getStore(Chain, dl, Compressed, Addr,
15244 MachinePointerInfo(), false, false, 0);
15246 case EXPAND_FROM_MEM: {
15248 SDValue Mask = Op.getOperand(4);
15249 SDValue PathThru = Op.getOperand(3);
15250 SDValue Addr = Op.getOperand(2);
15251 SDValue Chain = Op.getOperand(0);
15252 EVT VT = Op.getValueType();
15254 if (isAllOnes(Mask)) // return just a load
15255 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15257 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15258 VT.getVectorNumElements());
15259 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15260 Mask.getValueType().getSizeInBits());
15261 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15262 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15263 DAG.getIntPtrConstant(0));
15265 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15266 false, false, false, 0);
15268 SDValue Results[] = {
15269 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15271 return DAG.getMergeValues(Results, dl);
15276 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15277 SelectionDAG &DAG) const {
15278 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15279 MFI->setReturnAddressIsTaken(true);
15281 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15284 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15286 EVT PtrVT = getPointerTy();
15289 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15290 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15291 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15292 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15293 DAG.getNode(ISD::ADD, dl, PtrVT,
15294 FrameAddr, Offset),
15295 MachinePointerInfo(), false, false, false, 0);
15298 // Just load the return address.
15299 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15300 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15301 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15304 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15305 MachineFunction &MF = DAG.getMachineFunction();
15306 MachineFrameInfo *MFI = MF.getFrameInfo();
15307 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15308 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15309 EVT VT = Op.getValueType();
15311 MFI->setFrameAddressIsTaken(true);
15313 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15314 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15315 // is not possible to crawl up the stack without looking at the unwind codes
15317 int FrameAddrIndex = FuncInfo->getFAIndex();
15318 if (!FrameAddrIndex) {
15319 // Set up a frame object for the return address.
15320 unsigned SlotSize = RegInfo->getSlotSize();
15321 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15322 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15323 FuncInfo->setFAIndex(FrameAddrIndex);
15325 return DAG.getFrameIndex(FrameAddrIndex, VT);
15328 unsigned FrameReg =
15329 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15330 SDLoc dl(Op); // FIXME probably not meaningful
15331 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15332 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15333 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15334 "Invalid Frame Register!");
15335 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15337 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15338 MachinePointerInfo(),
15339 false, false, false, 0);
15343 // FIXME? Maybe this could be a TableGen attribute on some registers and
15344 // this table could be generated automatically from RegInfo.
15345 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15347 unsigned Reg = StringSwitch<unsigned>(RegName)
15348 .Case("esp", X86::ESP)
15349 .Case("rsp", X86::RSP)
15353 report_fatal_error("Invalid register name global variable");
15356 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15357 SelectionDAG &DAG) const {
15358 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15359 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15362 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15363 SDValue Chain = Op.getOperand(0);
15364 SDValue Offset = Op.getOperand(1);
15365 SDValue Handler = Op.getOperand(2);
15368 EVT PtrVT = getPointerTy();
15369 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15370 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15371 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15372 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15373 "Invalid Frame Register!");
15374 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15375 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15377 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15378 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15379 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15380 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15382 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15384 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15385 DAG.getRegister(StoreAddrReg, PtrVT));
15388 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15389 SelectionDAG &DAG) const {
15391 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15392 DAG.getVTList(MVT::i32, MVT::Other),
15393 Op.getOperand(0), Op.getOperand(1));
15396 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15397 SelectionDAG &DAG) const {
15399 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15400 Op.getOperand(0), Op.getOperand(1));
15403 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15404 return Op.getOperand(0);
15407 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15408 SelectionDAG &DAG) const {
15409 SDValue Root = Op.getOperand(0);
15410 SDValue Trmp = Op.getOperand(1); // trampoline
15411 SDValue FPtr = Op.getOperand(2); // nested function
15412 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15415 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15416 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15418 if (Subtarget->is64Bit()) {
15419 SDValue OutChains[6];
15421 // Large code-model.
15422 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15423 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15425 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15426 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15428 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15430 // Load the pointer to the nested function into R11.
15431 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15432 SDValue Addr = Trmp;
15433 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15434 Addr, MachinePointerInfo(TrmpAddr),
15437 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15438 DAG.getConstant(2, MVT::i64));
15439 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15440 MachinePointerInfo(TrmpAddr, 2),
15443 // Load the 'nest' parameter value into R10.
15444 // R10 is specified in X86CallingConv.td
15445 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15446 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15447 DAG.getConstant(10, MVT::i64));
15448 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15449 Addr, MachinePointerInfo(TrmpAddr, 10),
15452 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15453 DAG.getConstant(12, MVT::i64));
15454 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15455 MachinePointerInfo(TrmpAddr, 12),
15458 // Jump to the nested function.
15459 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15460 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15461 DAG.getConstant(20, MVT::i64));
15462 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15463 Addr, MachinePointerInfo(TrmpAddr, 20),
15466 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15467 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15468 DAG.getConstant(22, MVT::i64));
15469 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15470 MachinePointerInfo(TrmpAddr, 22),
15473 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15475 const Function *Func =
15476 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15477 CallingConv::ID CC = Func->getCallingConv();
15482 llvm_unreachable("Unsupported calling convention");
15483 case CallingConv::C:
15484 case CallingConv::X86_StdCall: {
15485 // Pass 'nest' parameter in ECX.
15486 // Must be kept in sync with X86CallingConv.td
15487 NestReg = X86::ECX;
15489 // Check that ECX wasn't needed by an 'inreg' parameter.
15490 FunctionType *FTy = Func->getFunctionType();
15491 const AttributeSet &Attrs = Func->getAttributes();
15493 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15494 unsigned InRegCount = 0;
15497 for (FunctionType::param_iterator I = FTy->param_begin(),
15498 E = FTy->param_end(); I != E; ++I, ++Idx)
15499 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15500 // FIXME: should only count parameters that are lowered to integers.
15501 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15503 if (InRegCount > 2) {
15504 report_fatal_error("Nest register in use - reduce number of inreg"
15510 case CallingConv::X86_FastCall:
15511 case CallingConv::X86_ThisCall:
15512 case CallingConv::Fast:
15513 // Pass 'nest' parameter in EAX.
15514 // Must be kept in sync with X86CallingConv.td
15515 NestReg = X86::EAX;
15519 SDValue OutChains[4];
15520 SDValue Addr, Disp;
15522 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15523 DAG.getConstant(10, MVT::i32));
15524 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15526 // This is storing the opcode for MOV32ri.
15527 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15528 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15529 OutChains[0] = DAG.getStore(Root, dl,
15530 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15531 Trmp, MachinePointerInfo(TrmpAddr),
15534 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15535 DAG.getConstant(1, MVT::i32));
15536 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15537 MachinePointerInfo(TrmpAddr, 1),
15540 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15541 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15542 DAG.getConstant(5, MVT::i32));
15543 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15544 MachinePointerInfo(TrmpAddr, 5),
15547 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15548 DAG.getConstant(6, MVT::i32));
15549 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15550 MachinePointerInfo(TrmpAddr, 6),
15553 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15557 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15558 SelectionDAG &DAG) const {
15560 The rounding mode is in bits 11:10 of FPSR, and has the following
15562 00 Round to nearest
15567 FLT_ROUNDS, on the other hand, expects the following:
15574 To perform the conversion, we do:
15575 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15578 MachineFunction &MF = DAG.getMachineFunction();
15579 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15580 unsigned StackAlignment = TFI.getStackAlignment();
15581 MVT VT = Op.getSimpleValueType();
15584 // Save FP Control Word to stack slot
15585 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15586 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15588 MachineMemOperand *MMO =
15589 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15590 MachineMemOperand::MOStore, 2, 2);
15592 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15593 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15594 DAG.getVTList(MVT::Other),
15595 Ops, MVT::i16, MMO);
15597 // Load FP Control Word from stack slot
15598 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15599 MachinePointerInfo(), false, false, false, 0);
15601 // Transform as necessary
15603 DAG.getNode(ISD::SRL, DL, MVT::i16,
15604 DAG.getNode(ISD::AND, DL, MVT::i16,
15605 CWD, DAG.getConstant(0x800, MVT::i16)),
15606 DAG.getConstant(11, MVT::i8));
15608 DAG.getNode(ISD::SRL, DL, MVT::i16,
15609 DAG.getNode(ISD::AND, DL, MVT::i16,
15610 CWD, DAG.getConstant(0x400, MVT::i16)),
15611 DAG.getConstant(9, MVT::i8));
15614 DAG.getNode(ISD::AND, DL, MVT::i16,
15615 DAG.getNode(ISD::ADD, DL, MVT::i16,
15616 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15617 DAG.getConstant(1, MVT::i16)),
15618 DAG.getConstant(3, MVT::i16));
15620 return DAG.getNode((VT.getSizeInBits() < 16 ?
15621 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15624 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15625 MVT VT = Op.getSimpleValueType();
15627 unsigned NumBits = VT.getSizeInBits();
15630 Op = Op.getOperand(0);
15631 if (VT == MVT::i8) {
15632 // Zero extend to i32 since there is not an i8 bsr.
15634 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15637 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15638 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15639 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15641 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15644 DAG.getConstant(NumBits+NumBits-1, OpVT),
15645 DAG.getConstant(X86::COND_E, MVT::i8),
15648 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15650 // Finally xor with NumBits-1.
15651 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15654 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15658 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15659 MVT VT = Op.getSimpleValueType();
15661 unsigned NumBits = VT.getSizeInBits();
15664 Op = Op.getOperand(0);
15665 if (VT == MVT::i8) {
15666 // Zero extend to i32 since there is not an i8 bsr.
15668 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15671 // Issue a bsr (scan bits in reverse).
15672 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15673 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15675 // And xor with NumBits-1.
15676 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15679 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15683 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15684 MVT VT = Op.getSimpleValueType();
15685 unsigned NumBits = VT.getSizeInBits();
15687 Op = Op.getOperand(0);
15689 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15690 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15691 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15693 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15696 DAG.getConstant(NumBits, VT),
15697 DAG.getConstant(X86::COND_E, MVT::i8),
15700 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15703 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15704 // ones, and then concatenate the result back.
15705 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15706 MVT VT = Op.getSimpleValueType();
15708 assert(VT.is256BitVector() && VT.isInteger() &&
15709 "Unsupported value type for operation");
15711 unsigned NumElems = VT.getVectorNumElements();
15714 // Extract the LHS vectors
15715 SDValue LHS = Op.getOperand(0);
15716 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15717 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15719 // Extract the RHS vectors
15720 SDValue RHS = Op.getOperand(1);
15721 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15722 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15724 MVT EltVT = VT.getVectorElementType();
15725 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15727 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15728 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15729 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15732 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15733 assert(Op.getSimpleValueType().is256BitVector() &&
15734 Op.getSimpleValueType().isInteger() &&
15735 "Only handle AVX 256-bit vector integer operation");
15736 return Lower256IntArith(Op, DAG);
15739 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15740 assert(Op.getSimpleValueType().is256BitVector() &&
15741 Op.getSimpleValueType().isInteger() &&
15742 "Only handle AVX 256-bit vector integer operation");
15743 return Lower256IntArith(Op, DAG);
15746 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15747 SelectionDAG &DAG) {
15749 MVT VT = Op.getSimpleValueType();
15751 // Decompose 256-bit ops into smaller 128-bit ops.
15752 if (VT.is256BitVector() && !Subtarget->hasInt256())
15753 return Lower256IntArith(Op, DAG);
15755 SDValue A = Op.getOperand(0);
15756 SDValue B = Op.getOperand(1);
15758 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15759 if (VT == MVT::v4i32) {
15760 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15761 "Should not custom lower when pmuldq is available!");
15763 // Extract the odd parts.
15764 static const int UnpackMask[] = { 1, -1, 3, -1 };
15765 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15766 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15768 // Multiply the even parts.
15769 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15770 // Now multiply odd parts.
15771 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15773 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15774 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15776 // Merge the two vectors back together with a shuffle. This expands into 2
15778 static const int ShufMask[] = { 0, 4, 2, 6 };
15779 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15782 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15783 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15785 // Ahi = psrlqi(a, 32);
15786 // Bhi = psrlqi(b, 32);
15788 // AloBlo = pmuludq(a, b);
15789 // AloBhi = pmuludq(a, Bhi);
15790 // AhiBlo = pmuludq(Ahi, b);
15792 // AloBhi = psllqi(AloBhi, 32);
15793 // AhiBlo = psllqi(AhiBlo, 32);
15794 // return AloBlo + AloBhi + AhiBlo;
15796 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15797 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15799 // Bit cast to 32-bit vectors for MULUDQ
15800 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15801 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15802 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15803 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15804 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15805 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15807 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15808 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15809 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15811 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15812 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15814 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15815 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15818 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15819 assert(Subtarget->isTargetWin64() && "Unexpected target");
15820 EVT VT = Op.getValueType();
15821 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15822 "Unexpected return type for lowering");
15826 switch (Op->getOpcode()) {
15827 default: llvm_unreachable("Unexpected request for libcall!");
15828 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15829 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15830 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15831 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15832 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15833 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15837 SDValue InChain = DAG.getEntryNode();
15839 TargetLowering::ArgListTy Args;
15840 TargetLowering::ArgListEntry Entry;
15841 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15842 EVT ArgVT = Op->getOperand(i).getValueType();
15843 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15844 "Unexpected argument type for lowering");
15845 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15846 Entry.Node = StackPtr;
15847 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15849 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15850 Entry.Ty = PointerType::get(ArgTy,0);
15851 Entry.isSExt = false;
15852 Entry.isZExt = false;
15853 Args.push_back(Entry);
15856 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15859 TargetLowering::CallLoweringInfo CLI(DAG);
15860 CLI.setDebugLoc(dl).setChain(InChain)
15861 .setCallee(getLibcallCallingConv(LC),
15862 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15863 Callee, std::move(Args), 0)
15864 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15866 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15867 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15870 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15871 SelectionDAG &DAG) {
15872 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15873 EVT VT = Op0.getValueType();
15876 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15877 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15879 // PMULxD operations multiply each even value (starting at 0) of LHS with
15880 // the related value of RHS and produce a widen result.
15881 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15882 // => <2 x i64> <ae|cg>
15884 // In other word, to have all the results, we need to perform two PMULxD:
15885 // 1. one with the even values.
15886 // 2. one with the odd values.
15887 // To achieve #2, with need to place the odd values at an even position.
15889 // Place the odd value at an even position (basically, shift all values 1
15890 // step to the left):
15891 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15892 // <a|b|c|d> => <b|undef|d|undef>
15893 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15894 // <e|f|g|h> => <f|undef|h|undef>
15895 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15897 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15899 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15900 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15902 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15903 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15904 // => <2 x i64> <ae|cg>
15905 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15906 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15907 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15908 // => <2 x i64> <bf|dh>
15909 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15910 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15912 // Shuffle it back into the right order.
15913 SDValue Highs, Lows;
15914 if (VT == MVT::v8i32) {
15915 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15916 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15917 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15918 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15920 const int HighMask[] = {1, 5, 3, 7};
15921 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15922 const int LowMask[] = {0, 4, 2, 6};
15923 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15926 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15927 // unsigned multiply.
15928 if (IsSigned && !Subtarget->hasSSE41()) {
15930 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15931 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15932 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15933 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15934 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15936 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15937 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15940 // The first result of MUL_LOHI is actually the low value, followed by the
15942 SDValue Ops[] = {Lows, Highs};
15943 return DAG.getMergeValues(Ops, dl);
15946 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15947 const X86Subtarget *Subtarget) {
15948 MVT VT = Op.getSimpleValueType();
15950 SDValue R = Op.getOperand(0);
15951 SDValue Amt = Op.getOperand(1);
15953 // Optimize shl/srl/sra with constant shift amount.
15954 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15955 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15956 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15958 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15959 (Subtarget->hasInt256() &&
15960 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15961 (Subtarget->hasAVX512() &&
15962 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15963 if (Op.getOpcode() == ISD::SHL)
15964 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15966 if (Op.getOpcode() == ISD::SRL)
15967 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15969 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15970 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15974 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15975 unsigned NumElts = VT.getVectorNumElements();
15976 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15978 if (Op.getOpcode() == ISD::SHL) {
15979 // Make a large shift.
15980 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15982 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15983 // Zero out the rightmost bits.
15984 SmallVector<SDValue, 32> V(
15985 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15986 return DAG.getNode(ISD::AND, dl, VT, SHL,
15987 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15989 if (Op.getOpcode() == ISD::SRL) {
15990 // Make a large shift.
15991 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15993 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15994 // Zero out the leftmost bits.
15995 SmallVector<SDValue, 32> V(
15996 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15997 return DAG.getNode(ISD::AND, dl, VT, SRL,
15998 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16000 if (Op.getOpcode() == ISD::SRA) {
16001 if (ShiftAmt == 7) {
16002 // R s>> 7 === R s< 0
16003 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16004 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16007 // R s>> a === ((R u>> a) ^ m) - m
16008 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16009 SmallVector<SDValue, 32> V(NumElts,
16010 DAG.getConstant(128 >> ShiftAmt, MVT::i8));
16011 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16012 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16013 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16016 llvm_unreachable("Unknown shift opcode.");
16021 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16022 if (!Subtarget->is64Bit() &&
16023 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16024 Amt.getOpcode() == ISD::BITCAST &&
16025 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16026 Amt = Amt.getOperand(0);
16027 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16028 VT.getVectorNumElements();
16029 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16030 uint64_t ShiftAmt = 0;
16031 for (unsigned i = 0; i != Ratio; ++i) {
16032 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16036 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16038 // Check remaining shift amounts.
16039 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16040 uint64_t ShAmt = 0;
16041 for (unsigned j = 0; j != Ratio; ++j) {
16042 ConstantSDNode *C =
16043 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16047 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16049 if (ShAmt != ShiftAmt)
16052 switch (Op.getOpcode()) {
16054 llvm_unreachable("Unknown shift opcode!");
16056 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16059 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16062 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16070 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16071 const X86Subtarget* Subtarget) {
16072 MVT VT = Op.getSimpleValueType();
16074 SDValue R = Op.getOperand(0);
16075 SDValue Amt = Op.getOperand(1);
16077 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16078 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16079 (Subtarget->hasInt256() &&
16080 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16081 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16082 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16084 EVT EltVT = VT.getVectorElementType();
16086 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16087 // Check if this build_vector node is doing a splat.
16088 // If so, then set BaseShAmt equal to the splat value.
16089 BaseShAmt = BV->getSplatValue();
16090 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16091 BaseShAmt = SDValue();
16093 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16094 Amt = Amt.getOperand(0);
16096 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16097 if (SVN && SVN->isSplat()) {
16098 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16099 SDValue InVec = Amt.getOperand(0);
16100 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16101 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16102 "Unexpected shuffle index found!");
16103 BaseShAmt = InVec.getOperand(SplatIdx);
16104 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16105 if (ConstantSDNode *C =
16106 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16107 if (C->getZExtValue() == SplatIdx)
16108 BaseShAmt = InVec.getOperand(1);
16113 // Avoid introducing an extract element from a shuffle.
16114 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16115 DAG.getIntPtrConstant(SplatIdx));
16119 if (BaseShAmt.getNode()) {
16120 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16121 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16122 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16123 else if (EltVT.bitsLT(MVT::i32))
16124 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16126 switch (Op.getOpcode()) {
16128 llvm_unreachable("Unknown shift opcode!");
16130 switch (VT.SimpleTy) {
16131 default: return SDValue();
16140 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16143 switch (VT.SimpleTy) {
16144 default: return SDValue();
16151 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16154 switch (VT.SimpleTy) {
16155 default: return SDValue();
16164 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16170 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16171 if (!Subtarget->is64Bit() &&
16172 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16173 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16174 Amt.getOpcode() == ISD::BITCAST &&
16175 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16176 Amt = Amt.getOperand(0);
16177 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16178 VT.getVectorNumElements();
16179 std::vector<SDValue> Vals(Ratio);
16180 for (unsigned i = 0; i != Ratio; ++i)
16181 Vals[i] = Amt.getOperand(i);
16182 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16183 for (unsigned j = 0; j != Ratio; ++j)
16184 if (Vals[j] != Amt.getOperand(i + j))
16187 switch (Op.getOpcode()) {
16189 llvm_unreachable("Unknown shift opcode!");
16191 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16193 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16195 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16202 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16203 SelectionDAG &DAG) {
16204 MVT VT = Op.getSimpleValueType();
16206 SDValue R = Op.getOperand(0);
16207 SDValue Amt = Op.getOperand(1);
16209 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16210 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16212 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16215 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16218 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16221 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16222 if (Subtarget->hasInt256()) {
16223 if (Op.getOpcode() == ISD::SRL &&
16224 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16225 VT == MVT::v4i64 || VT == MVT::v8i32))
16227 if (Op.getOpcode() == ISD::SHL &&
16228 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16229 VT == MVT::v4i64 || VT == MVT::v8i32))
16231 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16235 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16236 // shifts per-lane and then shuffle the partial results back together.
16237 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16238 // Splat the shift amounts so the scalar shifts above will catch it.
16239 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16240 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16241 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16242 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16243 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16246 // If possible, lower this packed shift into a vector multiply instead of
16247 // expanding it into a sequence of scalar shifts.
16248 // Do this only if the vector shift count is a constant build_vector.
16249 if (Op.getOpcode() == ISD::SHL &&
16250 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16251 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16252 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16253 SmallVector<SDValue, 8> Elts;
16254 EVT SVT = VT.getScalarType();
16255 unsigned SVTBits = SVT.getSizeInBits();
16256 const APInt &One = APInt(SVTBits, 1);
16257 unsigned NumElems = VT.getVectorNumElements();
16259 for (unsigned i=0; i !=NumElems; ++i) {
16260 SDValue Op = Amt->getOperand(i);
16261 if (Op->getOpcode() == ISD::UNDEF) {
16262 Elts.push_back(Op);
16266 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16267 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16268 uint64_t ShAmt = C.getZExtValue();
16269 if (ShAmt >= SVTBits) {
16270 Elts.push_back(DAG.getUNDEF(SVT));
16273 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16275 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16276 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16279 // Lower SHL with variable shift amount.
16280 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16281 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16283 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16284 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16285 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16286 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16289 // If possible, lower this shift as a sequence of two shifts by
16290 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16292 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16294 // Could be rewritten as:
16295 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16297 // The advantage is that the two shifts from the example would be
16298 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16299 // the vector shift into four scalar shifts plus four pairs of vector
16301 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16302 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16303 unsigned TargetOpcode = X86ISD::MOVSS;
16304 bool CanBeSimplified;
16305 // The splat value for the first packed shift (the 'X' from the example).
16306 SDValue Amt1 = Amt->getOperand(0);
16307 // The splat value for the second packed shift (the 'Y' from the example).
16308 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16309 Amt->getOperand(2);
16311 // See if it is possible to replace this node with a sequence of
16312 // two shifts followed by a MOVSS/MOVSD
16313 if (VT == MVT::v4i32) {
16314 // Check if it is legal to use a MOVSS.
16315 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16316 Amt2 == Amt->getOperand(3);
16317 if (!CanBeSimplified) {
16318 // Otherwise, check if we can still simplify this node using a MOVSD.
16319 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16320 Amt->getOperand(2) == Amt->getOperand(3);
16321 TargetOpcode = X86ISD::MOVSD;
16322 Amt2 = Amt->getOperand(2);
16325 // Do similar checks for the case where the machine value type
16327 CanBeSimplified = Amt1 == Amt->getOperand(1);
16328 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16329 CanBeSimplified = Amt2 == Amt->getOperand(i);
16331 if (!CanBeSimplified) {
16332 TargetOpcode = X86ISD::MOVSD;
16333 CanBeSimplified = true;
16334 Amt2 = Amt->getOperand(4);
16335 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16336 CanBeSimplified = Amt1 == Amt->getOperand(i);
16337 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16338 CanBeSimplified = Amt2 == Amt->getOperand(j);
16342 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16343 isa<ConstantSDNode>(Amt2)) {
16344 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16345 EVT CastVT = MVT::v4i32;
16347 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16348 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16350 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16351 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16352 if (TargetOpcode == X86ISD::MOVSD)
16353 CastVT = MVT::v2i64;
16354 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16355 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16356 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16358 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16362 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16363 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16366 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16367 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16369 // Turn 'a' into a mask suitable for VSELECT
16370 SDValue VSelM = DAG.getConstant(0x80, VT);
16371 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16372 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16374 SDValue CM1 = DAG.getConstant(0x0f, VT);
16375 SDValue CM2 = DAG.getConstant(0x3f, VT);
16377 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16378 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16379 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16380 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16381 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16384 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16385 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16386 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16388 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16389 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16390 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16391 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16392 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16395 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16396 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16397 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16399 // return VSELECT(r, r+r, a);
16400 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16401 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16405 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16406 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16407 // solution better.
16408 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16409 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16411 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16412 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16413 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16414 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16415 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16418 // Decompose 256-bit shifts into smaller 128-bit shifts.
16419 if (VT.is256BitVector()) {
16420 unsigned NumElems = VT.getVectorNumElements();
16421 MVT EltVT = VT.getVectorElementType();
16422 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16424 // Extract the two vectors
16425 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16426 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16428 // Recreate the shift amount vectors
16429 SDValue Amt1, Amt2;
16430 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16431 // Constant shift amount
16432 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16433 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16434 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16436 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16437 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16439 // Variable shift amount
16440 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16441 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16444 // Issue new vector shifts for the smaller types
16445 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16446 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16448 // Concatenate the result back
16449 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16455 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16456 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16457 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16458 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16459 // has only one use.
16460 SDNode *N = Op.getNode();
16461 SDValue LHS = N->getOperand(0);
16462 SDValue RHS = N->getOperand(1);
16463 unsigned BaseOp = 0;
16466 switch (Op.getOpcode()) {
16467 default: llvm_unreachable("Unknown ovf instruction!");
16469 // A subtract of one will be selected as a INC. Note that INC doesn't
16470 // set CF, so we can't do this for UADDO.
16471 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16473 BaseOp = X86ISD::INC;
16474 Cond = X86::COND_O;
16477 BaseOp = X86ISD::ADD;
16478 Cond = X86::COND_O;
16481 BaseOp = X86ISD::ADD;
16482 Cond = X86::COND_B;
16485 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16486 // set CF, so we can't do this for USUBO.
16487 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16489 BaseOp = X86ISD::DEC;
16490 Cond = X86::COND_O;
16493 BaseOp = X86ISD::SUB;
16494 Cond = X86::COND_O;
16497 BaseOp = X86ISD::SUB;
16498 Cond = X86::COND_B;
16501 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16502 Cond = X86::COND_O;
16504 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16505 if (N->getValueType(0) == MVT::i8) {
16506 BaseOp = X86ISD::UMUL8;
16507 Cond = X86::COND_O;
16510 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16512 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16515 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16516 DAG.getConstant(X86::COND_O, MVT::i32),
16517 SDValue(Sum.getNode(), 2));
16519 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16523 // Also sets EFLAGS.
16524 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16525 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16528 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16529 DAG.getConstant(Cond, MVT::i32),
16530 SDValue(Sum.getNode(), 1));
16532 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16535 /// Returns true if the operand type is exactly twice the native width, and
16536 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16537 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16538 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16539 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16540 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16543 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16544 else if (OpWidth == 128)
16545 return Subtarget->hasCmpxchg16b();
16550 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16551 return needsCmpXchgNb(SI->getValueOperand()->getType());
16554 // Note: this turns large loads into lock cmpxchg8b/16b.
16555 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16556 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16557 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16558 return needsCmpXchgNb(PTy->getElementType());
16561 TargetLoweringBase::AtomicRMWExpansionKind
16562 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16563 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16564 const Type *MemType = AI->getType();
16566 // If the operand is too big, we must see if cmpxchg8/16b is available
16567 // and default to library calls otherwise.
16568 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16569 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16570 : AtomicRMWExpansionKind::None;
16573 AtomicRMWInst::BinOp Op = AI->getOperation();
16576 llvm_unreachable("Unknown atomic operation");
16577 case AtomicRMWInst::Xchg:
16578 case AtomicRMWInst::Add:
16579 case AtomicRMWInst::Sub:
16580 // It's better to use xadd, xsub or xchg for these in all cases.
16581 return AtomicRMWExpansionKind::None;
16582 case AtomicRMWInst::Or:
16583 case AtomicRMWInst::And:
16584 case AtomicRMWInst::Xor:
16585 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16586 // prefix to a normal instruction for these operations.
16587 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16588 : AtomicRMWExpansionKind::None;
16589 case AtomicRMWInst::Nand:
16590 case AtomicRMWInst::Max:
16591 case AtomicRMWInst::Min:
16592 case AtomicRMWInst::UMax:
16593 case AtomicRMWInst::UMin:
16594 // These always require a non-trivial set of data operations on x86. We must
16595 // use a cmpxchg loop.
16596 return AtomicRMWExpansionKind::CmpXChg;
16600 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16601 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16602 // no-sse2). There isn't any reason to disable it if the target processor
16604 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16608 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16609 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16610 const Type *MemType = AI->getType();
16611 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16612 // there is no benefit in turning such RMWs into loads, and it is actually
16613 // harmful as it introduces a mfence.
16614 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16617 auto Builder = IRBuilder<>(AI);
16618 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16619 auto SynchScope = AI->getSynchScope();
16620 // We must restrict the ordering to avoid generating loads with Release or
16621 // ReleaseAcquire orderings.
16622 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16623 auto Ptr = AI->getPointerOperand();
16625 // Before the load we need a fence. Here is an example lifted from
16626 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16629 // x.store(1, relaxed);
16630 // r1 = y.fetch_add(0, release);
16632 // y.fetch_add(42, acquire);
16633 // r2 = x.load(relaxed);
16634 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16635 // lowered to just a load without a fence. A mfence flushes the store buffer,
16636 // making the optimization clearly correct.
16637 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16638 // otherwise, we might be able to be more agressive on relaxed idempotent
16639 // rmw. In practice, they do not look useful, so we don't try to be
16640 // especially clever.
16641 if (SynchScope == SingleThread) {
16642 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16643 // the IR level, so we must wrap it in an intrinsic.
16645 } else if (hasMFENCE(*Subtarget)) {
16646 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16647 Intrinsic::x86_sse2_mfence);
16648 Builder.CreateCall(MFence);
16650 // FIXME: it might make sense to use a locked operation here but on a
16651 // different cache-line to prevent cache-line bouncing. In practice it
16652 // is probably a small win, and x86 processors without mfence are rare
16653 // enough that we do not bother.
16657 // Finally we can emit the atomic load.
16658 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16659 AI->getType()->getPrimitiveSizeInBits());
16660 Loaded->setAtomic(Order, SynchScope);
16661 AI->replaceAllUsesWith(Loaded);
16662 AI->eraseFromParent();
16666 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16667 SelectionDAG &DAG) {
16669 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16670 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16671 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16672 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16674 // The only fence that needs an instruction is a sequentially-consistent
16675 // cross-thread fence.
16676 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16677 if (hasMFENCE(*Subtarget))
16678 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16680 SDValue Chain = Op.getOperand(0);
16681 SDValue Zero = DAG.getConstant(0, MVT::i32);
16683 DAG.getRegister(X86::ESP, MVT::i32), // Base
16684 DAG.getTargetConstant(1, MVT::i8), // Scale
16685 DAG.getRegister(0, MVT::i32), // Index
16686 DAG.getTargetConstant(0, MVT::i32), // Disp
16687 DAG.getRegister(0, MVT::i32), // Segment.
16691 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16692 return SDValue(Res, 0);
16695 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16696 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16699 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16700 SelectionDAG &DAG) {
16701 MVT T = Op.getSimpleValueType();
16705 switch(T.SimpleTy) {
16706 default: llvm_unreachable("Invalid value type!");
16707 case MVT::i8: Reg = X86::AL; size = 1; break;
16708 case MVT::i16: Reg = X86::AX; size = 2; break;
16709 case MVT::i32: Reg = X86::EAX; size = 4; break;
16711 assert(Subtarget->is64Bit() && "Node not type legal!");
16712 Reg = X86::RAX; size = 8;
16715 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16716 Op.getOperand(2), SDValue());
16717 SDValue Ops[] = { cpIn.getValue(0),
16720 DAG.getTargetConstant(size, MVT::i8),
16721 cpIn.getValue(1) };
16722 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16723 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16724 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16728 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16729 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16730 MVT::i32, cpOut.getValue(2));
16731 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16732 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16734 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16735 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16736 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16740 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16741 SelectionDAG &DAG) {
16742 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16743 MVT DstVT = Op.getSimpleValueType();
16745 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16746 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16747 if (DstVT != MVT::f64)
16748 // This conversion needs to be expanded.
16751 SDValue InVec = Op->getOperand(0);
16753 unsigned NumElts = SrcVT.getVectorNumElements();
16754 EVT SVT = SrcVT.getVectorElementType();
16756 // Widen the vector in input in the case of MVT::v2i32.
16757 // Example: from MVT::v2i32 to MVT::v4i32.
16758 SmallVector<SDValue, 16> Elts;
16759 for (unsigned i = 0, e = NumElts; i != e; ++i)
16760 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16761 DAG.getIntPtrConstant(i)));
16763 // Explicitly mark the extra elements as Undef.
16764 Elts.append(NumElts, DAG.getUNDEF(SVT));
16766 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16767 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16768 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16769 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16770 DAG.getIntPtrConstant(0));
16773 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16774 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16775 assert((DstVT == MVT::i64 ||
16776 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16777 "Unexpected custom BITCAST");
16778 // i64 <=> MMX conversions are Legal.
16779 if (SrcVT==MVT::i64 && DstVT.isVector())
16781 if (DstVT==MVT::i64 && SrcVT.isVector())
16783 // MMX <=> MMX conversions are Legal.
16784 if (SrcVT.isVector() && DstVT.isVector())
16786 // All other conversions need to be expanded.
16790 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16791 SelectionDAG &DAG) {
16792 SDNode *Node = Op.getNode();
16795 Op = Op.getOperand(0);
16796 EVT VT = Op.getValueType();
16797 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16798 "CTPOP lowering only implemented for 128/256-bit wide vector types");
16800 unsigned NumElts = VT.getVectorNumElements();
16801 EVT EltVT = VT.getVectorElementType();
16802 unsigned Len = EltVT.getSizeInBits();
16804 // This is the vectorized version of the "best" algorithm from
16805 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16806 // with a minor tweak to use a series of adds + shifts instead of vector
16807 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16809 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16810 // v8i32 => Always profitable
16812 // FIXME: There a couple of possible improvements:
16814 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16815 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16817 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16818 "CTPOP not implemented for this vector element type.");
16820 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16821 // extra legalization.
16822 bool NeedsBitcast = EltVT == MVT::i32;
16823 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16825 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16826 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16827 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16829 // v = v - ((v >> 1) & 0x55555555...)
16830 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16831 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16832 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16834 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16836 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16837 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16839 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16841 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16842 if (VT != And.getValueType())
16843 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16844 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16846 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16847 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16848 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16849 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16850 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16852 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16853 if (NeedsBitcast) {
16854 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16855 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16856 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16859 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16860 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16861 if (VT != AndRHS.getValueType()) {
16862 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16863 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16865 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16867 // v = (v + (v >> 4)) & 0x0F0F0F0F...
16868 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16869 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16870 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16871 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16873 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16874 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16875 if (NeedsBitcast) {
16876 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16877 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16879 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16880 if (VT != And.getValueType())
16881 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16883 // The algorithm mentioned above uses:
16884 // v = (v * 0x01010101...) >> (Len - 8)
16886 // Change it to use vector adds + vector shifts which yield faster results on
16887 // Haswell than using vector integer multiplication.
16889 // For i32 elements:
16890 // v = v + (v >> 8)
16891 // v = v + (v >> 16)
16893 // For i64 elements:
16894 // v = v + (v >> 8)
16895 // v = v + (v >> 16)
16896 // v = v + (v >> 32)
16899 SmallVector<SDValue, 8> Csts;
16900 for (unsigned i = 8; i <= Len/2; i *= 2) {
16901 Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16902 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16903 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16904 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16908 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16909 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16910 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16911 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16912 if (NeedsBitcast) {
16913 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16914 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16916 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16917 if (VT != And.getValueType())
16918 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16923 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16924 SDNode *Node = Op.getNode();
16926 EVT T = Node->getValueType(0);
16927 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16928 DAG.getConstant(0, T), Node->getOperand(2));
16929 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16930 cast<AtomicSDNode>(Node)->getMemoryVT(),
16931 Node->getOperand(0),
16932 Node->getOperand(1), negOp,
16933 cast<AtomicSDNode>(Node)->getMemOperand(),
16934 cast<AtomicSDNode>(Node)->getOrdering(),
16935 cast<AtomicSDNode>(Node)->getSynchScope());
16938 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16939 SDNode *Node = Op.getNode();
16941 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16943 // Convert seq_cst store -> xchg
16944 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16945 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16946 // (The only way to get a 16-byte store is cmpxchg16b)
16947 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16948 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16949 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16950 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16951 cast<AtomicSDNode>(Node)->getMemoryVT(),
16952 Node->getOperand(0),
16953 Node->getOperand(1), Node->getOperand(2),
16954 cast<AtomicSDNode>(Node)->getMemOperand(),
16955 cast<AtomicSDNode>(Node)->getOrdering(),
16956 cast<AtomicSDNode>(Node)->getSynchScope());
16957 return Swap.getValue(1);
16959 // Other atomic stores have a simple pattern.
16963 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16964 EVT VT = Op.getNode()->getSimpleValueType(0);
16966 // Let legalize expand this if it isn't a legal type yet.
16967 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16970 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16973 bool ExtraOp = false;
16974 switch (Op.getOpcode()) {
16975 default: llvm_unreachable("Invalid code");
16976 case ISD::ADDC: Opc = X86ISD::ADD; break;
16977 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16978 case ISD::SUBC: Opc = X86ISD::SUB; break;
16979 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16983 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16985 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16986 Op.getOperand(1), Op.getOperand(2));
16989 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16990 SelectionDAG &DAG) {
16991 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16993 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16994 // which returns the values as { float, float } (in XMM0) or
16995 // { double, double } (which is returned in XMM0, XMM1).
16997 SDValue Arg = Op.getOperand(0);
16998 EVT ArgVT = Arg.getValueType();
16999 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17001 TargetLowering::ArgListTy Args;
17002 TargetLowering::ArgListEntry Entry;
17006 Entry.isSExt = false;
17007 Entry.isZExt = false;
17008 Args.push_back(Entry);
17010 bool isF64 = ArgVT == MVT::f64;
17011 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17012 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17013 // the results are returned via SRet in memory.
17014 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17015 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17016 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17018 Type *RetTy = isF64
17019 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17020 : (Type*)VectorType::get(ArgTy, 4);
17022 TargetLowering::CallLoweringInfo CLI(DAG);
17023 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17024 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17026 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17029 // Returned in xmm0 and xmm1.
17030 return CallResult.first;
17032 // Returned in bits 0:31 and 32:64 xmm0.
17033 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17034 CallResult.first, DAG.getIntPtrConstant(0));
17035 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17036 CallResult.first, DAG.getIntPtrConstant(1));
17037 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17038 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17041 /// LowerOperation - Provide custom lowering hooks for some operations.
17043 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17044 switch (Op.getOpcode()) {
17045 default: llvm_unreachable("Should not custom lower this!");
17046 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17047 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17048 return LowerCMP_SWAP(Op, Subtarget, DAG);
17049 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
17050 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17051 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17052 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17053 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17054 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17055 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17056 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17057 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17058 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17059 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17060 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17061 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17062 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17063 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17064 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17065 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17066 case ISD::SHL_PARTS:
17067 case ISD::SRA_PARTS:
17068 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17069 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17070 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17071 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17072 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17073 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17074 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17075 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17076 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17077 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17078 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17080 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17081 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17082 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17083 case ISD::SETCC: return LowerSETCC(Op, DAG);
17084 case ISD::SELECT: return LowerSELECT(Op, DAG);
17085 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17086 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17087 case ISD::VASTART: return LowerVASTART(Op, DAG);
17088 case ISD::VAARG: return LowerVAARG(Op, DAG);
17089 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17090 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17091 case ISD::INTRINSIC_VOID:
17092 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17093 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17094 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17095 case ISD::FRAME_TO_ARGS_OFFSET:
17096 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17097 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17098 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17099 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17100 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17101 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17102 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17103 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17104 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17105 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17106 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17107 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17108 case ISD::UMUL_LOHI:
17109 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17112 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17118 case ISD::UMULO: return LowerXALUO(Op, DAG);
17119 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17120 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17124 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17125 case ISD::ADD: return LowerADD(Op, DAG);
17126 case ISD::SUB: return LowerSUB(Op, DAG);
17127 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17131 /// ReplaceNodeResults - Replace a node with an illegal result type
17132 /// with a new node built out of custom code.
17133 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17134 SmallVectorImpl<SDValue>&Results,
17135 SelectionDAG &DAG) const {
17137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17138 switch (N->getOpcode()) {
17140 llvm_unreachable("Do not know how to custom type legalize this operation!");
17141 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17142 case X86ISD::FMINC:
17144 case X86ISD::FMAXC:
17145 case X86ISD::FMAX: {
17146 EVT VT = N->getValueType(0);
17147 if (VT != MVT::v2f32)
17148 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17149 SDValue UNDEF = DAG.getUNDEF(VT);
17150 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17151 N->getOperand(0), UNDEF);
17152 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17153 N->getOperand(1), UNDEF);
17154 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17157 case ISD::SIGN_EXTEND_INREG:
17162 // We don't want to expand or promote these.
17169 case ISD::UDIVREM: {
17170 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17171 Results.push_back(V);
17174 case ISD::FP_TO_SINT:
17175 case ISD::FP_TO_UINT: {
17176 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17178 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17181 std::pair<SDValue,SDValue> Vals =
17182 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17183 SDValue FIST = Vals.first, StackSlot = Vals.second;
17184 if (FIST.getNode()) {
17185 EVT VT = N->getValueType(0);
17186 // Return a load from the stack slot.
17187 if (StackSlot.getNode())
17188 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17189 MachinePointerInfo(),
17190 false, false, false, 0));
17192 Results.push_back(FIST);
17196 case ISD::UINT_TO_FP: {
17197 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17198 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17199 N->getValueType(0) != MVT::v2f32)
17201 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17203 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17205 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17206 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17207 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17208 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17209 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17210 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17213 case ISD::FP_ROUND: {
17214 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17216 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17217 Results.push_back(V);
17220 case ISD::INTRINSIC_W_CHAIN: {
17221 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17223 default : llvm_unreachable("Do not know how to custom type "
17224 "legalize this intrinsic operation!");
17225 case Intrinsic::x86_rdtsc:
17226 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17228 case Intrinsic::x86_rdtscp:
17229 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17231 case Intrinsic::x86_rdpmc:
17232 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17235 case ISD::READCYCLECOUNTER: {
17236 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17239 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17240 EVT T = N->getValueType(0);
17241 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17242 bool Regs64bit = T == MVT::i128;
17243 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17244 SDValue cpInL, cpInH;
17245 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17246 DAG.getConstant(0, HalfT));
17247 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17248 DAG.getConstant(1, HalfT));
17249 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17250 Regs64bit ? X86::RAX : X86::EAX,
17252 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17253 Regs64bit ? X86::RDX : X86::EDX,
17254 cpInH, cpInL.getValue(1));
17255 SDValue swapInL, swapInH;
17256 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17257 DAG.getConstant(0, HalfT));
17258 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17259 DAG.getConstant(1, HalfT));
17260 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17261 Regs64bit ? X86::RBX : X86::EBX,
17262 swapInL, cpInH.getValue(1));
17263 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17264 Regs64bit ? X86::RCX : X86::ECX,
17265 swapInH, swapInL.getValue(1));
17266 SDValue Ops[] = { swapInH.getValue(0),
17268 swapInH.getValue(1) };
17269 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17270 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17271 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17272 X86ISD::LCMPXCHG8_DAG;
17273 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17274 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17275 Regs64bit ? X86::RAX : X86::EAX,
17276 HalfT, Result.getValue(1));
17277 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17278 Regs64bit ? X86::RDX : X86::EDX,
17279 HalfT, cpOutL.getValue(2));
17280 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17282 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17283 MVT::i32, cpOutH.getValue(2));
17285 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17286 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17287 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17289 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17290 Results.push_back(Success);
17291 Results.push_back(EFLAGS.getValue(1));
17294 case ISD::ATOMIC_SWAP:
17295 case ISD::ATOMIC_LOAD_ADD:
17296 case ISD::ATOMIC_LOAD_SUB:
17297 case ISD::ATOMIC_LOAD_AND:
17298 case ISD::ATOMIC_LOAD_OR:
17299 case ISD::ATOMIC_LOAD_XOR:
17300 case ISD::ATOMIC_LOAD_NAND:
17301 case ISD::ATOMIC_LOAD_MIN:
17302 case ISD::ATOMIC_LOAD_MAX:
17303 case ISD::ATOMIC_LOAD_UMIN:
17304 case ISD::ATOMIC_LOAD_UMAX:
17305 case ISD::ATOMIC_LOAD: {
17306 // Delegate to generic TypeLegalization. Situations we can really handle
17307 // should have already been dealt with by AtomicExpandPass.cpp.
17310 case ISD::BITCAST: {
17311 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17312 EVT DstVT = N->getValueType(0);
17313 EVT SrcVT = N->getOperand(0)->getValueType(0);
17315 if (SrcVT != MVT::f64 ||
17316 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17319 unsigned NumElts = DstVT.getVectorNumElements();
17320 EVT SVT = DstVT.getVectorElementType();
17321 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17322 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17323 MVT::v2f64, N->getOperand(0));
17324 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17326 if (ExperimentalVectorWideningLegalization) {
17327 // If we are legalizing vectors by widening, we already have the desired
17328 // legal vector type, just return it.
17329 Results.push_back(ToVecInt);
17333 SmallVector<SDValue, 8> Elts;
17334 for (unsigned i = 0, e = NumElts; i != e; ++i)
17335 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17336 ToVecInt, DAG.getIntPtrConstant(i)));
17338 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17343 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17345 default: return nullptr;
17346 case X86ISD::BSF: return "X86ISD::BSF";
17347 case X86ISD::BSR: return "X86ISD::BSR";
17348 case X86ISD::SHLD: return "X86ISD::SHLD";
17349 case X86ISD::SHRD: return "X86ISD::SHRD";
17350 case X86ISD::FAND: return "X86ISD::FAND";
17351 case X86ISD::FANDN: return "X86ISD::FANDN";
17352 case X86ISD::FOR: return "X86ISD::FOR";
17353 case X86ISD::FXOR: return "X86ISD::FXOR";
17354 case X86ISD::FSRL: return "X86ISD::FSRL";
17355 case X86ISD::FILD: return "X86ISD::FILD";
17356 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17357 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17358 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17359 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17360 case X86ISD::FLD: return "X86ISD::FLD";
17361 case X86ISD::FST: return "X86ISD::FST";
17362 case X86ISD::CALL: return "X86ISD::CALL";
17363 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17364 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17365 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17366 case X86ISD::BT: return "X86ISD::BT";
17367 case X86ISD::CMP: return "X86ISD::CMP";
17368 case X86ISD::COMI: return "X86ISD::COMI";
17369 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17370 case X86ISD::CMPM: return "X86ISD::CMPM";
17371 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17372 case X86ISD::SETCC: return "X86ISD::SETCC";
17373 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17374 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17375 case X86ISD::CMOV: return "X86ISD::CMOV";
17376 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17377 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17378 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17379 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17380 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17381 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17382 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17383 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17384 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17385 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17386 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17387 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17388 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17389 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17390 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17391 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17392 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17393 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17394 case X86ISD::HADD: return "X86ISD::HADD";
17395 case X86ISD::HSUB: return "X86ISD::HSUB";
17396 case X86ISD::FHADD: return "X86ISD::FHADD";
17397 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17398 case X86ISD::UMAX: return "X86ISD::UMAX";
17399 case X86ISD::UMIN: return "X86ISD::UMIN";
17400 case X86ISD::SMAX: return "X86ISD::SMAX";
17401 case X86ISD::SMIN: return "X86ISD::SMIN";
17402 case X86ISD::FMAX: return "X86ISD::FMAX";
17403 case X86ISD::FMIN: return "X86ISD::FMIN";
17404 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17405 case X86ISD::FMINC: return "X86ISD::FMINC";
17406 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17407 case X86ISD::FRCP: return "X86ISD::FRCP";
17408 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17409 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17410 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17411 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17412 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17413 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17414 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17415 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17416 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17417 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17418 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17419 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17420 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17421 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17422 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17423 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17424 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17425 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17426 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17427 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17428 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17429 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17430 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17431 case X86ISD::VSHL: return "X86ISD::VSHL";
17432 case X86ISD::VSRL: return "X86ISD::VSRL";
17433 case X86ISD::VSRA: return "X86ISD::VSRA";
17434 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17435 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17436 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17437 case X86ISD::CMPP: return "X86ISD::CMPP";
17438 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17439 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17440 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17441 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17442 case X86ISD::ADD: return "X86ISD::ADD";
17443 case X86ISD::SUB: return "X86ISD::SUB";
17444 case X86ISD::ADC: return "X86ISD::ADC";
17445 case X86ISD::SBB: return "X86ISD::SBB";
17446 case X86ISD::SMUL: return "X86ISD::SMUL";
17447 case X86ISD::UMUL: return "X86ISD::UMUL";
17448 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17449 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17450 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17451 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17452 case X86ISD::INC: return "X86ISD::INC";
17453 case X86ISD::DEC: return "X86ISD::DEC";
17454 case X86ISD::OR: return "X86ISD::OR";
17455 case X86ISD::XOR: return "X86ISD::XOR";
17456 case X86ISD::AND: return "X86ISD::AND";
17457 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17458 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17459 case X86ISD::PTEST: return "X86ISD::PTEST";
17460 case X86ISD::TESTP: return "X86ISD::TESTP";
17461 case X86ISD::TESTM: return "X86ISD::TESTM";
17462 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17463 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17464 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17465 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17466 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17467 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17468 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17469 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17470 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17471 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17472 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17473 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17474 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17475 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17476 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17477 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17478 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17479 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17480 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17481 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17482 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17483 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17484 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17485 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17486 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17487 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17488 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17489 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17490 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17491 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17492 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17493 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17494 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17495 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17496 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17497 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17498 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17499 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17500 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17501 case X86ISD::SAHF: return "X86ISD::SAHF";
17502 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17503 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17504 case X86ISD::FMADD: return "X86ISD::FMADD";
17505 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17506 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17507 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17508 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17509 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17510 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17511 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17512 case X86ISD::XTEST: return "X86ISD::XTEST";
17513 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17514 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17515 case X86ISD::SELECT: return "X86ISD::SELECT";
17516 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17517 case X86ISD::RCP28: return "X86ISD::RCP28";
17518 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17519 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17520 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17521 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17522 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17526 // isLegalAddressingMode - Return true if the addressing mode represented
17527 // by AM is legal for this target, for a load/store of the specified type.
17528 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17530 // X86 supports extremely general addressing modes.
17531 CodeModel::Model M = getTargetMachine().getCodeModel();
17532 Reloc::Model R = getTargetMachine().getRelocationModel();
17534 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17535 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17540 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17542 // If a reference to this global requires an extra load, we can't fold it.
17543 if (isGlobalStubReference(GVFlags))
17546 // If BaseGV requires a register for the PIC base, we cannot also have a
17547 // BaseReg specified.
17548 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17551 // If lower 4G is not available, then we must use rip-relative addressing.
17552 if ((M != CodeModel::Small || R != Reloc::Static) &&
17553 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17557 switch (AM.Scale) {
17563 // These scales always work.
17568 // These scales are formed with basereg+scalereg. Only accept if there is
17573 default: // Other stuff never works.
17580 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17581 unsigned Bits = Ty->getScalarSizeInBits();
17583 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17584 // particularly cheaper than those without.
17588 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17589 // variable shifts just as cheap as scalar ones.
17590 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17593 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17594 // fully general vector.
17598 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17599 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17601 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17602 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17603 return NumBits1 > NumBits2;
17606 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17607 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17610 if (!isTypeLegal(EVT::getEVT(Ty1)))
17613 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17615 // Assuming the caller doesn't have a zeroext or signext return parameter,
17616 // truncation all the way down to i1 is valid.
17620 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17621 return isInt<32>(Imm);
17624 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17625 // Can also use sub to handle negated immediates.
17626 return isInt<32>(Imm);
17629 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17630 if (!VT1.isInteger() || !VT2.isInteger())
17632 unsigned NumBits1 = VT1.getSizeInBits();
17633 unsigned NumBits2 = VT2.getSizeInBits();
17634 return NumBits1 > NumBits2;
17637 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17638 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17639 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17642 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17643 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17644 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17647 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17648 EVT VT1 = Val.getValueType();
17649 if (isZExtFree(VT1, VT2))
17652 if (Val.getOpcode() != ISD::LOAD)
17655 if (!VT1.isSimple() || !VT1.isInteger() ||
17656 !VT2.isSimple() || !VT2.isInteger())
17659 switch (VT1.getSimpleVT().SimpleTy) {
17664 // X86 has 8, 16, and 32-bit zero-extending loads.
17671 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17674 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17675 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17678 VT = VT.getScalarType();
17680 if (!VT.isSimple())
17683 switch (VT.getSimpleVT().SimpleTy) {
17694 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17695 // i16 instructions are longer (0x66 prefix) and potentially slower.
17696 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17699 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17700 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17701 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17702 /// are assumed to be legal.
17704 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17706 if (!VT.isSimple())
17709 // Very little shuffling can be done for 64-bit vectors right now.
17710 if (VT.getSizeInBits() == 64)
17713 // We only care that the types being shuffled are legal. The lowering can
17714 // handle any possible shuffle mask that results.
17715 return isTypeLegal(VT.getSimpleVT());
17719 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17721 // Just delegate to the generic legality, clear masks aren't special.
17722 return isShuffleMaskLegal(Mask, VT);
17725 //===----------------------------------------------------------------------===//
17726 // X86 Scheduler Hooks
17727 //===----------------------------------------------------------------------===//
17729 /// Utility function to emit xbegin specifying the start of an RTM region.
17730 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17731 const TargetInstrInfo *TII) {
17732 DebugLoc DL = MI->getDebugLoc();
17734 const BasicBlock *BB = MBB->getBasicBlock();
17735 MachineFunction::iterator I = MBB;
17738 // For the v = xbegin(), we generate
17749 MachineBasicBlock *thisMBB = MBB;
17750 MachineFunction *MF = MBB->getParent();
17751 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17752 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17753 MF->insert(I, mainMBB);
17754 MF->insert(I, sinkMBB);
17756 // Transfer the remainder of BB and its successor edges to sinkMBB.
17757 sinkMBB->splice(sinkMBB->begin(), MBB,
17758 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17759 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17763 // # fallthrough to mainMBB
17764 // # abortion to sinkMBB
17765 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17766 thisMBB->addSuccessor(mainMBB);
17767 thisMBB->addSuccessor(sinkMBB);
17771 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17772 mainMBB->addSuccessor(sinkMBB);
17775 // EAX is live into the sinkMBB
17776 sinkMBB->addLiveIn(X86::EAX);
17777 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17778 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17781 MI->eraseFromParent();
17785 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17786 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17787 // in the .td file.
17788 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17789 const TargetInstrInfo *TII) {
17791 switch (MI->getOpcode()) {
17792 default: llvm_unreachable("illegal opcode!");
17793 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17794 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17795 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17796 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17797 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17798 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17799 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17800 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17803 DebugLoc dl = MI->getDebugLoc();
17804 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17806 unsigned NumArgs = MI->getNumOperands();
17807 for (unsigned i = 1; i < NumArgs; ++i) {
17808 MachineOperand &Op = MI->getOperand(i);
17809 if (!(Op.isReg() && Op.isImplicit()))
17810 MIB.addOperand(Op);
17812 if (MI->hasOneMemOperand())
17813 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17815 BuildMI(*BB, MI, dl,
17816 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17817 .addReg(X86::XMM0);
17819 MI->eraseFromParent();
17823 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17824 // defs in an instruction pattern
17825 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17826 const TargetInstrInfo *TII) {
17828 switch (MI->getOpcode()) {
17829 default: llvm_unreachable("illegal opcode!");
17830 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17831 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17832 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17833 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17834 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17835 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17836 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17837 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17840 DebugLoc dl = MI->getDebugLoc();
17841 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17843 unsigned NumArgs = MI->getNumOperands(); // remove the results
17844 for (unsigned i = 1; i < NumArgs; ++i) {
17845 MachineOperand &Op = MI->getOperand(i);
17846 if (!(Op.isReg() && Op.isImplicit()))
17847 MIB.addOperand(Op);
17849 if (MI->hasOneMemOperand())
17850 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17852 BuildMI(*BB, MI, dl,
17853 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17856 MI->eraseFromParent();
17860 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17861 const X86Subtarget *Subtarget) {
17862 DebugLoc dl = MI->getDebugLoc();
17863 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17864 // Address into RAX/EAX, other two args into ECX, EDX.
17865 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17866 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17867 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17868 for (int i = 0; i < X86::AddrNumOperands; ++i)
17869 MIB.addOperand(MI->getOperand(i));
17871 unsigned ValOps = X86::AddrNumOperands;
17872 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17873 .addReg(MI->getOperand(ValOps).getReg());
17874 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17875 .addReg(MI->getOperand(ValOps+1).getReg());
17877 // The instruction doesn't actually take any operands though.
17878 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17880 MI->eraseFromParent(); // The pseudo is gone now.
17884 MachineBasicBlock *
17885 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17886 MachineBasicBlock *MBB) const {
17887 // Emit va_arg instruction on X86-64.
17889 // Operands to this pseudo-instruction:
17890 // 0 ) Output : destination address (reg)
17891 // 1-5) Input : va_list address (addr, i64mem)
17892 // 6 ) ArgSize : Size (in bytes) of vararg type
17893 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17894 // 8 ) Align : Alignment of type
17895 // 9 ) EFLAGS (implicit-def)
17897 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17898 static_assert(X86::AddrNumOperands == 5,
17899 "VAARG_64 assumes 5 address operands");
17901 unsigned DestReg = MI->getOperand(0).getReg();
17902 MachineOperand &Base = MI->getOperand(1);
17903 MachineOperand &Scale = MI->getOperand(2);
17904 MachineOperand &Index = MI->getOperand(3);
17905 MachineOperand &Disp = MI->getOperand(4);
17906 MachineOperand &Segment = MI->getOperand(5);
17907 unsigned ArgSize = MI->getOperand(6).getImm();
17908 unsigned ArgMode = MI->getOperand(7).getImm();
17909 unsigned Align = MI->getOperand(8).getImm();
17911 // Memory Reference
17912 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17913 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17914 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17916 // Machine Information
17917 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17918 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17919 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17920 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17921 DebugLoc DL = MI->getDebugLoc();
17923 // struct va_list {
17926 // i64 overflow_area (address)
17927 // i64 reg_save_area (address)
17929 // sizeof(va_list) = 24
17930 // alignment(va_list) = 8
17932 unsigned TotalNumIntRegs = 6;
17933 unsigned TotalNumXMMRegs = 8;
17934 bool UseGPOffset = (ArgMode == 1);
17935 bool UseFPOffset = (ArgMode == 2);
17936 unsigned MaxOffset = TotalNumIntRegs * 8 +
17937 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17939 /* Align ArgSize to a multiple of 8 */
17940 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17941 bool NeedsAlign = (Align > 8);
17943 MachineBasicBlock *thisMBB = MBB;
17944 MachineBasicBlock *overflowMBB;
17945 MachineBasicBlock *offsetMBB;
17946 MachineBasicBlock *endMBB;
17948 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17949 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17950 unsigned OffsetReg = 0;
17952 if (!UseGPOffset && !UseFPOffset) {
17953 // If we only pull from the overflow region, we don't create a branch.
17954 // We don't need to alter control flow.
17955 OffsetDestReg = 0; // unused
17956 OverflowDestReg = DestReg;
17958 offsetMBB = nullptr;
17959 overflowMBB = thisMBB;
17962 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17963 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17964 // If not, pull from overflow_area. (branch to overflowMBB)
17969 // offsetMBB overflowMBB
17974 // Registers for the PHI in endMBB
17975 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17976 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17978 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17979 MachineFunction *MF = MBB->getParent();
17980 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17981 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17982 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17984 MachineFunction::iterator MBBIter = MBB;
17987 // Insert the new basic blocks
17988 MF->insert(MBBIter, offsetMBB);
17989 MF->insert(MBBIter, overflowMBB);
17990 MF->insert(MBBIter, endMBB);
17992 // Transfer the remainder of MBB and its successor edges to endMBB.
17993 endMBB->splice(endMBB->begin(), thisMBB,
17994 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17995 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17997 // Make offsetMBB and overflowMBB successors of thisMBB
17998 thisMBB->addSuccessor(offsetMBB);
17999 thisMBB->addSuccessor(overflowMBB);
18001 // endMBB is a successor of both offsetMBB and overflowMBB
18002 offsetMBB->addSuccessor(endMBB);
18003 overflowMBB->addSuccessor(endMBB);
18005 // Load the offset value into a register
18006 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18007 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18011 .addDisp(Disp, UseFPOffset ? 4 : 0)
18012 .addOperand(Segment)
18013 .setMemRefs(MMOBegin, MMOEnd);
18015 // Check if there is enough room left to pull this argument.
18016 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18018 .addImm(MaxOffset + 8 - ArgSizeA8);
18020 // Branch to "overflowMBB" if offset >= max
18021 // Fall through to "offsetMBB" otherwise
18022 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18023 .addMBB(overflowMBB);
18026 // In offsetMBB, emit code to use the reg_save_area.
18028 assert(OffsetReg != 0);
18030 // Read the reg_save_area address.
18031 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18032 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18037 .addOperand(Segment)
18038 .setMemRefs(MMOBegin, MMOEnd);
18040 // Zero-extend the offset
18041 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18042 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18045 .addImm(X86::sub_32bit);
18047 // Add the offset to the reg_save_area to get the final address.
18048 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18049 .addReg(OffsetReg64)
18050 .addReg(RegSaveReg);
18052 // Compute the offset for the next argument
18053 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18054 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18056 .addImm(UseFPOffset ? 16 : 8);
18058 // Store it back into the va_list.
18059 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18063 .addDisp(Disp, UseFPOffset ? 4 : 0)
18064 .addOperand(Segment)
18065 .addReg(NextOffsetReg)
18066 .setMemRefs(MMOBegin, MMOEnd);
18069 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18074 // Emit code to use overflow area
18077 // Load the overflow_area address into a register.
18078 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18079 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18084 .addOperand(Segment)
18085 .setMemRefs(MMOBegin, MMOEnd);
18087 // If we need to align it, do so. Otherwise, just copy the address
18088 // to OverflowDestReg.
18090 // Align the overflow address
18091 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18092 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18094 // aligned_addr = (addr + (align-1)) & ~(align-1)
18095 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18096 .addReg(OverflowAddrReg)
18099 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18101 .addImm(~(uint64_t)(Align-1));
18103 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18104 .addReg(OverflowAddrReg);
18107 // Compute the next overflow address after this argument.
18108 // (the overflow address should be kept 8-byte aligned)
18109 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18110 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18111 .addReg(OverflowDestReg)
18112 .addImm(ArgSizeA8);
18114 // Store the new overflow address.
18115 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18120 .addOperand(Segment)
18121 .addReg(NextAddrReg)
18122 .setMemRefs(MMOBegin, MMOEnd);
18124 // If we branched, emit the PHI to the front of endMBB.
18126 BuildMI(*endMBB, endMBB->begin(), DL,
18127 TII->get(X86::PHI), DestReg)
18128 .addReg(OffsetDestReg).addMBB(offsetMBB)
18129 .addReg(OverflowDestReg).addMBB(overflowMBB);
18132 // Erase the pseudo instruction
18133 MI->eraseFromParent();
18138 MachineBasicBlock *
18139 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18141 MachineBasicBlock *MBB) const {
18142 // Emit code to save XMM registers to the stack. The ABI says that the
18143 // number of registers to save is given in %al, so it's theoretically
18144 // possible to do an indirect jump trick to avoid saving all of them,
18145 // however this code takes a simpler approach and just executes all
18146 // of the stores if %al is non-zero. It's less code, and it's probably
18147 // easier on the hardware branch predictor, and stores aren't all that
18148 // expensive anyway.
18150 // Create the new basic blocks. One block contains all the XMM stores,
18151 // and one block is the final destination regardless of whether any
18152 // stores were performed.
18153 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18154 MachineFunction *F = MBB->getParent();
18155 MachineFunction::iterator MBBIter = MBB;
18157 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18158 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18159 F->insert(MBBIter, XMMSaveMBB);
18160 F->insert(MBBIter, EndMBB);
18162 // Transfer the remainder of MBB and its successor edges to EndMBB.
18163 EndMBB->splice(EndMBB->begin(), MBB,
18164 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18165 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18167 // The original block will now fall through to the XMM save block.
18168 MBB->addSuccessor(XMMSaveMBB);
18169 // The XMMSaveMBB will fall through to the end block.
18170 XMMSaveMBB->addSuccessor(EndMBB);
18172 // Now add the instructions.
18173 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18174 DebugLoc DL = MI->getDebugLoc();
18176 unsigned CountReg = MI->getOperand(0).getReg();
18177 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18178 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18180 if (!Subtarget->isTargetWin64()) {
18181 // If %al is 0, branch around the XMM save block.
18182 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18183 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18184 MBB->addSuccessor(EndMBB);
18187 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18188 // that was just emitted, but clearly shouldn't be "saved".
18189 assert((MI->getNumOperands() <= 3 ||
18190 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18191 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18192 && "Expected last argument to be EFLAGS");
18193 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18194 // In the XMM save block, save all the XMM argument registers.
18195 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18196 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18197 MachineMemOperand *MMO =
18198 F->getMachineMemOperand(
18199 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18200 MachineMemOperand::MOStore,
18201 /*Size=*/16, /*Align=*/16);
18202 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18203 .addFrameIndex(RegSaveFrameIndex)
18204 .addImm(/*Scale=*/1)
18205 .addReg(/*IndexReg=*/0)
18206 .addImm(/*Disp=*/Offset)
18207 .addReg(/*Segment=*/0)
18208 .addReg(MI->getOperand(i).getReg())
18209 .addMemOperand(MMO);
18212 MI->eraseFromParent(); // The pseudo instruction is gone now.
18217 // The EFLAGS operand of SelectItr might be missing a kill marker
18218 // because there were multiple uses of EFLAGS, and ISel didn't know
18219 // which to mark. Figure out whether SelectItr should have had a
18220 // kill marker, and set it if it should. Returns the correct kill
18222 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18223 MachineBasicBlock* BB,
18224 const TargetRegisterInfo* TRI) {
18225 // Scan forward through BB for a use/def of EFLAGS.
18226 MachineBasicBlock::iterator miI(std::next(SelectItr));
18227 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18228 const MachineInstr& mi = *miI;
18229 if (mi.readsRegister(X86::EFLAGS))
18231 if (mi.definesRegister(X86::EFLAGS))
18232 break; // Should have kill-flag - update below.
18235 // If we hit the end of the block, check whether EFLAGS is live into a
18237 if (miI == BB->end()) {
18238 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18239 sEnd = BB->succ_end();
18240 sItr != sEnd; ++sItr) {
18241 MachineBasicBlock* succ = *sItr;
18242 if (succ->isLiveIn(X86::EFLAGS))
18247 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18248 // out. SelectMI should have a kill flag on EFLAGS.
18249 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18253 MachineBasicBlock *
18254 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18255 MachineBasicBlock *BB) const {
18256 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18257 DebugLoc DL = MI->getDebugLoc();
18259 // To "insert" a SELECT_CC instruction, we actually have to insert the
18260 // diamond control-flow pattern. The incoming instruction knows the
18261 // destination vreg to set, the condition code register to branch on, the
18262 // true/false values to select between, and a branch opcode to use.
18263 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18264 MachineFunction::iterator It = BB;
18270 // cmpTY ccX, r1, r2
18272 // fallthrough --> copy0MBB
18273 MachineBasicBlock *thisMBB = BB;
18274 MachineFunction *F = BB->getParent();
18276 // We also lower double CMOVs:
18277 // (CMOV (CMOV F, T, cc1), T, cc2)
18278 // to two successives branches. For that, we look for another CMOV as the
18279 // following instruction.
18281 // Without this, we would add a PHI between the two jumps, which ends up
18282 // creating a few copies all around. For instance, for
18284 // (sitofp (zext (fcmp une)))
18286 // we would generate:
18288 // ucomiss %xmm1, %xmm0
18289 // movss <1.0f>, %xmm0
18290 // movaps %xmm0, %xmm1
18292 // xorps %xmm1, %xmm1
18295 // movaps %xmm1, %xmm0
18299 // because this custom-inserter would have generated:
18311 // A: X = ...; Y = ...
18313 // C: Z = PHI [X, A], [Y, B]
18315 // E: PHI [X, C], [Z, D]
18317 // If we lower both CMOVs in a single step, we can instead generate:
18329 // A: X = ...; Y = ...
18331 // E: PHI [X, A], [X, C], [Y, D]
18333 // Which, in our sitofp/fcmp example, gives us something like:
18335 // ucomiss %xmm1, %xmm0
18336 // movss <1.0f>, %xmm0
18339 // xorps %xmm0, %xmm0
18343 MachineInstr *NextCMOV = nullptr;
18344 MachineBasicBlock::iterator NextMIIt =
18345 std::next(MachineBasicBlock::iterator(MI));
18346 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18347 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18348 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18349 NextCMOV = &*NextMIIt;
18351 MachineBasicBlock *jcc1MBB = nullptr;
18353 // If we have a double CMOV, we lower it to two successive branches to
18354 // the same block. EFLAGS is used by both, so mark it as live in the second.
18356 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18357 F->insert(It, jcc1MBB);
18358 jcc1MBB->addLiveIn(X86::EFLAGS);
18361 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18362 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18363 F->insert(It, copy0MBB);
18364 F->insert(It, sinkMBB);
18366 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18367 // live into the sink and copy blocks.
18368 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18370 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18371 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18372 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18373 copy0MBB->addLiveIn(X86::EFLAGS);
18374 sinkMBB->addLiveIn(X86::EFLAGS);
18377 // Transfer the remainder of BB and its successor edges to sinkMBB.
18378 sinkMBB->splice(sinkMBB->begin(), BB,
18379 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18380 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18382 // Add the true and fallthrough blocks as its successors.
18384 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18385 BB->addSuccessor(jcc1MBB);
18387 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18388 // jump to the sinkMBB.
18389 jcc1MBB->addSuccessor(copy0MBB);
18390 jcc1MBB->addSuccessor(sinkMBB);
18392 BB->addSuccessor(copy0MBB);
18395 // The true block target of the first (or only) branch is always sinkMBB.
18396 BB->addSuccessor(sinkMBB);
18398 // Create the conditional branch instruction.
18400 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18401 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18404 unsigned Opc2 = X86::GetCondBranchFromCond(
18405 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18406 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18410 // %FalseValue = ...
18411 // # fallthrough to sinkMBB
18412 copy0MBB->addSuccessor(sinkMBB);
18415 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18417 MachineInstrBuilder MIB =
18418 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18419 MI->getOperand(0).getReg())
18420 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18421 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18423 // If we have a double CMOV, the second Jcc provides the same incoming
18424 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18426 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18427 // Copy the PHI result to the register defined by the second CMOV.
18428 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18429 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18430 .addReg(MI->getOperand(0).getReg());
18431 NextCMOV->eraseFromParent();
18434 MI->eraseFromParent(); // The pseudo instruction is gone now.
18438 MachineBasicBlock *
18439 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18440 MachineBasicBlock *BB) const {
18441 MachineFunction *MF = BB->getParent();
18442 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18443 DebugLoc DL = MI->getDebugLoc();
18444 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18446 assert(MF->shouldSplitStack());
18448 const bool Is64Bit = Subtarget->is64Bit();
18449 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18451 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18452 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18455 // ... [Till the alloca]
18456 // If stacklet is not large enough, jump to mallocMBB
18459 // Allocate by subtracting from RSP
18460 // Jump to continueMBB
18463 // Allocate by call to runtime
18467 // [rest of original BB]
18470 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18471 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18472 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18474 MachineRegisterInfo &MRI = MF->getRegInfo();
18475 const TargetRegisterClass *AddrRegClass =
18476 getRegClassFor(getPointerTy());
18478 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18479 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18480 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18481 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18482 sizeVReg = MI->getOperand(1).getReg(),
18483 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18485 MachineFunction::iterator MBBIter = BB;
18488 MF->insert(MBBIter, bumpMBB);
18489 MF->insert(MBBIter, mallocMBB);
18490 MF->insert(MBBIter, continueMBB);
18492 continueMBB->splice(continueMBB->begin(), BB,
18493 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18494 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18496 // Add code to the main basic block to check if the stack limit has been hit,
18497 // and if so, jump to mallocMBB otherwise to bumpMBB.
18498 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18499 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18500 .addReg(tmpSPVReg).addReg(sizeVReg);
18501 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18502 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18503 .addReg(SPLimitVReg);
18504 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18506 // bumpMBB simply decreases the stack pointer, since we know the current
18507 // stacklet has enough space.
18508 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18509 .addReg(SPLimitVReg);
18510 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18511 .addReg(SPLimitVReg);
18512 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18514 // Calls into a routine in libgcc to allocate more space from the heap.
18515 const uint32_t *RegMask =
18516 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18518 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18520 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18521 .addExternalSymbol("__morestack_allocate_stack_space")
18522 .addRegMask(RegMask)
18523 .addReg(X86::RDI, RegState::Implicit)
18524 .addReg(X86::RAX, RegState::ImplicitDefine);
18525 } else if (Is64Bit) {
18526 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18528 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18529 .addExternalSymbol("__morestack_allocate_stack_space")
18530 .addRegMask(RegMask)
18531 .addReg(X86::EDI, RegState::Implicit)
18532 .addReg(X86::EAX, RegState::ImplicitDefine);
18534 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18536 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18537 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18538 .addExternalSymbol("__morestack_allocate_stack_space")
18539 .addRegMask(RegMask)
18540 .addReg(X86::EAX, RegState::ImplicitDefine);
18544 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18547 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18548 .addReg(IsLP64 ? X86::RAX : X86::EAX);
18549 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18551 // Set up the CFG correctly.
18552 BB->addSuccessor(bumpMBB);
18553 BB->addSuccessor(mallocMBB);
18554 mallocMBB->addSuccessor(continueMBB);
18555 bumpMBB->addSuccessor(continueMBB);
18557 // Take care of the PHI nodes.
18558 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18559 MI->getOperand(0).getReg())
18560 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18561 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18563 // Delete the original pseudo instruction.
18564 MI->eraseFromParent();
18567 return continueMBB;
18570 MachineBasicBlock *
18571 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18572 MachineBasicBlock *BB) const {
18573 DebugLoc DL = MI->getDebugLoc();
18575 assert(!Subtarget->isTargetMachO());
18577 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18579 MI->eraseFromParent(); // The pseudo instruction is gone now.
18583 MachineBasicBlock *
18584 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18585 MachineBasicBlock *BB) const {
18586 // This is pretty easy. We're taking the value that we received from
18587 // our load from the relocation, sticking it in either RDI (x86-64)
18588 // or EAX and doing an indirect call. The return value will then
18589 // be in the normal return register.
18590 MachineFunction *F = BB->getParent();
18591 const X86InstrInfo *TII = Subtarget->getInstrInfo();
18592 DebugLoc DL = MI->getDebugLoc();
18594 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18595 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18597 // Get a register mask for the lowered call.
18598 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18599 // proper register mask.
18600 const uint32_t *RegMask =
18601 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18602 if (Subtarget->is64Bit()) {
18603 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18604 TII->get(X86::MOV64rm), X86::RDI)
18606 .addImm(0).addReg(0)
18607 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18608 MI->getOperand(3).getTargetFlags())
18610 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18611 addDirectMem(MIB, X86::RDI);
18612 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18613 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18614 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18615 TII->get(X86::MOV32rm), X86::EAX)
18617 .addImm(0).addReg(0)
18618 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18619 MI->getOperand(3).getTargetFlags())
18621 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18622 addDirectMem(MIB, X86::EAX);
18623 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18625 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18626 TII->get(X86::MOV32rm), X86::EAX)
18627 .addReg(TII->getGlobalBaseReg(F))
18628 .addImm(0).addReg(0)
18629 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18630 MI->getOperand(3).getTargetFlags())
18632 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18633 addDirectMem(MIB, X86::EAX);
18634 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18637 MI->eraseFromParent(); // The pseudo instruction is gone now.
18641 MachineBasicBlock *
18642 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18643 MachineBasicBlock *MBB) const {
18644 DebugLoc DL = MI->getDebugLoc();
18645 MachineFunction *MF = MBB->getParent();
18646 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18647 MachineRegisterInfo &MRI = MF->getRegInfo();
18649 const BasicBlock *BB = MBB->getBasicBlock();
18650 MachineFunction::iterator I = MBB;
18653 // Memory Reference
18654 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18655 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18658 unsigned MemOpndSlot = 0;
18660 unsigned CurOp = 0;
18662 DstReg = MI->getOperand(CurOp++).getReg();
18663 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18664 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18665 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18666 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18668 MemOpndSlot = CurOp;
18670 MVT PVT = getPointerTy();
18671 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18672 "Invalid Pointer Size!");
18674 // For v = setjmp(buf), we generate
18677 // buf[LabelOffset] = restoreMBB
18678 // SjLjSetup restoreMBB
18684 // v = phi(main, restore)
18687 // if base pointer being used, load it from frame
18690 MachineBasicBlock *thisMBB = MBB;
18691 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18692 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18693 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18694 MF->insert(I, mainMBB);
18695 MF->insert(I, sinkMBB);
18696 MF->push_back(restoreMBB);
18698 MachineInstrBuilder MIB;
18700 // Transfer the remainder of BB and its successor edges to sinkMBB.
18701 sinkMBB->splice(sinkMBB->begin(), MBB,
18702 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18703 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18706 unsigned PtrStoreOpc = 0;
18707 unsigned LabelReg = 0;
18708 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18709 Reloc::Model RM = MF->getTarget().getRelocationModel();
18710 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18711 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18713 // Prepare IP either in reg or imm.
18714 if (!UseImmLabel) {
18715 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18716 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18717 LabelReg = MRI.createVirtualRegister(PtrRC);
18718 if (Subtarget->is64Bit()) {
18719 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18723 .addMBB(restoreMBB)
18726 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18727 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18728 .addReg(XII->getGlobalBaseReg(MF))
18731 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18735 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18737 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18738 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18739 if (i == X86::AddrDisp)
18740 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18742 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18745 MIB.addReg(LabelReg);
18747 MIB.addMBB(restoreMBB);
18748 MIB.setMemRefs(MMOBegin, MMOEnd);
18750 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18751 .addMBB(restoreMBB);
18753 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18754 MIB.addRegMask(RegInfo->getNoPreservedMask());
18755 thisMBB->addSuccessor(mainMBB);
18756 thisMBB->addSuccessor(restoreMBB);
18760 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18761 mainMBB->addSuccessor(sinkMBB);
18764 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18765 TII->get(X86::PHI), DstReg)
18766 .addReg(mainDstReg).addMBB(mainMBB)
18767 .addReg(restoreDstReg).addMBB(restoreMBB);
18770 if (RegInfo->hasBasePointer(*MF)) {
18771 const bool Uses64BitFramePtr =
18772 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18773 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18774 X86FI->setRestoreBasePointer(MF);
18775 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18776 unsigned BasePtr = RegInfo->getBaseRegister();
18777 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18778 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18779 FramePtr, true, X86FI->getRestoreBasePointerOffset())
18780 .setMIFlag(MachineInstr::FrameSetup);
18782 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18783 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18784 restoreMBB->addSuccessor(sinkMBB);
18786 MI->eraseFromParent();
18790 MachineBasicBlock *
18791 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18792 MachineBasicBlock *MBB) const {
18793 DebugLoc DL = MI->getDebugLoc();
18794 MachineFunction *MF = MBB->getParent();
18795 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18796 MachineRegisterInfo &MRI = MF->getRegInfo();
18798 // Memory Reference
18799 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18800 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18802 MVT PVT = getPointerTy();
18803 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18804 "Invalid Pointer Size!");
18806 const TargetRegisterClass *RC =
18807 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18808 unsigned Tmp = MRI.createVirtualRegister(RC);
18809 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18810 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18811 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18812 unsigned SP = RegInfo->getStackRegister();
18814 MachineInstrBuilder MIB;
18816 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18817 const int64_t SPOffset = 2 * PVT.getStoreSize();
18819 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18820 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18823 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18824 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18825 MIB.addOperand(MI->getOperand(i));
18826 MIB.setMemRefs(MMOBegin, MMOEnd);
18828 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18829 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18830 if (i == X86::AddrDisp)
18831 MIB.addDisp(MI->getOperand(i), LabelOffset);
18833 MIB.addOperand(MI->getOperand(i));
18835 MIB.setMemRefs(MMOBegin, MMOEnd);
18837 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18838 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18839 if (i == X86::AddrDisp)
18840 MIB.addDisp(MI->getOperand(i), SPOffset);
18842 MIB.addOperand(MI->getOperand(i));
18844 MIB.setMemRefs(MMOBegin, MMOEnd);
18846 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18848 MI->eraseFromParent();
18852 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18853 // accumulator loops. Writing back to the accumulator allows the coalescer
18854 // to remove extra copies in the loop.
18855 MachineBasicBlock *
18856 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18857 MachineBasicBlock *MBB) const {
18858 MachineOperand &AddendOp = MI->getOperand(3);
18860 // Bail out early if the addend isn't a register - we can't switch these.
18861 if (!AddendOp.isReg())
18864 MachineFunction &MF = *MBB->getParent();
18865 MachineRegisterInfo &MRI = MF.getRegInfo();
18867 // Check whether the addend is defined by a PHI:
18868 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18869 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18870 if (!AddendDef.isPHI())
18873 // Look for the following pattern:
18875 // %addend = phi [%entry, 0], [%loop, %result]
18877 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18881 // %addend = phi [%entry, 0], [%loop, %result]
18883 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18885 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18886 assert(AddendDef.getOperand(i).isReg());
18887 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18888 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18889 if (&PHISrcInst == MI) {
18890 // Found a matching instruction.
18891 unsigned NewFMAOpc = 0;
18892 switch (MI->getOpcode()) {
18893 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18894 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18895 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18896 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18897 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18898 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18899 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18900 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18901 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18902 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18903 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18904 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18905 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18906 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18907 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18908 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18909 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18910 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18911 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18912 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18914 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18915 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18916 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18917 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18918 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18919 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18920 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18921 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18922 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18923 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18924 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18925 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18926 default: llvm_unreachable("Unrecognized FMA variant.");
18929 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18930 MachineInstrBuilder MIB =
18931 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18932 .addOperand(MI->getOperand(0))
18933 .addOperand(MI->getOperand(3))
18934 .addOperand(MI->getOperand(2))
18935 .addOperand(MI->getOperand(1));
18936 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18937 MI->eraseFromParent();
18944 MachineBasicBlock *
18945 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18946 MachineBasicBlock *BB) const {
18947 switch (MI->getOpcode()) {
18948 default: llvm_unreachable("Unexpected instr type to insert");
18949 case X86::TAILJMPd64:
18950 case X86::TAILJMPr64:
18951 case X86::TAILJMPm64:
18952 case X86::TAILJMPd64_REX:
18953 case X86::TAILJMPr64_REX:
18954 case X86::TAILJMPm64_REX:
18955 llvm_unreachable("TAILJMP64 would not be touched here.");
18956 case X86::TCRETURNdi64:
18957 case X86::TCRETURNri64:
18958 case X86::TCRETURNmi64:
18960 case X86::WIN_ALLOCA:
18961 return EmitLoweredWinAlloca(MI, BB);
18962 case X86::SEG_ALLOCA_32:
18963 case X86::SEG_ALLOCA_64:
18964 return EmitLoweredSegAlloca(MI, BB);
18965 case X86::TLSCall_32:
18966 case X86::TLSCall_64:
18967 return EmitLoweredTLSCall(MI, BB);
18968 case X86::CMOV_GR8:
18969 case X86::CMOV_FR32:
18970 case X86::CMOV_FR64:
18971 case X86::CMOV_V4F32:
18972 case X86::CMOV_V2F64:
18973 case X86::CMOV_V2I64:
18974 case X86::CMOV_V8F32:
18975 case X86::CMOV_V4F64:
18976 case X86::CMOV_V4I64:
18977 case X86::CMOV_V16F32:
18978 case X86::CMOV_V8F64:
18979 case X86::CMOV_V8I64:
18980 case X86::CMOV_GR16:
18981 case X86::CMOV_GR32:
18982 case X86::CMOV_RFP32:
18983 case X86::CMOV_RFP64:
18984 case X86::CMOV_RFP80:
18985 return EmitLoweredSelect(MI, BB);
18987 case X86::FP32_TO_INT16_IN_MEM:
18988 case X86::FP32_TO_INT32_IN_MEM:
18989 case X86::FP32_TO_INT64_IN_MEM:
18990 case X86::FP64_TO_INT16_IN_MEM:
18991 case X86::FP64_TO_INT32_IN_MEM:
18992 case X86::FP64_TO_INT64_IN_MEM:
18993 case X86::FP80_TO_INT16_IN_MEM:
18994 case X86::FP80_TO_INT32_IN_MEM:
18995 case X86::FP80_TO_INT64_IN_MEM: {
18996 MachineFunction *F = BB->getParent();
18997 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18998 DebugLoc DL = MI->getDebugLoc();
19000 // Change the floating point control register to use "round towards zero"
19001 // mode when truncating to an integer value.
19002 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19003 addFrameReference(BuildMI(*BB, MI, DL,
19004 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19006 // Load the old value of the high byte of the control word...
19008 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19009 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19012 // Set the high part to be round to zero...
19013 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19016 // Reload the modified control word now...
19017 addFrameReference(BuildMI(*BB, MI, DL,
19018 TII->get(X86::FLDCW16m)), CWFrameIdx);
19020 // Restore the memory image of control word to original value
19021 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19024 // Get the X86 opcode to use.
19026 switch (MI->getOpcode()) {
19027 default: llvm_unreachable("illegal opcode!");
19028 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19029 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19030 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19031 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19032 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19033 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19034 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19035 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19036 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19040 MachineOperand &Op = MI->getOperand(0);
19042 AM.BaseType = X86AddressMode::RegBase;
19043 AM.Base.Reg = Op.getReg();
19045 AM.BaseType = X86AddressMode::FrameIndexBase;
19046 AM.Base.FrameIndex = Op.getIndex();
19048 Op = MI->getOperand(1);
19050 AM.Scale = Op.getImm();
19051 Op = MI->getOperand(2);
19053 AM.IndexReg = Op.getImm();
19054 Op = MI->getOperand(3);
19055 if (Op.isGlobal()) {
19056 AM.GV = Op.getGlobal();
19058 AM.Disp = Op.getImm();
19060 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19061 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19063 // Reload the original control word now.
19064 addFrameReference(BuildMI(*BB, MI, DL,
19065 TII->get(X86::FLDCW16m)), CWFrameIdx);
19067 MI->eraseFromParent(); // The pseudo instruction is gone now.
19070 // String/text processing lowering.
19071 case X86::PCMPISTRM128REG:
19072 case X86::VPCMPISTRM128REG:
19073 case X86::PCMPISTRM128MEM:
19074 case X86::VPCMPISTRM128MEM:
19075 case X86::PCMPESTRM128REG:
19076 case X86::VPCMPESTRM128REG:
19077 case X86::PCMPESTRM128MEM:
19078 case X86::VPCMPESTRM128MEM:
19079 assert(Subtarget->hasSSE42() &&
19080 "Target must have SSE4.2 or AVX features enabled");
19081 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19083 // String/text processing lowering.
19084 case X86::PCMPISTRIREG:
19085 case X86::VPCMPISTRIREG:
19086 case X86::PCMPISTRIMEM:
19087 case X86::VPCMPISTRIMEM:
19088 case X86::PCMPESTRIREG:
19089 case X86::VPCMPESTRIREG:
19090 case X86::PCMPESTRIMEM:
19091 case X86::VPCMPESTRIMEM:
19092 assert(Subtarget->hasSSE42() &&
19093 "Target must have SSE4.2 or AVX features enabled");
19094 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19096 // Thread synchronization.
19098 return EmitMonitor(MI, BB, Subtarget);
19102 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19104 case X86::VASTART_SAVE_XMM_REGS:
19105 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19107 case X86::VAARG_64:
19108 return EmitVAARG64WithCustomInserter(MI, BB);
19110 case X86::EH_SjLj_SetJmp32:
19111 case X86::EH_SjLj_SetJmp64:
19112 return emitEHSjLjSetJmp(MI, BB);
19114 case X86::EH_SjLj_LongJmp32:
19115 case X86::EH_SjLj_LongJmp64:
19116 return emitEHSjLjLongJmp(MI, BB);
19118 case TargetOpcode::STATEPOINT:
19119 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19120 // this point in the process. We diverge later.
19121 return emitPatchPoint(MI, BB);
19123 case TargetOpcode::STACKMAP:
19124 case TargetOpcode::PATCHPOINT:
19125 return emitPatchPoint(MI, BB);
19127 case X86::VFMADDPDr213r:
19128 case X86::VFMADDPSr213r:
19129 case X86::VFMADDSDr213r:
19130 case X86::VFMADDSSr213r:
19131 case X86::VFMSUBPDr213r:
19132 case X86::VFMSUBPSr213r:
19133 case X86::VFMSUBSDr213r:
19134 case X86::VFMSUBSSr213r:
19135 case X86::VFNMADDPDr213r:
19136 case X86::VFNMADDPSr213r:
19137 case X86::VFNMADDSDr213r:
19138 case X86::VFNMADDSSr213r:
19139 case X86::VFNMSUBPDr213r:
19140 case X86::VFNMSUBPSr213r:
19141 case X86::VFNMSUBSDr213r:
19142 case X86::VFNMSUBSSr213r:
19143 case X86::VFMADDSUBPDr213r:
19144 case X86::VFMADDSUBPSr213r:
19145 case X86::VFMSUBADDPDr213r:
19146 case X86::VFMSUBADDPSr213r:
19147 case X86::VFMADDPDr213rY:
19148 case X86::VFMADDPSr213rY:
19149 case X86::VFMSUBPDr213rY:
19150 case X86::VFMSUBPSr213rY:
19151 case X86::VFNMADDPDr213rY:
19152 case X86::VFNMADDPSr213rY:
19153 case X86::VFNMSUBPDr213rY:
19154 case X86::VFNMSUBPSr213rY:
19155 case X86::VFMADDSUBPDr213rY:
19156 case X86::VFMADDSUBPSr213rY:
19157 case X86::VFMSUBADDPDr213rY:
19158 case X86::VFMSUBADDPSr213rY:
19159 return emitFMA3Instr(MI, BB);
19163 //===----------------------------------------------------------------------===//
19164 // X86 Optimization Hooks
19165 //===----------------------------------------------------------------------===//
19167 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19170 const SelectionDAG &DAG,
19171 unsigned Depth) const {
19172 unsigned BitWidth = KnownZero.getBitWidth();
19173 unsigned Opc = Op.getOpcode();
19174 assert((Opc >= ISD::BUILTIN_OP_END ||
19175 Opc == ISD::INTRINSIC_WO_CHAIN ||
19176 Opc == ISD::INTRINSIC_W_CHAIN ||
19177 Opc == ISD::INTRINSIC_VOID) &&
19178 "Should use MaskedValueIsZero if you don't know whether Op"
19179 " is a target node!");
19181 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19195 // These nodes' second result is a boolean.
19196 if (Op.getResNo() == 0)
19199 case X86ISD::SETCC:
19200 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19202 case ISD::INTRINSIC_WO_CHAIN: {
19203 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19204 unsigned NumLoBits = 0;
19207 case Intrinsic::x86_sse_movmsk_ps:
19208 case Intrinsic::x86_avx_movmsk_ps_256:
19209 case Intrinsic::x86_sse2_movmsk_pd:
19210 case Intrinsic::x86_avx_movmsk_pd_256:
19211 case Intrinsic::x86_mmx_pmovmskb:
19212 case Intrinsic::x86_sse2_pmovmskb_128:
19213 case Intrinsic::x86_avx2_pmovmskb: {
19214 // High bits of movmskp{s|d}, pmovmskb are known zero.
19216 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19217 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19218 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19219 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19220 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19221 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19222 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19223 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19225 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19234 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19236 const SelectionDAG &,
19237 unsigned Depth) const {
19238 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19239 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19240 return Op.getValueType().getScalarType().getSizeInBits();
19246 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19247 /// node is a GlobalAddress + offset.
19248 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19249 const GlobalValue* &GA,
19250 int64_t &Offset) const {
19251 if (N->getOpcode() == X86ISD::Wrapper) {
19252 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19253 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19254 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19258 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19261 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19262 /// same as extracting the high 128-bit part of 256-bit vector and then
19263 /// inserting the result into the low part of a new 256-bit vector
19264 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19265 EVT VT = SVOp->getValueType(0);
19266 unsigned NumElems = VT.getVectorNumElements();
19268 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19269 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19270 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19271 SVOp->getMaskElt(j) >= 0)
19277 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19278 /// same as extracting the low 128-bit part of 256-bit vector and then
19279 /// inserting the result into the high part of a new 256-bit vector
19280 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19281 EVT VT = SVOp->getValueType(0);
19282 unsigned NumElems = VT.getVectorNumElements();
19284 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19285 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19286 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19287 SVOp->getMaskElt(j) >= 0)
19293 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19294 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19295 TargetLowering::DAGCombinerInfo &DCI,
19296 const X86Subtarget* Subtarget) {
19298 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19299 SDValue V1 = SVOp->getOperand(0);
19300 SDValue V2 = SVOp->getOperand(1);
19301 EVT VT = SVOp->getValueType(0);
19302 unsigned NumElems = VT.getVectorNumElements();
19304 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19305 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19309 // V UNDEF BUILD_VECTOR UNDEF
19311 // CONCAT_VECTOR CONCAT_VECTOR
19314 // RESULT: V + zero extended
19316 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19317 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19318 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19321 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19324 // To match the shuffle mask, the first half of the mask should
19325 // be exactly the first vector, and all the rest a splat with the
19326 // first element of the second one.
19327 for (unsigned i = 0; i != NumElems/2; ++i)
19328 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19329 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19332 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19333 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19334 if (Ld->hasNUsesOfValue(1, 0)) {
19335 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19336 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19338 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19340 Ld->getPointerInfo(),
19341 Ld->getAlignment(),
19342 false/*isVolatile*/, true/*ReadMem*/,
19343 false/*WriteMem*/);
19345 // Make sure the newly-created LOAD is in the same position as Ld in
19346 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19347 // and update uses of Ld's output chain to use the TokenFactor.
19348 if (Ld->hasAnyUseOfValue(1)) {
19349 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19350 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19351 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19352 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19353 SDValue(ResNode.getNode(), 1));
19356 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19360 // Emit a zeroed vector and insert the desired subvector on its
19362 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19363 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19364 return DCI.CombineTo(N, InsV);
19367 //===--------------------------------------------------------------------===//
19368 // Combine some shuffles into subvector extracts and inserts:
19371 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19372 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19373 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19374 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19375 return DCI.CombineTo(N, InsV);
19378 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19379 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19380 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19381 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19382 return DCI.CombineTo(N, InsV);
19388 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19391 /// This is the leaf of the recursive combinine below. When we have found some
19392 /// chain of single-use x86 shuffle instructions and accumulated the combined
19393 /// shuffle mask represented by them, this will try to pattern match that mask
19394 /// into either a single instruction if there is a special purpose instruction
19395 /// for this operation, or into a PSHUFB instruction which is a fully general
19396 /// instruction but should only be used to replace chains over a certain depth.
19397 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19398 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19399 TargetLowering::DAGCombinerInfo &DCI,
19400 const X86Subtarget *Subtarget) {
19401 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19403 // Find the operand that enters the chain. Note that multiple uses are OK
19404 // here, we're not going to remove the operand we find.
19405 SDValue Input = Op.getOperand(0);
19406 while (Input.getOpcode() == ISD::BITCAST)
19407 Input = Input.getOperand(0);
19409 MVT VT = Input.getSimpleValueType();
19410 MVT RootVT = Root.getSimpleValueType();
19413 // Just remove no-op shuffle masks.
19414 if (Mask.size() == 1) {
19415 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19420 // Use the float domain if the operand type is a floating point type.
19421 bool FloatDomain = VT.isFloatingPoint();
19423 // For floating point shuffles, we don't have free copies in the shuffle
19424 // instructions or the ability to load as part of the instruction, so
19425 // canonicalize their shuffles to UNPCK or MOV variants.
19427 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19428 // vectors because it can have a load folded into it that UNPCK cannot. This
19429 // doesn't preclude something switching to the shorter encoding post-RA.
19431 // FIXME: Should teach these routines about AVX vector widths.
19432 if (FloatDomain && VT.getSizeInBits() == 128) {
19433 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19434 bool Lo = Mask.equals({0, 0});
19437 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19438 // is no slower than UNPCKLPD but has the option to fold the input operand
19439 // into even an unaligned memory load.
19440 if (Lo && Subtarget->hasSSE3()) {
19441 Shuffle = X86ISD::MOVDDUP;
19442 ShuffleVT = MVT::v2f64;
19444 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19445 // than the UNPCK variants.
19446 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19447 ShuffleVT = MVT::v4f32;
19449 if (Depth == 1 && Root->getOpcode() == Shuffle)
19450 return false; // Nothing to do!
19451 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19452 DCI.AddToWorklist(Op.getNode());
19453 if (Shuffle == X86ISD::MOVDDUP)
19454 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19456 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19457 DCI.AddToWorklist(Op.getNode());
19458 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19462 if (Subtarget->hasSSE3() &&
19463 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19464 bool Lo = Mask.equals({0, 0, 2, 2});
19465 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19466 MVT ShuffleVT = MVT::v4f32;
19467 if (Depth == 1 && Root->getOpcode() == Shuffle)
19468 return false; // Nothing to do!
19469 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19470 DCI.AddToWorklist(Op.getNode());
19471 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19472 DCI.AddToWorklist(Op.getNode());
19473 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19477 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19478 bool Lo = Mask.equals({0, 0, 1, 1});
19479 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19480 MVT ShuffleVT = MVT::v4f32;
19481 if (Depth == 1 && Root->getOpcode() == Shuffle)
19482 return false; // Nothing to do!
19483 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19484 DCI.AddToWorklist(Op.getNode());
19485 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19486 DCI.AddToWorklist(Op.getNode());
19487 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19493 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19494 // variants as none of these have single-instruction variants that are
19495 // superior to the UNPCK formulation.
19496 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19497 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19498 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19499 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19501 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19502 bool Lo = Mask[0] == 0;
19503 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19504 if (Depth == 1 && Root->getOpcode() == Shuffle)
19505 return false; // Nothing to do!
19507 switch (Mask.size()) {
19509 ShuffleVT = MVT::v8i16;
19512 ShuffleVT = MVT::v16i8;
19515 llvm_unreachable("Impossible mask size!");
19517 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19518 DCI.AddToWorklist(Op.getNode());
19519 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19520 DCI.AddToWorklist(Op.getNode());
19521 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19526 // Don't try to re-form single instruction chains under any circumstances now
19527 // that we've done encoding canonicalization for them.
19531 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19532 // can replace them with a single PSHUFB instruction profitably. Intel's
19533 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19534 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19535 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19536 SmallVector<SDValue, 16> PSHUFBMask;
19537 int NumBytes = VT.getSizeInBits() / 8;
19538 int Ratio = NumBytes / Mask.size();
19539 for (int i = 0; i < NumBytes; ++i) {
19540 if (Mask[i / Ratio] == SM_SentinelUndef) {
19541 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19544 int M = Mask[i / Ratio] != SM_SentinelZero
19545 ? Ratio * Mask[i / Ratio] + i % Ratio
19547 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19549 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19550 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19551 DCI.AddToWorklist(Op.getNode());
19552 SDValue PSHUFBMaskOp =
19553 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19554 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19555 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19556 DCI.AddToWorklist(Op.getNode());
19557 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19562 // Failed to find any combines.
19566 /// \brief Fully generic combining of x86 shuffle instructions.
19568 /// This should be the last combine run over the x86 shuffle instructions. Once
19569 /// they have been fully optimized, this will recursively consider all chains
19570 /// of single-use shuffle instructions, build a generic model of the cumulative
19571 /// shuffle operation, and check for simpler instructions which implement this
19572 /// operation. We use this primarily for two purposes:
19574 /// 1) Collapse generic shuffles to specialized single instructions when
19575 /// equivalent. In most cases, this is just an encoding size win, but
19576 /// sometimes we will collapse multiple generic shuffles into a single
19577 /// special-purpose shuffle.
19578 /// 2) Look for sequences of shuffle instructions with 3 or more total
19579 /// instructions, and replace them with the slightly more expensive SSSE3
19580 /// PSHUFB instruction if available. We do this as the last combining step
19581 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19582 /// a suitable short sequence of other instructions. The PHUFB will either
19583 /// use a register or have to read from memory and so is slightly (but only
19584 /// slightly) more expensive than the other shuffle instructions.
19586 /// Because this is inherently a quadratic operation (for each shuffle in
19587 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19588 /// This should never be an issue in practice as the shuffle lowering doesn't
19589 /// produce sequences of more than 8 instructions.
19591 /// FIXME: We will currently miss some cases where the redundant shuffling
19592 /// would simplify under the threshold for PSHUFB formation because of
19593 /// combine-ordering. To fix this, we should do the redundant instruction
19594 /// combining in this recursive walk.
19595 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19596 ArrayRef<int> RootMask,
19597 int Depth, bool HasPSHUFB,
19599 TargetLowering::DAGCombinerInfo &DCI,
19600 const X86Subtarget *Subtarget) {
19601 // Bound the depth of our recursive combine because this is ultimately
19602 // quadratic in nature.
19606 // Directly rip through bitcasts to find the underlying operand.
19607 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19608 Op = Op.getOperand(0);
19610 MVT VT = Op.getSimpleValueType();
19611 if (!VT.isVector())
19612 return false; // Bail if we hit a non-vector.
19614 assert(Root.getSimpleValueType().isVector() &&
19615 "Shuffles operate on vector types!");
19616 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19617 "Can only combine shuffles of the same vector register size.");
19619 if (!isTargetShuffle(Op.getOpcode()))
19621 SmallVector<int, 16> OpMask;
19623 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19624 // We only can combine unary shuffles which we can decode the mask for.
19625 if (!HaveMask || !IsUnary)
19628 assert(VT.getVectorNumElements() == OpMask.size() &&
19629 "Different mask size from vector size!");
19630 assert(((RootMask.size() > OpMask.size() &&
19631 RootMask.size() % OpMask.size() == 0) ||
19632 (OpMask.size() > RootMask.size() &&
19633 OpMask.size() % RootMask.size() == 0) ||
19634 OpMask.size() == RootMask.size()) &&
19635 "The smaller number of elements must divide the larger.");
19636 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19637 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19638 assert(((RootRatio == 1 && OpRatio == 1) ||
19639 (RootRatio == 1) != (OpRatio == 1)) &&
19640 "Must not have a ratio for both incoming and op masks!");
19642 SmallVector<int, 16> Mask;
19643 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19645 // Merge this shuffle operation's mask into our accumulated mask. Note that
19646 // this shuffle's mask will be the first applied to the input, followed by the
19647 // root mask to get us all the way to the root value arrangement. The reason
19648 // for this order is that we are recursing up the operation chain.
19649 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19650 int RootIdx = i / RootRatio;
19651 if (RootMask[RootIdx] < 0) {
19652 // This is a zero or undef lane, we're done.
19653 Mask.push_back(RootMask[RootIdx]);
19657 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19658 int OpIdx = RootMaskedIdx / OpRatio;
19659 if (OpMask[OpIdx] < 0) {
19660 // The incoming lanes are zero or undef, it doesn't matter which ones we
19662 Mask.push_back(OpMask[OpIdx]);
19666 // Ok, we have non-zero lanes, map them through.
19667 Mask.push_back(OpMask[OpIdx] * OpRatio +
19668 RootMaskedIdx % OpRatio);
19671 // See if we can recurse into the operand to combine more things.
19672 switch (Op.getOpcode()) {
19673 case X86ISD::PSHUFB:
19675 case X86ISD::PSHUFD:
19676 case X86ISD::PSHUFHW:
19677 case X86ISD::PSHUFLW:
19678 if (Op.getOperand(0).hasOneUse() &&
19679 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19680 HasPSHUFB, DAG, DCI, Subtarget))
19684 case X86ISD::UNPCKL:
19685 case X86ISD::UNPCKH:
19686 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19687 // We can't check for single use, we have to check that this shuffle is the only user.
19688 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19689 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19690 HasPSHUFB, DAG, DCI, Subtarget))
19695 // Minor canonicalization of the accumulated shuffle mask to make it easier
19696 // to match below. All this does is detect masks with squential pairs of
19697 // elements, and shrink them to the half-width mask. It does this in a loop
19698 // so it will reduce the size of the mask to the minimal width mask which
19699 // performs an equivalent shuffle.
19700 SmallVector<int, 16> WidenedMask;
19701 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19702 Mask = std::move(WidenedMask);
19703 WidenedMask.clear();
19706 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19710 /// \brief Get the PSHUF-style mask from PSHUF node.
19712 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19713 /// PSHUF-style masks that can be reused with such instructions.
19714 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19715 MVT VT = N.getSimpleValueType();
19716 SmallVector<int, 4> Mask;
19718 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19722 // If we have more than 128-bits, only the low 128-bits of shuffle mask
19723 // matter. Check that the upper masks are repeats and remove them.
19724 if (VT.getSizeInBits() > 128) {
19725 int LaneElts = 128 / VT.getScalarSizeInBits();
19727 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19728 for (int j = 0; j < LaneElts; ++j)
19729 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19730 "Mask doesn't repeat in high 128-bit lanes!");
19732 Mask.resize(LaneElts);
19735 switch (N.getOpcode()) {
19736 case X86ISD::PSHUFD:
19738 case X86ISD::PSHUFLW:
19741 case X86ISD::PSHUFHW:
19742 Mask.erase(Mask.begin(), Mask.begin() + 4);
19743 for (int &M : Mask)
19747 llvm_unreachable("No valid shuffle instruction found!");
19751 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19753 /// We walk up the chain and look for a combinable shuffle, skipping over
19754 /// shuffles that we could hoist this shuffle's transformation past without
19755 /// altering anything.
19757 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19759 TargetLowering::DAGCombinerInfo &DCI) {
19760 assert(N.getOpcode() == X86ISD::PSHUFD &&
19761 "Called with something other than an x86 128-bit half shuffle!");
19764 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19765 // of the shuffles in the chain so that we can form a fresh chain to replace
19767 SmallVector<SDValue, 8> Chain;
19768 SDValue V = N.getOperand(0);
19769 for (; V.hasOneUse(); V = V.getOperand(0)) {
19770 switch (V.getOpcode()) {
19772 return SDValue(); // Nothing combined!
19775 // Skip bitcasts as we always know the type for the target specific
19779 case X86ISD::PSHUFD:
19780 // Found another dword shuffle.
19783 case X86ISD::PSHUFLW:
19784 // Check that the low words (being shuffled) are the identity in the
19785 // dword shuffle, and the high words are self-contained.
19786 if (Mask[0] != 0 || Mask[1] != 1 ||
19787 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19790 Chain.push_back(V);
19793 case X86ISD::PSHUFHW:
19794 // Check that the high words (being shuffled) are the identity in the
19795 // dword shuffle, and the low words are self-contained.
19796 if (Mask[2] != 2 || Mask[3] != 3 ||
19797 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19800 Chain.push_back(V);
19803 case X86ISD::UNPCKL:
19804 case X86ISD::UNPCKH:
19805 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19806 // shuffle into a preceding word shuffle.
19807 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19808 V.getSimpleValueType().getScalarType() != MVT::i16)
19811 // Search for a half-shuffle which we can combine with.
19812 unsigned CombineOp =
19813 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19814 if (V.getOperand(0) != V.getOperand(1) ||
19815 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19817 Chain.push_back(V);
19818 V = V.getOperand(0);
19820 switch (V.getOpcode()) {
19822 return SDValue(); // Nothing to combine.
19824 case X86ISD::PSHUFLW:
19825 case X86ISD::PSHUFHW:
19826 if (V.getOpcode() == CombineOp)
19829 Chain.push_back(V);
19833 V = V.getOperand(0);
19837 } while (V.hasOneUse());
19840 // Break out of the loop if we break out of the switch.
19844 if (!V.hasOneUse())
19845 // We fell out of the loop without finding a viable combining instruction.
19848 // Merge this node's mask and our incoming mask.
19849 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19850 for (int &M : Mask)
19852 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19853 getV4X86ShuffleImm8ForMask(Mask, DAG));
19855 // Rebuild the chain around this new shuffle.
19856 while (!Chain.empty()) {
19857 SDValue W = Chain.pop_back_val();
19859 if (V.getValueType() != W.getOperand(0).getValueType())
19860 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19862 switch (W.getOpcode()) {
19864 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19866 case X86ISD::UNPCKL:
19867 case X86ISD::UNPCKH:
19868 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19871 case X86ISD::PSHUFD:
19872 case X86ISD::PSHUFLW:
19873 case X86ISD::PSHUFHW:
19874 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19878 if (V.getValueType() != N.getValueType())
19879 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19881 // Return the new chain to replace N.
19885 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19887 /// We walk up the chain, skipping shuffles of the other half and looking
19888 /// through shuffles which switch halves trying to find a shuffle of the same
19889 /// pair of dwords.
19890 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19892 TargetLowering::DAGCombinerInfo &DCI) {
19894 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19895 "Called with something other than an x86 128-bit half shuffle!");
19897 unsigned CombineOpcode = N.getOpcode();
19899 // Walk up a single-use chain looking for a combinable shuffle.
19900 SDValue V = N.getOperand(0);
19901 for (; V.hasOneUse(); V = V.getOperand(0)) {
19902 switch (V.getOpcode()) {
19904 return false; // Nothing combined!
19907 // Skip bitcasts as we always know the type for the target specific
19911 case X86ISD::PSHUFLW:
19912 case X86ISD::PSHUFHW:
19913 if (V.getOpcode() == CombineOpcode)
19916 // Other-half shuffles are no-ops.
19919 // Break out of the loop if we break out of the switch.
19923 if (!V.hasOneUse())
19924 // We fell out of the loop without finding a viable combining instruction.
19927 // Combine away the bottom node as its shuffle will be accumulated into
19928 // a preceding shuffle.
19929 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19931 // Record the old value.
19934 // Merge this node's mask and our incoming mask (adjusted to account for all
19935 // the pshufd instructions encountered).
19936 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19937 for (int &M : Mask)
19939 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19940 getV4X86ShuffleImm8ForMask(Mask, DAG));
19942 // Check that the shuffles didn't cancel each other out. If not, we need to
19943 // combine to the new one.
19945 // Replace the combinable shuffle with the combined one, updating all users
19946 // so that we re-evaluate the chain here.
19947 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19952 /// \brief Try to combine x86 target specific shuffles.
19953 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19954 TargetLowering::DAGCombinerInfo &DCI,
19955 const X86Subtarget *Subtarget) {
19957 MVT VT = N.getSimpleValueType();
19958 SmallVector<int, 4> Mask;
19960 switch (N.getOpcode()) {
19961 case X86ISD::PSHUFD:
19962 case X86ISD::PSHUFLW:
19963 case X86ISD::PSHUFHW:
19964 Mask = getPSHUFShuffleMask(N);
19965 assert(Mask.size() == 4);
19971 // Nuke no-op shuffles that show up after combining.
19972 if (isNoopShuffleMask(Mask))
19973 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19975 // Look for simplifications involving one or two shuffle instructions.
19976 SDValue V = N.getOperand(0);
19977 switch (N.getOpcode()) {
19980 case X86ISD::PSHUFLW:
19981 case X86ISD::PSHUFHW:
19982 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19984 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19985 return SDValue(); // We combined away this shuffle, so we're done.
19987 // See if this reduces to a PSHUFD which is no more expensive and can
19988 // combine with more operations. Note that it has to at least flip the
19989 // dwords as otherwise it would have been removed as a no-op.
19990 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19991 int DMask[] = {0, 1, 2, 3};
19992 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19993 DMask[DOffset + 0] = DOffset + 1;
19994 DMask[DOffset + 1] = DOffset + 0;
19995 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19996 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19997 DCI.AddToWorklist(V.getNode());
19998 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19999 getV4X86ShuffleImm8ForMask(DMask, DAG));
20000 DCI.AddToWorklist(V.getNode());
20001 return DAG.getNode(ISD::BITCAST, DL, VT, V);
20004 // Look for shuffle patterns which can be implemented as a single unpack.
20005 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20006 // only works when we have a PSHUFD followed by two half-shuffles.
20007 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20008 (V.getOpcode() == X86ISD::PSHUFLW ||
20009 V.getOpcode() == X86ISD::PSHUFHW) &&
20010 V.getOpcode() != N.getOpcode() &&
20012 SDValue D = V.getOperand(0);
20013 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20014 D = D.getOperand(0);
20015 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20016 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20017 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20018 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20019 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20021 for (int i = 0; i < 4; ++i) {
20022 WordMask[i + NOffset] = Mask[i] + NOffset;
20023 WordMask[i + VOffset] = VMask[i] + VOffset;
20025 // Map the word mask through the DWord mask.
20027 for (int i = 0; i < 8; ++i)
20028 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20029 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20030 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20031 // We can replace all three shuffles with an unpack.
20032 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20033 DCI.AddToWorklist(V.getNode());
20034 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20043 case X86ISD::PSHUFD:
20044 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20053 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20055 /// We combine this directly on the abstract vector shuffle nodes so it is
20056 /// easier to generically match. We also insert dummy vector shuffle nodes for
20057 /// the operands which explicitly discard the lanes which are unused by this
20058 /// operation to try to flow through the rest of the combiner the fact that
20059 /// they're unused.
20060 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20062 EVT VT = N->getValueType(0);
20064 // We only handle target-independent shuffles.
20065 // FIXME: It would be easy and harmless to use the target shuffle mask
20066 // extraction tool to support more.
20067 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20070 auto *SVN = cast<ShuffleVectorSDNode>(N);
20071 ArrayRef<int> Mask = SVN->getMask();
20072 SDValue V1 = N->getOperand(0);
20073 SDValue V2 = N->getOperand(1);
20075 // We require the first shuffle operand to be the SUB node, and the second to
20076 // be the ADD node.
20077 // FIXME: We should support the commuted patterns.
20078 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20081 // If there are other uses of these operations we can't fold them.
20082 if (!V1->hasOneUse() || !V2->hasOneUse())
20085 // Ensure that both operations have the same operands. Note that we can
20086 // commute the FADD operands.
20087 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20088 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20089 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20092 // We're looking for blends between FADD and FSUB nodes. We insist on these
20093 // nodes being lined up in a specific expected pattern.
20094 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20095 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20096 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20099 // Only specific types are legal at this point, assert so we notice if and
20100 // when these change.
20101 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20102 VT == MVT::v4f64) &&
20103 "Unknown vector type encountered!");
20105 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20108 /// PerformShuffleCombine - Performs several different shuffle combines.
20109 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20110 TargetLowering::DAGCombinerInfo &DCI,
20111 const X86Subtarget *Subtarget) {
20113 SDValue N0 = N->getOperand(0);
20114 SDValue N1 = N->getOperand(1);
20115 EVT VT = N->getValueType(0);
20117 // Don't create instructions with illegal types after legalize types has run.
20118 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20119 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20122 // If we have legalized the vector types, look for blends of FADD and FSUB
20123 // nodes that we can fuse into an ADDSUB node.
20124 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20125 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20128 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20129 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20130 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20131 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20133 // During Type Legalization, when promoting illegal vector types,
20134 // the backend might introduce new shuffle dag nodes and bitcasts.
20136 // This code performs the following transformation:
20137 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20138 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20140 // We do this only if both the bitcast and the BINOP dag nodes have
20141 // one use. Also, perform this transformation only if the new binary
20142 // operation is legal. This is to avoid introducing dag nodes that
20143 // potentially need to be further expanded (or custom lowered) into a
20144 // less optimal sequence of dag nodes.
20145 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20146 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20147 N0.getOpcode() == ISD::BITCAST) {
20148 SDValue BC0 = N0.getOperand(0);
20149 EVT SVT = BC0.getValueType();
20150 unsigned Opcode = BC0.getOpcode();
20151 unsigned NumElts = VT.getVectorNumElements();
20153 if (BC0.hasOneUse() && SVT.isVector() &&
20154 SVT.getVectorNumElements() * 2 == NumElts &&
20155 TLI.isOperationLegal(Opcode, VT)) {
20156 bool CanFold = false;
20168 unsigned SVTNumElts = SVT.getVectorNumElements();
20169 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20170 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20171 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20172 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20173 CanFold = SVOp->getMaskElt(i) < 0;
20176 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20177 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20178 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20179 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20184 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20185 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20186 // consecutive, non-overlapping, and in the right order.
20187 SmallVector<SDValue, 16> Elts;
20188 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20189 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20191 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20195 if (isTargetShuffle(N->getOpcode())) {
20197 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20198 if (Shuffle.getNode())
20201 // Try recursively combining arbitrary sequences of x86 shuffle
20202 // instructions into higher-order shuffles. We do this after combining
20203 // specific PSHUF instruction sequences into their minimal form so that we
20204 // can evaluate how many specialized shuffle instructions are involved in
20205 // a particular chain.
20206 SmallVector<int, 1> NonceMask; // Just a placeholder.
20207 NonceMask.push_back(0);
20208 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20209 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20211 return SDValue(); // This routine will use CombineTo to replace N.
20217 /// PerformTruncateCombine - Converts truncate operation to
20218 /// a sequence of vector shuffle operations.
20219 /// It is possible when we truncate 256-bit vector to 128-bit vector
20220 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20221 TargetLowering::DAGCombinerInfo &DCI,
20222 const X86Subtarget *Subtarget) {
20226 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20227 /// specific shuffle of a load can be folded into a single element load.
20228 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20229 /// shuffles have been custom lowered so we need to handle those here.
20230 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20231 TargetLowering::DAGCombinerInfo &DCI) {
20232 if (DCI.isBeforeLegalizeOps())
20235 SDValue InVec = N->getOperand(0);
20236 SDValue EltNo = N->getOperand(1);
20238 if (!isa<ConstantSDNode>(EltNo))
20241 EVT OriginalVT = InVec.getValueType();
20243 if (InVec.getOpcode() == ISD::BITCAST) {
20244 // Don't duplicate a load with other uses.
20245 if (!InVec.hasOneUse())
20247 EVT BCVT = InVec.getOperand(0).getValueType();
20248 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20250 InVec = InVec.getOperand(0);
20253 EVT CurrentVT = InVec.getValueType();
20255 if (!isTargetShuffle(InVec.getOpcode()))
20258 // Don't duplicate a load with other uses.
20259 if (!InVec.hasOneUse())
20262 SmallVector<int, 16> ShuffleMask;
20264 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20265 ShuffleMask, UnaryShuffle))
20268 // Select the input vector, guarding against out of range extract vector.
20269 unsigned NumElems = CurrentVT.getVectorNumElements();
20270 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20271 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20272 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20273 : InVec.getOperand(1);
20275 // If inputs to shuffle are the same for both ops, then allow 2 uses
20276 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20277 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20279 if (LdNode.getOpcode() == ISD::BITCAST) {
20280 // Don't duplicate a load with other uses.
20281 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20284 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20285 LdNode = LdNode.getOperand(0);
20288 if (!ISD::isNormalLoad(LdNode.getNode()))
20291 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20293 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20296 EVT EltVT = N->getValueType(0);
20297 // If there's a bitcast before the shuffle, check if the load type and
20298 // alignment is valid.
20299 unsigned Align = LN0->getAlignment();
20300 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20301 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20302 EltVT.getTypeForEVT(*DAG.getContext()));
20304 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20307 // All checks match so transform back to vector_shuffle so that DAG combiner
20308 // can finish the job
20311 // Create shuffle node taking into account the case that its a unary shuffle
20312 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20313 : InVec.getOperand(1);
20314 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20315 InVec.getOperand(0), Shuffle,
20317 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20318 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20322 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20323 /// special and don't usually play with other vector types, it's better to
20324 /// handle them early to be sure we emit efficient code by avoiding
20325 /// store-load conversions.
20326 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20327 if (N->getValueType(0) != MVT::x86mmx ||
20328 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20329 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20332 SDValue V = N->getOperand(0);
20333 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20334 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20335 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20336 N->getValueType(0), V.getOperand(0));
20341 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20342 /// generation and convert it from being a bunch of shuffles and extracts
20343 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20344 /// storing the value and loading scalars back, while for x64 we should
20345 /// use 64-bit extracts and shifts.
20346 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20347 TargetLowering::DAGCombinerInfo &DCI) {
20348 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20349 if (NewOp.getNode())
20352 SDValue InputVector = N->getOperand(0);
20354 // Detect mmx to i32 conversion through a v2i32 elt extract.
20355 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20356 N->getValueType(0) == MVT::i32 &&
20357 InputVector.getValueType() == MVT::v2i32) {
20359 // The bitcast source is a direct mmx result.
20360 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20361 if (MMXSrc.getValueType() == MVT::x86mmx)
20362 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20363 N->getValueType(0),
20364 InputVector.getNode()->getOperand(0));
20366 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20367 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20368 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20369 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20370 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20371 MMXSrcOp.getValueType() == MVT::v1i64 &&
20372 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20373 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20374 N->getValueType(0),
20375 MMXSrcOp.getOperand(0));
20378 // Only operate on vectors of 4 elements, where the alternative shuffling
20379 // gets to be more expensive.
20380 if (InputVector.getValueType() != MVT::v4i32)
20383 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20384 // single use which is a sign-extend or zero-extend, and all elements are
20386 SmallVector<SDNode *, 4> Uses;
20387 unsigned ExtractedElements = 0;
20388 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20389 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20390 if (UI.getUse().getResNo() != InputVector.getResNo())
20393 SDNode *Extract = *UI;
20394 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20397 if (Extract->getValueType(0) != MVT::i32)
20399 if (!Extract->hasOneUse())
20401 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20402 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20404 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20407 // Record which element was extracted.
20408 ExtractedElements |=
20409 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20411 Uses.push_back(Extract);
20414 // If not all the elements were used, this may not be worthwhile.
20415 if (ExtractedElements != 15)
20418 // Ok, we've now decided to do the transformation.
20419 // If 64-bit shifts are legal, use the extract-shift sequence,
20420 // otherwise bounce the vector off the cache.
20421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20423 SDLoc dl(InputVector);
20425 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20426 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20427 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20428 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20429 DAG.getConstant(0, VecIdxTy));
20430 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20431 DAG.getConstant(1, VecIdxTy));
20433 SDValue ShAmt = DAG.getConstant(32,
20434 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20435 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20436 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20437 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20438 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20439 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20440 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20442 // Store the value to a temporary stack slot.
20443 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20444 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20445 MachinePointerInfo(), false, false, 0);
20447 EVT ElementType = InputVector.getValueType().getVectorElementType();
20448 unsigned EltSize = ElementType.getSizeInBits() / 8;
20450 // Replace each use (extract) with a load of the appropriate element.
20451 for (unsigned i = 0; i < 4; ++i) {
20452 uint64_t Offset = EltSize * i;
20453 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20455 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20456 StackPtr, OffsetVal);
20458 // Load the scalar.
20459 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20460 ScalarAddr, MachinePointerInfo(),
20461 false, false, false, 0);
20466 // Replace the extracts
20467 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20468 UE = Uses.end(); UI != UE; ++UI) {
20469 SDNode *Extract = *UI;
20471 SDValue Idx = Extract->getOperand(1);
20472 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20473 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20476 // The replacement was made in place; don't return anything.
20480 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20481 static std::pair<unsigned, bool>
20482 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20483 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20484 if (!VT.isVector())
20485 return std::make_pair(0, false);
20487 bool NeedSplit = false;
20488 switch (VT.getSimpleVT().SimpleTy) {
20489 default: return std::make_pair(0, false);
20492 if (!Subtarget->hasVLX())
20493 return std::make_pair(0, false);
20497 if (!Subtarget->hasBWI())
20498 return std::make_pair(0, false);
20502 if (!Subtarget->hasAVX512())
20503 return std::make_pair(0, false);
20508 if (!Subtarget->hasAVX2())
20510 if (!Subtarget->hasAVX())
20511 return std::make_pair(0, false);
20516 if (!Subtarget->hasSSE2())
20517 return std::make_pair(0, false);
20520 // SSE2 has only a small subset of the operations.
20521 bool hasUnsigned = Subtarget->hasSSE41() ||
20522 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20523 bool hasSigned = Subtarget->hasSSE41() ||
20524 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20526 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20529 // Check for x CC y ? x : y.
20530 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20531 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20536 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20539 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20542 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20545 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20547 // Check for x CC y ? y : x -- a min/max with reversed arms.
20548 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20549 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20554 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20557 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20560 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20563 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20567 return std::make_pair(Opc, NeedSplit);
20571 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20572 const X86Subtarget *Subtarget) {
20574 SDValue Cond = N->getOperand(0);
20575 SDValue LHS = N->getOperand(1);
20576 SDValue RHS = N->getOperand(2);
20578 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20579 SDValue CondSrc = Cond->getOperand(0);
20580 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20581 Cond = CondSrc->getOperand(0);
20584 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20587 // A vselect where all conditions and data are constants can be optimized into
20588 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20589 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20590 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20593 unsigned MaskValue = 0;
20594 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20597 MVT VT = N->getSimpleValueType(0);
20598 unsigned NumElems = VT.getVectorNumElements();
20599 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20600 for (unsigned i = 0; i < NumElems; ++i) {
20601 // Be sure we emit undef where we can.
20602 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20603 ShuffleMask[i] = -1;
20605 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20608 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20609 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20611 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20614 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20616 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20617 TargetLowering::DAGCombinerInfo &DCI,
20618 const X86Subtarget *Subtarget) {
20620 SDValue Cond = N->getOperand(0);
20621 // Get the LHS/RHS of the select.
20622 SDValue LHS = N->getOperand(1);
20623 SDValue RHS = N->getOperand(2);
20624 EVT VT = LHS.getValueType();
20625 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20627 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20628 // instructions match the semantics of the common C idiom x<y?x:y but not
20629 // x<=y?x:y, because of how they handle negative zero (which can be
20630 // ignored in unsafe-math mode).
20631 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20632 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20633 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20634 (Subtarget->hasSSE2() ||
20635 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20636 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20638 unsigned Opcode = 0;
20639 // Check for x CC y ? x : y.
20640 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20641 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20645 // Converting this to a min would handle NaNs incorrectly, and swapping
20646 // the operands would cause it to handle comparisons between positive
20647 // and negative zero incorrectly.
20648 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20649 if (!DAG.getTarget().Options.UnsafeFPMath &&
20650 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20652 std::swap(LHS, RHS);
20654 Opcode = X86ISD::FMIN;
20657 // Converting this to a min would handle comparisons between positive
20658 // and negative zero incorrectly.
20659 if (!DAG.getTarget().Options.UnsafeFPMath &&
20660 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20662 Opcode = X86ISD::FMIN;
20665 // Converting this to a min would handle both negative zeros and NaNs
20666 // incorrectly, but we can swap the operands to fix both.
20667 std::swap(LHS, RHS);
20671 Opcode = X86ISD::FMIN;
20675 // Converting this to a max would handle comparisons between positive
20676 // and negative zero incorrectly.
20677 if (!DAG.getTarget().Options.UnsafeFPMath &&
20678 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20680 Opcode = X86ISD::FMAX;
20683 // Converting this to a max would handle NaNs incorrectly, and swapping
20684 // the operands would cause it to handle comparisons between positive
20685 // and negative zero incorrectly.
20686 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20687 if (!DAG.getTarget().Options.UnsafeFPMath &&
20688 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20690 std::swap(LHS, RHS);
20692 Opcode = X86ISD::FMAX;
20695 // Converting this to a max would handle both negative zeros and NaNs
20696 // incorrectly, but we can swap the operands to fix both.
20697 std::swap(LHS, RHS);
20701 Opcode = X86ISD::FMAX;
20704 // Check for x CC y ? y : x -- a min/max with reversed arms.
20705 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20706 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20710 // Converting this to a min would handle comparisons between positive
20711 // and negative zero incorrectly, and swapping the operands would
20712 // cause it to handle NaNs incorrectly.
20713 if (!DAG.getTarget().Options.UnsafeFPMath &&
20714 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20715 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20717 std::swap(LHS, RHS);
20719 Opcode = X86ISD::FMIN;
20722 // Converting this to a min would handle NaNs incorrectly.
20723 if (!DAG.getTarget().Options.UnsafeFPMath &&
20724 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20726 Opcode = X86ISD::FMIN;
20729 // Converting this to a min would handle both negative zeros and NaNs
20730 // incorrectly, but we can swap the operands to fix both.
20731 std::swap(LHS, RHS);
20735 Opcode = X86ISD::FMIN;
20739 // Converting this to a max would handle NaNs incorrectly.
20740 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20742 Opcode = X86ISD::FMAX;
20745 // Converting this to a max would handle comparisons between positive
20746 // and negative zero incorrectly, and swapping the operands would
20747 // cause it to handle NaNs incorrectly.
20748 if (!DAG.getTarget().Options.UnsafeFPMath &&
20749 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20750 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20752 std::swap(LHS, RHS);
20754 Opcode = X86ISD::FMAX;
20757 // Converting this to a max would handle both negative zeros and NaNs
20758 // incorrectly, but we can swap the operands to fix both.
20759 std::swap(LHS, RHS);
20763 Opcode = X86ISD::FMAX;
20769 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20772 EVT CondVT = Cond.getValueType();
20773 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20774 CondVT.getVectorElementType() == MVT::i1) {
20775 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20776 // lowering on KNL. In this case we convert it to
20777 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20778 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20779 // Since SKX these selects have a proper lowering.
20780 EVT OpVT = LHS.getValueType();
20781 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20782 (OpVT.getVectorElementType() == MVT::i8 ||
20783 OpVT.getVectorElementType() == MVT::i16) &&
20784 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20785 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20786 DCI.AddToWorklist(Cond.getNode());
20787 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20790 // If this is a select between two integer constants, try to do some
20792 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20793 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20794 // Don't do this for crazy integer types.
20795 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20796 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20797 // so that TrueC (the true value) is larger than FalseC.
20798 bool NeedsCondInvert = false;
20800 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20801 // Efficiently invertible.
20802 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20803 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20804 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20805 NeedsCondInvert = true;
20806 std::swap(TrueC, FalseC);
20809 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20810 if (FalseC->getAPIntValue() == 0 &&
20811 TrueC->getAPIntValue().isPowerOf2()) {
20812 if (NeedsCondInvert) // Invert the condition if needed.
20813 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20814 DAG.getConstant(1, Cond.getValueType()));
20816 // Zero extend the condition if needed.
20817 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20819 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20820 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20821 DAG.getConstant(ShAmt, MVT::i8));
20824 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20825 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20826 if (NeedsCondInvert) // Invert the condition if needed.
20827 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20828 DAG.getConstant(1, Cond.getValueType()));
20830 // Zero extend the condition if needed.
20831 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20832 FalseC->getValueType(0), Cond);
20833 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20834 SDValue(FalseC, 0));
20837 // Optimize cases that will turn into an LEA instruction. This requires
20838 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20839 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20840 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20841 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20843 bool isFastMultiplier = false;
20845 switch ((unsigned char)Diff) {
20847 case 1: // result = add base, cond
20848 case 2: // result = lea base( , cond*2)
20849 case 3: // result = lea base(cond, cond*2)
20850 case 4: // result = lea base( , cond*4)
20851 case 5: // result = lea base(cond, cond*4)
20852 case 8: // result = lea base( , cond*8)
20853 case 9: // result = lea base(cond, cond*8)
20854 isFastMultiplier = true;
20859 if (isFastMultiplier) {
20860 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20861 if (NeedsCondInvert) // Invert the condition if needed.
20862 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20863 DAG.getConstant(1, Cond.getValueType()));
20865 // Zero extend the condition if needed.
20866 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20868 // Scale the condition by the difference.
20870 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20871 DAG.getConstant(Diff, Cond.getValueType()));
20873 // Add the base if non-zero.
20874 if (FalseC->getAPIntValue() != 0)
20875 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20876 SDValue(FalseC, 0));
20883 // Canonicalize max and min:
20884 // (x > y) ? x : y -> (x >= y) ? x : y
20885 // (x < y) ? x : y -> (x <= y) ? x : y
20886 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20887 // the need for an extra compare
20888 // against zero. e.g.
20889 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20891 // testl %edi, %edi
20893 // cmovgl %edi, %eax
20897 // cmovsl %eax, %edi
20898 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20899 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20900 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20901 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20906 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20907 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20908 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20909 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20914 // Early exit check
20915 if (!TLI.isTypeLegal(VT))
20918 // Match VSELECTs into subs with unsigned saturation.
20919 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20920 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20921 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20922 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20923 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20925 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20926 // left side invert the predicate to simplify logic below.
20928 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20930 CC = ISD::getSetCCInverse(CC, true);
20931 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20935 if (Other.getNode() && Other->getNumOperands() == 2 &&
20936 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20937 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20938 SDValue CondRHS = Cond->getOperand(1);
20940 // Look for a general sub with unsigned saturation first.
20941 // x >= y ? x-y : 0 --> subus x, y
20942 // x > y ? x-y : 0 --> subus x, y
20943 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20944 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20945 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20947 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20948 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20949 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20950 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20951 // If the RHS is a constant we have to reverse the const
20952 // canonicalization.
20953 // x > C-1 ? x+-C : 0 --> subus x, C
20954 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20955 CondRHSConst->getAPIntValue() ==
20956 (-OpRHSConst->getAPIntValue() - 1))
20957 return DAG.getNode(
20958 X86ISD::SUBUS, DL, VT, OpLHS,
20959 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20961 // Another special case: If C was a sign bit, the sub has been
20962 // canonicalized into a xor.
20963 // FIXME: Would it be better to use computeKnownBits to determine
20964 // whether it's safe to decanonicalize the xor?
20965 // x s< 0 ? x^C : 0 --> subus x, C
20966 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20967 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20968 OpRHSConst->getAPIntValue().isSignBit())
20969 // Note that we have to rebuild the RHS constant here to ensure we
20970 // don't rely on particular values of undef lanes.
20971 return DAG.getNode(
20972 X86ISD::SUBUS, DL, VT, OpLHS,
20973 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20978 // Try to match a min/max vector operation.
20979 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20980 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20981 unsigned Opc = ret.first;
20982 bool NeedSplit = ret.second;
20984 if (Opc && NeedSplit) {
20985 unsigned NumElems = VT.getVectorNumElements();
20986 // Extract the LHS vectors
20987 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20988 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20990 // Extract the RHS vectors
20991 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20992 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20994 // Create min/max for each subvector
20995 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20996 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20998 // Merge the result
20999 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21001 return DAG.getNode(Opc, DL, VT, LHS, RHS);
21004 // Simplify vector selection if condition value type matches vselect
21006 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21007 assert(Cond.getValueType().isVector() &&
21008 "vector select expects a vector selector!");
21010 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21011 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21013 // Try invert the condition if true value is not all 1s and false value
21015 if (!TValIsAllOnes && !FValIsAllZeros &&
21016 // Check if the selector will be produced by CMPP*/PCMP*
21017 Cond.getOpcode() == ISD::SETCC &&
21018 // Check if SETCC has already been promoted
21019 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21020 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21021 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21023 if (TValIsAllZeros || FValIsAllOnes) {
21024 SDValue CC = Cond.getOperand(2);
21025 ISD::CondCode NewCC =
21026 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21027 Cond.getOperand(0).getValueType().isInteger());
21028 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21029 std::swap(LHS, RHS);
21030 TValIsAllOnes = FValIsAllOnes;
21031 FValIsAllZeros = TValIsAllZeros;
21035 if (TValIsAllOnes || FValIsAllZeros) {
21038 if (TValIsAllOnes && FValIsAllZeros)
21040 else if (TValIsAllOnes)
21041 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21042 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21043 else if (FValIsAllZeros)
21044 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21045 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21047 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21051 // We should generate an X86ISD::BLENDI from a vselect if its argument
21052 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21053 // constants. This specific pattern gets generated when we split a
21054 // selector for a 512 bit vector in a machine without AVX512 (but with
21055 // 256-bit vectors), during legalization:
21057 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21059 // Iff we find this pattern and the build_vectors are built from
21060 // constants, we translate the vselect into a shuffle_vector that we
21061 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21062 if ((N->getOpcode() == ISD::VSELECT ||
21063 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21064 !DCI.isBeforeLegalize()) {
21065 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21066 if (Shuffle.getNode())
21070 // If this is a *dynamic* select (non-constant condition) and we can match
21071 // this node with one of the variable blend instructions, restructure the
21072 // condition so that the blends can use the high bit of each element and use
21073 // SimplifyDemandedBits to simplify the condition operand.
21074 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21075 !DCI.isBeforeLegalize() &&
21076 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21077 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21079 // Don't optimize vector selects that map to mask-registers.
21083 // We can only handle the cases where VSELECT is directly legal on the
21084 // subtarget. We custom lower VSELECT nodes with constant conditions and
21085 // this makes it hard to see whether a dynamic VSELECT will correctly
21086 // lower, so we both check the operation's status and explicitly handle the
21087 // cases where a *dynamic* blend will fail even though a constant-condition
21088 // blend could be custom lowered.
21089 // FIXME: We should find a better way to handle this class of problems.
21090 // Potentially, we should combine constant-condition vselect nodes
21091 // pre-legalization into shuffles and not mark as many types as custom
21093 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21095 // FIXME: We don't support i16-element blends currently. We could and
21096 // should support them by making *all* the bits in the condition be set
21097 // rather than just the high bit and using an i8-element blend.
21098 if (VT.getScalarType() == MVT::i16)
21100 // Dynamic blending was only available from SSE4.1 onward.
21101 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21103 // Byte blends are only available in AVX2
21104 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21105 !Subtarget->hasAVX2())
21108 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21109 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21111 APInt KnownZero, KnownOne;
21112 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21113 DCI.isBeforeLegalizeOps());
21114 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21115 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21117 // If we changed the computation somewhere in the DAG, this change
21118 // will affect all users of Cond.
21119 // Make sure it is fine and update all the nodes so that we do not
21120 // use the generic VSELECT anymore. Otherwise, we may perform
21121 // wrong optimizations as we messed up with the actual expectation
21122 // for the vector boolean values.
21123 if (Cond != TLO.Old) {
21124 // Check all uses of that condition operand to check whether it will be
21125 // consumed by non-BLEND instructions, which may depend on all bits are
21127 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21129 if (I->getOpcode() != ISD::VSELECT)
21130 // TODO: Add other opcodes eventually lowered into BLEND.
21133 // Update all the users of the condition, before committing the change,
21134 // so that the VSELECT optimizations that expect the correct vector
21135 // boolean value will not be triggered.
21136 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21138 DAG.ReplaceAllUsesOfValueWith(
21140 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21141 Cond, I->getOperand(1), I->getOperand(2)));
21142 DCI.CommitTargetLoweringOpt(TLO);
21145 // At this point, only Cond is changed. Change the condition
21146 // just for N to keep the opportunity to optimize all other
21147 // users their own way.
21148 DAG.ReplaceAllUsesOfValueWith(
21150 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21151 TLO.New, N->getOperand(1), N->getOperand(2)));
21159 // Check whether a boolean test is testing a boolean value generated by
21160 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21163 // Simplify the following patterns:
21164 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21165 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21166 // to (Op EFLAGS Cond)
21168 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21169 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21170 // to (Op EFLAGS !Cond)
21172 // where Op could be BRCOND or CMOV.
21174 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21175 // Quit if not CMP and SUB with its value result used.
21176 if (Cmp.getOpcode() != X86ISD::CMP &&
21177 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21180 // Quit if not used as a boolean value.
21181 if (CC != X86::COND_E && CC != X86::COND_NE)
21184 // Check CMP operands. One of them should be 0 or 1 and the other should be
21185 // an SetCC or extended from it.
21186 SDValue Op1 = Cmp.getOperand(0);
21187 SDValue Op2 = Cmp.getOperand(1);
21190 const ConstantSDNode* C = nullptr;
21191 bool needOppositeCond = (CC == X86::COND_E);
21192 bool checkAgainstTrue = false; // Is it a comparison against 1?
21194 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21196 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21198 else // Quit if all operands are not constants.
21201 if (C->getZExtValue() == 1) {
21202 needOppositeCond = !needOppositeCond;
21203 checkAgainstTrue = true;
21204 } else if (C->getZExtValue() != 0)
21205 // Quit if the constant is neither 0 or 1.
21208 bool truncatedToBoolWithAnd = false;
21209 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21210 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21211 SetCC.getOpcode() == ISD::TRUNCATE ||
21212 SetCC.getOpcode() == ISD::AND) {
21213 if (SetCC.getOpcode() == ISD::AND) {
21215 ConstantSDNode *CS;
21216 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21217 CS->getZExtValue() == 1)
21219 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21220 CS->getZExtValue() == 1)
21224 SetCC = SetCC.getOperand(OpIdx);
21225 truncatedToBoolWithAnd = true;
21227 SetCC = SetCC.getOperand(0);
21230 switch (SetCC.getOpcode()) {
21231 case X86ISD::SETCC_CARRY:
21232 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21233 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21234 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21235 // truncated to i1 using 'and'.
21236 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21238 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21239 "Invalid use of SETCC_CARRY!");
21241 case X86ISD::SETCC:
21242 // Set the condition code or opposite one if necessary.
21243 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21244 if (needOppositeCond)
21245 CC = X86::GetOppositeBranchCondition(CC);
21246 return SetCC.getOperand(1);
21247 case X86ISD::CMOV: {
21248 // Check whether false/true value has canonical one, i.e. 0 or 1.
21249 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21250 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21251 // Quit if true value is not a constant.
21254 // Quit if false value is not a constant.
21256 SDValue Op = SetCC.getOperand(0);
21257 // Skip 'zext' or 'trunc' node.
21258 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21259 Op.getOpcode() == ISD::TRUNCATE)
21260 Op = Op.getOperand(0);
21261 // A special case for rdrand/rdseed, where 0 is set if false cond is
21263 if ((Op.getOpcode() != X86ISD::RDRAND &&
21264 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21267 // Quit if false value is not the constant 0 or 1.
21268 bool FValIsFalse = true;
21269 if (FVal && FVal->getZExtValue() != 0) {
21270 if (FVal->getZExtValue() != 1)
21272 // If FVal is 1, opposite cond is needed.
21273 needOppositeCond = !needOppositeCond;
21274 FValIsFalse = false;
21276 // Quit if TVal is not the constant opposite of FVal.
21277 if (FValIsFalse && TVal->getZExtValue() != 1)
21279 if (!FValIsFalse && TVal->getZExtValue() != 0)
21281 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21282 if (needOppositeCond)
21283 CC = X86::GetOppositeBranchCondition(CC);
21284 return SetCC.getOperand(3);
21291 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21293 /// (X86or (X86setcc) (X86setcc))
21294 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21295 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21296 X86::CondCode &CC1, SDValue &Flags,
21298 if (Cond->getOpcode() == X86ISD::CMP) {
21299 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21300 if (!CondOp1C || !CondOp1C->isNullValue())
21303 Cond = Cond->getOperand(0);
21308 SDValue SetCC0, SetCC1;
21309 switch (Cond->getOpcode()) {
21310 default: return false;
21317 SetCC0 = Cond->getOperand(0);
21318 SetCC1 = Cond->getOperand(1);
21322 // Make sure we have SETCC nodes, using the same flags value.
21323 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21324 SetCC1.getOpcode() != X86ISD::SETCC ||
21325 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21328 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21329 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21330 Flags = SetCC0->getOperand(1);
21334 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21335 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21336 TargetLowering::DAGCombinerInfo &DCI,
21337 const X86Subtarget *Subtarget) {
21340 // If the flag operand isn't dead, don't touch this CMOV.
21341 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21344 SDValue FalseOp = N->getOperand(0);
21345 SDValue TrueOp = N->getOperand(1);
21346 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21347 SDValue Cond = N->getOperand(3);
21349 if (CC == X86::COND_E || CC == X86::COND_NE) {
21350 switch (Cond.getOpcode()) {
21354 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21355 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21356 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21362 Flags = checkBoolTestSetCCCombine(Cond, CC);
21363 if (Flags.getNode() &&
21364 // Extra check as FCMOV only supports a subset of X86 cond.
21365 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21366 SDValue Ops[] = { FalseOp, TrueOp,
21367 DAG.getConstant(CC, MVT::i8), Flags };
21368 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21371 // If this is a select between two integer constants, try to do some
21372 // optimizations. Note that the operands are ordered the opposite of SELECT
21374 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21375 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21376 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21377 // larger than FalseC (the false value).
21378 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21379 CC = X86::GetOppositeBranchCondition(CC);
21380 std::swap(TrueC, FalseC);
21381 std::swap(TrueOp, FalseOp);
21384 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21385 // This is efficient for any integer data type (including i8/i16) and
21387 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21388 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21389 DAG.getConstant(CC, MVT::i8), Cond);
21391 // Zero extend the condition if needed.
21392 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21394 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21395 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21396 DAG.getConstant(ShAmt, MVT::i8));
21397 if (N->getNumValues() == 2) // Dead flag value?
21398 return DCI.CombineTo(N, Cond, SDValue());
21402 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21403 // for any integer data type, including i8/i16.
21404 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21405 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21406 DAG.getConstant(CC, MVT::i8), Cond);
21408 // Zero extend the condition if needed.
21409 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21410 FalseC->getValueType(0), Cond);
21411 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21412 SDValue(FalseC, 0));
21414 if (N->getNumValues() == 2) // Dead flag value?
21415 return DCI.CombineTo(N, Cond, SDValue());
21419 // Optimize cases that will turn into an LEA instruction. This requires
21420 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21421 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21422 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21423 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21425 bool isFastMultiplier = false;
21427 switch ((unsigned char)Diff) {
21429 case 1: // result = add base, cond
21430 case 2: // result = lea base( , cond*2)
21431 case 3: // result = lea base(cond, cond*2)
21432 case 4: // result = lea base( , cond*4)
21433 case 5: // result = lea base(cond, cond*4)
21434 case 8: // result = lea base( , cond*8)
21435 case 9: // result = lea base(cond, cond*8)
21436 isFastMultiplier = true;
21441 if (isFastMultiplier) {
21442 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21443 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21444 DAG.getConstant(CC, MVT::i8), Cond);
21445 // Zero extend the condition if needed.
21446 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21448 // Scale the condition by the difference.
21450 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21451 DAG.getConstant(Diff, Cond.getValueType()));
21453 // Add the base if non-zero.
21454 if (FalseC->getAPIntValue() != 0)
21455 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21456 SDValue(FalseC, 0));
21457 if (N->getNumValues() == 2) // Dead flag value?
21458 return DCI.CombineTo(N, Cond, SDValue());
21465 // Handle these cases:
21466 // (select (x != c), e, c) -> select (x != c), e, x),
21467 // (select (x == c), c, e) -> select (x == c), x, e)
21468 // where the c is an integer constant, and the "select" is the combination
21469 // of CMOV and CMP.
21471 // The rationale for this change is that the conditional-move from a constant
21472 // needs two instructions, however, conditional-move from a register needs
21473 // only one instruction.
21475 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21476 // some instruction-combining opportunities. This opt needs to be
21477 // postponed as late as possible.
21479 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21480 // the DCI.xxxx conditions are provided to postpone the optimization as
21481 // late as possible.
21483 ConstantSDNode *CmpAgainst = nullptr;
21484 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21485 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21486 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21488 if (CC == X86::COND_NE &&
21489 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21490 CC = X86::GetOppositeBranchCondition(CC);
21491 std::swap(TrueOp, FalseOp);
21494 if (CC == X86::COND_E &&
21495 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21496 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21497 DAG.getConstant(CC, MVT::i8), Cond };
21498 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21503 // Fold and/or of setcc's to double CMOV:
21504 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21505 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21507 // This combine lets us generate:
21508 // cmovcc1 (jcc1 if we don't have CMOV)
21514 // cmovne (jne if we don't have CMOV)
21515 // When we can't use the CMOV instruction, it might increase branch
21517 // When we can use CMOV, or when there is no mispredict, this improves
21518 // throughput and reduces register pressure.
21520 if (CC == X86::COND_NE) {
21522 X86::CondCode CC0, CC1;
21524 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21526 std::swap(FalseOp, TrueOp);
21527 CC0 = X86::GetOppositeBranchCondition(CC0);
21528 CC1 = X86::GetOppositeBranchCondition(CC1);
21531 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21533 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21534 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21535 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21536 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21544 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21545 const X86Subtarget *Subtarget) {
21546 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21548 default: return SDValue();
21549 // SSE/AVX/AVX2 blend intrinsics.
21550 case Intrinsic::x86_avx2_pblendvb:
21551 // Don't try to simplify this intrinsic if we don't have AVX2.
21552 if (!Subtarget->hasAVX2())
21555 case Intrinsic::x86_avx_blendv_pd_256:
21556 case Intrinsic::x86_avx_blendv_ps_256:
21557 // Don't try to simplify this intrinsic if we don't have AVX.
21558 if (!Subtarget->hasAVX())
21561 case Intrinsic::x86_sse41_blendvps:
21562 case Intrinsic::x86_sse41_blendvpd:
21563 case Intrinsic::x86_sse41_pblendvb: {
21564 SDValue Op0 = N->getOperand(1);
21565 SDValue Op1 = N->getOperand(2);
21566 SDValue Mask = N->getOperand(3);
21568 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21569 if (!Subtarget->hasSSE41())
21572 // fold (blend A, A, Mask) -> A
21575 // fold (blend A, B, allZeros) -> A
21576 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21578 // fold (blend A, B, allOnes) -> B
21579 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21582 // Simplify the case where the mask is a constant i32 value.
21583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21584 if (C->isNullValue())
21586 if (C->isAllOnesValue())
21593 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21594 case Intrinsic::x86_sse2_psrai_w:
21595 case Intrinsic::x86_sse2_psrai_d:
21596 case Intrinsic::x86_avx2_psrai_w:
21597 case Intrinsic::x86_avx2_psrai_d:
21598 case Intrinsic::x86_sse2_psra_w:
21599 case Intrinsic::x86_sse2_psra_d:
21600 case Intrinsic::x86_avx2_psra_w:
21601 case Intrinsic::x86_avx2_psra_d: {
21602 SDValue Op0 = N->getOperand(1);
21603 SDValue Op1 = N->getOperand(2);
21604 EVT VT = Op0.getValueType();
21605 assert(VT.isVector() && "Expected a vector type!");
21607 if (isa<BuildVectorSDNode>(Op1))
21608 Op1 = Op1.getOperand(0);
21610 if (!isa<ConstantSDNode>(Op1))
21613 EVT SVT = VT.getVectorElementType();
21614 unsigned SVTBits = SVT.getSizeInBits();
21616 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21617 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21618 uint64_t ShAmt = C.getZExtValue();
21620 // Don't try to convert this shift into a ISD::SRA if the shift
21621 // count is bigger than or equal to the element size.
21622 if (ShAmt >= SVTBits)
21625 // Trivial case: if the shift count is zero, then fold this
21626 // into the first operand.
21630 // Replace this packed shift intrinsic with a target independent
21632 SDValue Splat = DAG.getConstant(C, VT);
21633 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21638 /// PerformMulCombine - Optimize a single multiply with constant into two
21639 /// in order to implement it with two cheaper instructions, e.g.
21640 /// LEA + SHL, LEA + LEA.
21641 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21642 TargetLowering::DAGCombinerInfo &DCI) {
21643 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21646 EVT VT = N->getValueType(0);
21647 if (VT != MVT::i64 && VT != MVT::i32)
21650 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21653 uint64_t MulAmt = C->getZExtValue();
21654 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21657 uint64_t MulAmt1 = 0;
21658 uint64_t MulAmt2 = 0;
21659 if ((MulAmt % 9) == 0) {
21661 MulAmt2 = MulAmt / 9;
21662 } else if ((MulAmt % 5) == 0) {
21664 MulAmt2 = MulAmt / 5;
21665 } else if ((MulAmt % 3) == 0) {
21667 MulAmt2 = MulAmt / 3;
21670 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21673 if (isPowerOf2_64(MulAmt2) &&
21674 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21675 // If second multiplifer is pow2, issue it first. We want the multiply by
21676 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21678 std::swap(MulAmt1, MulAmt2);
21681 if (isPowerOf2_64(MulAmt1))
21682 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21683 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21685 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21686 DAG.getConstant(MulAmt1, VT));
21688 if (isPowerOf2_64(MulAmt2))
21689 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21690 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21692 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21693 DAG.getConstant(MulAmt2, VT));
21695 // Do not add new nodes to DAG combiner worklist.
21696 DCI.CombineTo(N, NewMul, false);
21701 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21702 SDValue N0 = N->getOperand(0);
21703 SDValue N1 = N->getOperand(1);
21704 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21705 EVT VT = N0.getValueType();
21707 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21708 // since the result of setcc_c is all zero's or all ones.
21709 if (VT.isInteger() && !VT.isVector() &&
21710 N1C && N0.getOpcode() == ISD::AND &&
21711 N0.getOperand(1).getOpcode() == ISD::Constant) {
21712 SDValue N00 = N0.getOperand(0);
21713 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21714 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21715 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21716 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21717 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21718 APInt ShAmt = N1C->getAPIntValue();
21719 Mask = Mask.shl(ShAmt);
21721 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21722 N00, DAG.getConstant(Mask, VT));
21726 // Hardware support for vector shifts is sparse which makes us scalarize the
21727 // vector operations in many cases. Also, on sandybridge ADD is faster than
21729 // (shl V, 1) -> add V,V
21730 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21731 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21732 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21733 // We shift all of the values by one. In many cases we do not have
21734 // hardware support for this operation. This is better expressed as an ADD
21736 if (N1SplatC->getZExtValue() == 1)
21737 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21743 /// \brief Returns a vector of 0s if the node in input is a vector logical
21744 /// shift by a constant amount which is known to be bigger than or equal
21745 /// to the vector element size in bits.
21746 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21747 const X86Subtarget *Subtarget) {
21748 EVT VT = N->getValueType(0);
21750 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21751 (!Subtarget->hasInt256() ||
21752 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21755 SDValue Amt = N->getOperand(1);
21757 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21758 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21759 APInt ShiftAmt = AmtSplat->getAPIntValue();
21760 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21762 // SSE2/AVX2 logical shifts always return a vector of 0s
21763 // if the shift amount is bigger than or equal to
21764 // the element size. The constant shift amount will be
21765 // encoded as a 8-bit immediate.
21766 if (ShiftAmt.trunc(8).uge(MaxAmount))
21767 return getZeroVector(VT, Subtarget, DAG, DL);
21773 /// PerformShiftCombine - Combine shifts.
21774 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21775 TargetLowering::DAGCombinerInfo &DCI,
21776 const X86Subtarget *Subtarget) {
21777 if (N->getOpcode() == ISD::SHL) {
21778 SDValue V = PerformSHLCombine(N, DAG);
21779 if (V.getNode()) return V;
21782 if (N->getOpcode() != ISD::SRA) {
21783 // Try to fold this logical shift into a zero vector.
21784 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21785 if (V.getNode()) return V;
21791 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21792 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21793 // and friends. Likewise for OR -> CMPNEQSS.
21794 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21795 TargetLowering::DAGCombinerInfo &DCI,
21796 const X86Subtarget *Subtarget) {
21799 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21800 // we're requiring SSE2 for both.
21801 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21802 SDValue N0 = N->getOperand(0);
21803 SDValue N1 = N->getOperand(1);
21804 SDValue CMP0 = N0->getOperand(1);
21805 SDValue CMP1 = N1->getOperand(1);
21808 // The SETCCs should both refer to the same CMP.
21809 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21812 SDValue CMP00 = CMP0->getOperand(0);
21813 SDValue CMP01 = CMP0->getOperand(1);
21814 EVT VT = CMP00.getValueType();
21816 if (VT == MVT::f32 || VT == MVT::f64) {
21817 bool ExpectingFlags = false;
21818 // Check for any users that want flags:
21819 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21820 !ExpectingFlags && UI != UE; ++UI)
21821 switch (UI->getOpcode()) {
21826 ExpectingFlags = true;
21828 case ISD::CopyToReg:
21829 case ISD::SIGN_EXTEND:
21830 case ISD::ZERO_EXTEND:
21831 case ISD::ANY_EXTEND:
21835 if (!ExpectingFlags) {
21836 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21837 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21839 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21840 X86::CondCode tmp = cc0;
21845 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21846 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21847 // FIXME: need symbolic constants for these magic numbers.
21848 // See X86ATTInstPrinter.cpp:printSSECC().
21849 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21850 if (Subtarget->hasAVX512()) {
21851 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21852 CMP01, DAG.getConstant(x86cc, MVT::i8));
21853 if (N->getValueType(0) != MVT::i1)
21854 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21858 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21859 CMP00.getValueType(), CMP00, CMP01,
21860 DAG.getConstant(x86cc, MVT::i8));
21862 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21863 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21865 if (is64BitFP && !Subtarget->is64Bit()) {
21866 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21867 // 64-bit integer, since that's not a legal type. Since
21868 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21869 // bits, but can do this little dance to extract the lowest 32 bits
21870 // and work with those going forward.
21871 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21873 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21875 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21876 Vector32, DAG.getIntPtrConstant(0));
21880 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21881 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21882 DAG.getConstant(1, IntVT));
21883 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21884 return OneBitOfTruth;
21892 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21893 /// so it can be folded inside ANDNP.
21894 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21895 EVT VT = N->getValueType(0);
21897 // Match direct AllOnes for 128 and 256-bit vectors
21898 if (ISD::isBuildVectorAllOnes(N))
21901 // Look through a bit convert.
21902 if (N->getOpcode() == ISD::BITCAST)
21903 N = N->getOperand(0).getNode();
21905 // Sometimes the operand may come from a insert_subvector building a 256-bit
21907 if (VT.is256BitVector() &&
21908 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21909 SDValue V1 = N->getOperand(0);
21910 SDValue V2 = N->getOperand(1);
21912 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21913 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21914 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21915 ISD::isBuildVectorAllOnes(V2.getNode()))
21922 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21923 // register. In most cases we actually compare or select YMM-sized registers
21924 // and mixing the two types creates horrible code. This method optimizes
21925 // some of the transition sequences.
21926 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21927 TargetLowering::DAGCombinerInfo &DCI,
21928 const X86Subtarget *Subtarget) {
21929 EVT VT = N->getValueType(0);
21930 if (!VT.is256BitVector())
21933 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21934 N->getOpcode() == ISD::ZERO_EXTEND ||
21935 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21937 SDValue Narrow = N->getOperand(0);
21938 EVT NarrowVT = Narrow->getValueType(0);
21939 if (!NarrowVT.is128BitVector())
21942 if (Narrow->getOpcode() != ISD::XOR &&
21943 Narrow->getOpcode() != ISD::AND &&
21944 Narrow->getOpcode() != ISD::OR)
21947 SDValue N0 = Narrow->getOperand(0);
21948 SDValue N1 = Narrow->getOperand(1);
21951 // The Left side has to be a trunc.
21952 if (N0.getOpcode() != ISD::TRUNCATE)
21955 // The type of the truncated inputs.
21956 EVT WideVT = N0->getOperand(0)->getValueType(0);
21960 // The right side has to be a 'trunc' or a constant vector.
21961 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21962 ConstantSDNode *RHSConstSplat = nullptr;
21963 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21964 RHSConstSplat = RHSBV->getConstantSplatNode();
21965 if (!RHSTrunc && !RHSConstSplat)
21968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21970 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21973 // Set N0 and N1 to hold the inputs to the new wide operation.
21974 N0 = N0->getOperand(0);
21975 if (RHSConstSplat) {
21976 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21977 SDValue(RHSConstSplat, 0));
21978 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21979 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21980 } else if (RHSTrunc) {
21981 N1 = N1->getOperand(0);
21984 // Generate the wide operation.
21985 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21986 unsigned Opcode = N->getOpcode();
21988 case ISD::ANY_EXTEND:
21990 case ISD::ZERO_EXTEND: {
21991 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21992 APInt Mask = APInt::getAllOnesValue(InBits);
21993 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21994 return DAG.getNode(ISD::AND, DL, VT,
21995 Op, DAG.getConstant(Mask, VT));
21997 case ISD::SIGN_EXTEND:
21998 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21999 Op, DAG.getValueType(NarrowVT));
22001 llvm_unreachable("Unexpected opcode");
22005 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22006 TargetLowering::DAGCombinerInfo &DCI,
22007 const X86Subtarget *Subtarget) {
22008 SDValue N0 = N->getOperand(0);
22009 SDValue N1 = N->getOperand(1);
22012 // A vector zext_in_reg may be represented as a shuffle,
22013 // feeding into a bitcast (this represents anyext) feeding into
22014 // an and with a mask.
22015 // We'd like to try to combine that into a shuffle with zero
22016 // plus a bitcast, removing the and.
22017 if (N0.getOpcode() != ISD::BITCAST ||
22018 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22021 // The other side of the AND should be a splat of 2^C, where C
22022 // is the number of bits in the source type.
22023 if (N1.getOpcode() == ISD::BITCAST)
22024 N1 = N1.getOperand(0);
22025 if (N1.getOpcode() != ISD::BUILD_VECTOR)
22027 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22029 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22030 EVT SrcType = Shuffle->getValueType(0);
22032 // We expect a single-source shuffle
22033 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22036 unsigned SrcSize = SrcType.getScalarSizeInBits();
22038 APInt SplatValue, SplatUndef;
22039 unsigned SplatBitSize;
22041 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22042 SplatBitSize, HasAnyUndefs))
22045 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22046 // Make sure the splat matches the mask we expect
22047 if (SplatBitSize > ResSize ||
22048 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22051 // Make sure the input and output size make sense
22052 if (SrcSize >= ResSize || ResSize % SrcSize)
22055 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22056 // The number of u's between each two values depends on the ratio between
22057 // the source and dest type.
22058 unsigned ZextRatio = ResSize / SrcSize;
22059 bool IsZext = true;
22060 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22061 if (i % ZextRatio) {
22062 if (Shuffle->getMaskElt(i) > 0) {
22068 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22069 // Expected element number
22079 // Ok, perform the transformation - replace the shuffle with
22080 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22081 // (instead of undef) where the k elements come from the zero vector.
22082 SmallVector<int, 8> Mask;
22083 unsigned NumElems = SrcType.getVectorNumElements();
22084 for (unsigned i = 0; i < NumElems; ++i)
22086 Mask.push_back(NumElems);
22088 Mask.push_back(i / ZextRatio);
22090 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22091 Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22092 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22095 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22096 TargetLowering::DAGCombinerInfo &DCI,
22097 const X86Subtarget *Subtarget) {
22098 if (DCI.isBeforeLegalizeOps())
22101 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22104 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22107 EVT VT = N->getValueType(0);
22108 SDValue N0 = N->getOperand(0);
22109 SDValue N1 = N->getOperand(1);
22112 // Create BEXTR instructions
22113 // BEXTR is ((X >> imm) & (2**size-1))
22114 if (VT == MVT::i32 || VT == MVT::i64) {
22115 // Check for BEXTR.
22116 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22117 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22118 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22119 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22120 if (MaskNode && ShiftNode) {
22121 uint64_t Mask = MaskNode->getZExtValue();
22122 uint64_t Shift = ShiftNode->getZExtValue();
22123 if (isMask_64(Mask)) {
22124 uint64_t MaskSize = countPopulation(Mask);
22125 if (Shift + MaskSize <= VT.getSizeInBits())
22126 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22127 DAG.getConstant(Shift | (MaskSize << 8), VT));
22135 // Want to form ANDNP nodes:
22136 // 1) In the hopes of then easily combining them with OR and AND nodes
22137 // to form PBLEND/PSIGN.
22138 // 2) To match ANDN packed intrinsics
22139 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22142 // Check LHS for vnot
22143 if (N0.getOpcode() == ISD::XOR &&
22144 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22145 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22146 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22148 // Check RHS for vnot
22149 if (N1.getOpcode() == ISD::XOR &&
22150 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22151 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22152 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22157 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22158 TargetLowering::DAGCombinerInfo &DCI,
22159 const X86Subtarget *Subtarget) {
22160 if (DCI.isBeforeLegalizeOps())
22163 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22167 SDValue N0 = N->getOperand(0);
22168 SDValue N1 = N->getOperand(1);
22169 EVT VT = N->getValueType(0);
22171 // look for psign/blend
22172 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22173 if (!Subtarget->hasSSSE3() ||
22174 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22177 // Canonicalize pandn to RHS
22178 if (N0.getOpcode() == X86ISD::ANDNP)
22180 // or (and (m, y), (pandn m, x))
22181 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22182 SDValue Mask = N1.getOperand(0);
22183 SDValue X = N1.getOperand(1);
22185 if (N0.getOperand(0) == Mask)
22186 Y = N0.getOperand(1);
22187 if (N0.getOperand(1) == Mask)
22188 Y = N0.getOperand(0);
22190 // Check to see if the mask appeared in both the AND and ANDNP and
22194 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22195 // Look through mask bitcast.
22196 if (Mask.getOpcode() == ISD::BITCAST)
22197 Mask = Mask.getOperand(0);
22198 if (X.getOpcode() == ISD::BITCAST)
22199 X = X.getOperand(0);
22200 if (Y.getOpcode() == ISD::BITCAST)
22201 Y = Y.getOperand(0);
22203 EVT MaskVT = Mask.getValueType();
22205 // Validate that the Mask operand is a vector sra node.
22206 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22207 // there is no psrai.b
22208 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22209 unsigned SraAmt = ~0;
22210 if (Mask.getOpcode() == ISD::SRA) {
22211 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22212 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22213 SraAmt = AmtConst->getZExtValue();
22214 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22215 SDValue SraC = Mask.getOperand(1);
22216 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22218 if ((SraAmt + 1) != EltBits)
22223 // Now we know we at least have a plendvb with the mask val. See if
22224 // we can form a psignb/w/d.
22225 // psign = x.type == y.type == mask.type && y = sub(0, x);
22226 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22227 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22228 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22229 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22230 "Unsupported VT for PSIGN");
22231 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22232 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22234 // PBLENDVB only available on SSE 4.1
22235 if (!Subtarget->hasSSE41())
22238 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22240 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22241 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22242 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22243 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22244 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22248 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22251 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22252 MachineFunction &MF = DAG.getMachineFunction();
22254 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22256 // SHLD/SHRD instructions have lower register pressure, but on some
22257 // platforms they have higher latency than the equivalent
22258 // series of shifts/or that would otherwise be generated.
22259 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22260 // have higher latencies and we are not optimizing for size.
22261 if (!OptForSize && Subtarget->isSHLDSlow())
22264 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22266 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22268 if (!N0.hasOneUse() || !N1.hasOneUse())
22271 SDValue ShAmt0 = N0.getOperand(1);
22272 if (ShAmt0.getValueType() != MVT::i8)
22274 SDValue ShAmt1 = N1.getOperand(1);
22275 if (ShAmt1.getValueType() != MVT::i8)
22277 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22278 ShAmt0 = ShAmt0.getOperand(0);
22279 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22280 ShAmt1 = ShAmt1.getOperand(0);
22283 unsigned Opc = X86ISD::SHLD;
22284 SDValue Op0 = N0.getOperand(0);
22285 SDValue Op1 = N1.getOperand(0);
22286 if (ShAmt0.getOpcode() == ISD::SUB) {
22287 Opc = X86ISD::SHRD;
22288 std::swap(Op0, Op1);
22289 std::swap(ShAmt0, ShAmt1);
22292 unsigned Bits = VT.getSizeInBits();
22293 if (ShAmt1.getOpcode() == ISD::SUB) {
22294 SDValue Sum = ShAmt1.getOperand(0);
22295 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22296 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22297 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22298 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22299 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22300 return DAG.getNode(Opc, DL, VT,
22302 DAG.getNode(ISD::TRUNCATE, DL,
22305 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22306 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22308 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22309 return DAG.getNode(Opc, DL, VT,
22310 N0.getOperand(0), N1.getOperand(0),
22311 DAG.getNode(ISD::TRUNCATE, DL,
22318 // Generate NEG and CMOV for integer abs.
22319 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22320 EVT VT = N->getValueType(0);
22322 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22323 // 8-bit integer abs to NEG and CMOV.
22324 if (VT.isInteger() && VT.getSizeInBits() == 8)
22327 SDValue N0 = N->getOperand(0);
22328 SDValue N1 = N->getOperand(1);
22331 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22332 // and change it to SUB and CMOV.
22333 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22334 N0.getOpcode() == ISD::ADD &&
22335 N0.getOperand(1) == N1 &&
22336 N1.getOpcode() == ISD::SRA &&
22337 N1.getOperand(0) == N0.getOperand(0))
22338 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22339 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22340 // Generate SUB & CMOV.
22341 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22342 DAG.getConstant(0, VT), N0.getOperand(0));
22344 SDValue Ops[] = { N0.getOperand(0), Neg,
22345 DAG.getConstant(X86::COND_GE, MVT::i8),
22346 SDValue(Neg.getNode(), 1) };
22347 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22352 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22353 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22354 TargetLowering::DAGCombinerInfo &DCI,
22355 const X86Subtarget *Subtarget) {
22356 if (DCI.isBeforeLegalizeOps())
22359 if (Subtarget->hasCMov()) {
22360 SDValue RV = performIntegerAbsCombine(N, DAG);
22368 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22369 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22370 TargetLowering::DAGCombinerInfo &DCI,
22371 const X86Subtarget *Subtarget) {
22372 LoadSDNode *Ld = cast<LoadSDNode>(N);
22373 EVT RegVT = Ld->getValueType(0);
22374 EVT MemVT = Ld->getMemoryVT();
22376 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22378 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22379 // into two 16-byte operations.
22380 ISD::LoadExtType Ext = Ld->getExtensionType();
22381 unsigned Alignment = Ld->getAlignment();
22382 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22383 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22384 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22385 unsigned NumElems = RegVT.getVectorNumElements();
22389 SDValue Ptr = Ld->getBasePtr();
22390 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22392 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22394 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22395 Ld->getPointerInfo(), Ld->isVolatile(),
22396 Ld->isNonTemporal(), Ld->isInvariant(),
22398 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22399 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22400 Ld->getPointerInfo(), Ld->isVolatile(),
22401 Ld->isNonTemporal(), Ld->isInvariant(),
22402 std::min(16U, Alignment));
22403 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22405 Load2.getValue(1));
22407 SDValue NewVec = DAG.getUNDEF(RegVT);
22408 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22409 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22410 return DCI.CombineTo(N, NewVec, TF, true);
22416 /// PerformMLOADCombine - Resolve extending loads
22417 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22418 TargetLowering::DAGCombinerInfo &DCI,
22419 const X86Subtarget *Subtarget) {
22420 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22421 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22424 EVT VT = Mld->getValueType(0);
22425 unsigned NumElems = VT.getVectorNumElements();
22426 EVT LdVT = Mld->getMemoryVT();
22429 assert(LdVT != VT && "Cannot extend to the same type");
22430 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22431 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22432 // From, To sizes and ElemCount must be pow of two
22433 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22434 "Unexpected size for extending masked load");
22436 unsigned SizeRatio = ToSz / FromSz;
22437 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22439 // Create a type on which we perform the shuffle
22440 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22441 LdVT.getScalarType(), NumElems*SizeRatio);
22442 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22444 // Convert Src0 value
22445 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22446 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22447 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22448 for (unsigned i = 0; i != NumElems; ++i)
22449 ShuffleVec[i] = i * SizeRatio;
22451 // Can't shuffle using an illegal type.
22452 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22453 && "WideVecVT should be legal");
22454 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22455 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22457 // Prepare the new mask
22459 SDValue Mask = Mld->getMask();
22460 if (Mask.getValueType() == VT) {
22461 // Mask and original value have the same type
22462 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22463 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22464 for (unsigned i = 0; i != NumElems; ++i)
22465 ShuffleVec[i] = i * SizeRatio;
22466 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22467 ShuffleVec[i] = NumElems*SizeRatio;
22468 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22469 DAG.getConstant(0, WideVecVT),
22473 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22474 unsigned WidenNumElts = NumElems*SizeRatio;
22475 unsigned MaskNumElts = VT.getVectorNumElements();
22476 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22479 unsigned NumConcat = WidenNumElts / MaskNumElts;
22480 SmallVector<SDValue, 16> Ops(NumConcat);
22481 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22483 for (unsigned i = 1; i != NumConcat; ++i)
22486 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22489 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22490 Mld->getBasePtr(), NewMask, WideSrc0,
22491 Mld->getMemoryVT(), Mld->getMemOperand(),
22493 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22494 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22497 /// PerformMSTORECombine - Resolve truncating stores
22498 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22499 const X86Subtarget *Subtarget) {
22500 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22501 if (!Mst->isTruncatingStore())
22504 EVT VT = Mst->getValue().getValueType();
22505 unsigned NumElems = VT.getVectorNumElements();
22506 EVT StVT = Mst->getMemoryVT();
22509 assert(StVT != VT && "Cannot truncate to the same type");
22510 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22511 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22513 // From, To sizes and ElemCount must be pow of two
22514 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22515 "Unexpected size for truncating masked store");
22516 // We are going to use the original vector elt for storing.
22517 // Accumulated smaller vector elements must be a multiple of the store size.
22518 assert (((NumElems * FromSz) % ToSz) == 0 &&
22519 "Unexpected ratio for truncating masked store");
22521 unsigned SizeRatio = FromSz / ToSz;
22522 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22524 // Create a type on which we perform the shuffle
22525 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22526 StVT.getScalarType(), NumElems*SizeRatio);
22528 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22530 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22531 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22532 for (unsigned i = 0; i != NumElems; ++i)
22533 ShuffleVec[i] = i * SizeRatio;
22535 // Can't shuffle using an illegal type.
22536 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22537 && "WideVecVT should be legal");
22539 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22540 DAG.getUNDEF(WideVecVT),
22544 SDValue Mask = Mst->getMask();
22545 if (Mask.getValueType() == VT) {
22546 // Mask and original value have the same type
22547 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22548 for (unsigned i = 0; i != NumElems; ++i)
22549 ShuffleVec[i] = i * SizeRatio;
22550 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22551 ShuffleVec[i] = NumElems*SizeRatio;
22552 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22553 DAG.getConstant(0, WideVecVT),
22557 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22558 unsigned WidenNumElts = NumElems*SizeRatio;
22559 unsigned MaskNumElts = VT.getVectorNumElements();
22560 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22563 unsigned NumConcat = WidenNumElts / MaskNumElts;
22564 SmallVector<SDValue, 16> Ops(NumConcat);
22565 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22567 for (unsigned i = 1; i != NumConcat; ++i)
22570 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22573 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22574 NewMask, StVT, Mst->getMemOperand(), false);
22576 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22577 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22578 const X86Subtarget *Subtarget) {
22579 StoreSDNode *St = cast<StoreSDNode>(N);
22580 EVT VT = St->getValue().getValueType();
22581 EVT StVT = St->getMemoryVT();
22583 SDValue StoredVal = St->getOperand(1);
22584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22586 // If we are saving a concatenation of two XMM registers and 32-byte stores
22587 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22588 unsigned Alignment = St->getAlignment();
22589 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22590 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22591 StVT == VT && !IsAligned) {
22592 unsigned NumElems = VT.getVectorNumElements();
22596 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22597 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22599 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22600 SDValue Ptr0 = St->getBasePtr();
22601 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22603 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22604 St->getPointerInfo(), St->isVolatile(),
22605 St->isNonTemporal(), Alignment);
22606 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22607 St->getPointerInfo(), St->isVolatile(),
22608 St->isNonTemporal(),
22609 std::min(16U, Alignment));
22610 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22613 // Optimize trunc store (of multiple scalars) to shuffle and store.
22614 // First, pack all of the elements in one place. Next, store to memory
22615 // in fewer chunks.
22616 if (St->isTruncatingStore() && VT.isVector()) {
22617 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22618 unsigned NumElems = VT.getVectorNumElements();
22619 assert(StVT != VT && "Cannot truncate to the same type");
22620 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22621 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22623 // From, To sizes and ElemCount must be pow of two
22624 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22625 // We are going to use the original vector elt for storing.
22626 // Accumulated smaller vector elements must be a multiple of the store size.
22627 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22629 unsigned SizeRatio = FromSz / ToSz;
22631 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22633 // Create a type on which we perform the shuffle
22634 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22635 StVT.getScalarType(), NumElems*SizeRatio);
22637 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22639 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22640 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22641 for (unsigned i = 0; i != NumElems; ++i)
22642 ShuffleVec[i] = i * SizeRatio;
22644 // Can't shuffle using an illegal type.
22645 if (!TLI.isTypeLegal(WideVecVT))
22648 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22649 DAG.getUNDEF(WideVecVT),
22651 // At this point all of the data is stored at the bottom of the
22652 // register. We now need to save it to mem.
22654 // Find the largest store unit
22655 MVT StoreType = MVT::i8;
22656 for (MVT Tp : MVT::integer_valuetypes()) {
22657 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22661 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22662 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22663 (64 <= NumElems * ToSz))
22664 StoreType = MVT::f64;
22666 // Bitcast the original vector into a vector of store-size units
22667 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22668 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22669 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22670 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22671 SmallVector<SDValue, 8> Chains;
22672 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22673 TLI.getPointerTy());
22674 SDValue Ptr = St->getBasePtr();
22676 // Perform one or more big stores into memory.
22677 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22678 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22679 StoreType, ShuffWide,
22680 DAG.getIntPtrConstant(i));
22681 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22682 St->getPointerInfo(), St->isVolatile(),
22683 St->isNonTemporal(), St->getAlignment());
22684 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22685 Chains.push_back(Ch);
22688 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22691 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22692 // the FP state in cases where an emms may be missing.
22693 // A preferable solution to the general problem is to figure out the right
22694 // places to insert EMMS. This qualifies as a quick hack.
22696 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22697 if (VT.getSizeInBits() != 64)
22700 const Function *F = DAG.getMachineFunction().getFunction();
22701 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22702 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22703 && Subtarget->hasSSE2();
22704 if ((VT.isVector() ||
22705 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22706 isa<LoadSDNode>(St->getValue()) &&
22707 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22708 St->getChain().hasOneUse() && !St->isVolatile()) {
22709 SDNode* LdVal = St->getValue().getNode();
22710 LoadSDNode *Ld = nullptr;
22711 int TokenFactorIndex = -1;
22712 SmallVector<SDValue, 8> Ops;
22713 SDNode* ChainVal = St->getChain().getNode();
22714 // Must be a store of a load. We currently handle two cases: the load
22715 // is a direct child, and it's under an intervening TokenFactor. It is
22716 // possible to dig deeper under nested TokenFactors.
22717 if (ChainVal == LdVal)
22718 Ld = cast<LoadSDNode>(St->getChain());
22719 else if (St->getValue().hasOneUse() &&
22720 ChainVal->getOpcode() == ISD::TokenFactor) {
22721 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22722 if (ChainVal->getOperand(i).getNode() == LdVal) {
22723 TokenFactorIndex = i;
22724 Ld = cast<LoadSDNode>(St->getValue());
22726 Ops.push_back(ChainVal->getOperand(i));
22730 if (!Ld || !ISD::isNormalLoad(Ld))
22733 // If this is not the MMX case, i.e. we are just turning i64 load/store
22734 // into f64 load/store, avoid the transformation if there are multiple
22735 // uses of the loaded value.
22736 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22741 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22742 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22744 if (Subtarget->is64Bit() || F64IsLegal) {
22745 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22746 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22747 Ld->getPointerInfo(), Ld->isVolatile(),
22748 Ld->isNonTemporal(), Ld->isInvariant(),
22749 Ld->getAlignment());
22750 SDValue NewChain = NewLd.getValue(1);
22751 if (TokenFactorIndex != -1) {
22752 Ops.push_back(NewChain);
22753 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22755 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22756 St->getPointerInfo(),
22757 St->isVolatile(), St->isNonTemporal(),
22758 St->getAlignment());
22761 // Otherwise, lower to two pairs of 32-bit loads / stores.
22762 SDValue LoAddr = Ld->getBasePtr();
22763 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22764 DAG.getConstant(4, MVT::i32));
22766 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22767 Ld->getPointerInfo(),
22768 Ld->isVolatile(), Ld->isNonTemporal(),
22769 Ld->isInvariant(), Ld->getAlignment());
22770 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22771 Ld->getPointerInfo().getWithOffset(4),
22772 Ld->isVolatile(), Ld->isNonTemporal(),
22774 MinAlign(Ld->getAlignment(), 4));
22776 SDValue NewChain = LoLd.getValue(1);
22777 if (TokenFactorIndex != -1) {
22778 Ops.push_back(LoLd);
22779 Ops.push_back(HiLd);
22780 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22783 LoAddr = St->getBasePtr();
22784 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22785 DAG.getConstant(4, MVT::i32));
22787 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22788 St->getPointerInfo(),
22789 St->isVolatile(), St->isNonTemporal(),
22790 St->getAlignment());
22791 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22792 St->getPointerInfo().getWithOffset(4),
22794 St->isNonTemporal(),
22795 MinAlign(St->getAlignment(), 4));
22796 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22801 /// Return 'true' if this vector operation is "horizontal"
22802 /// and return the operands for the horizontal operation in LHS and RHS. A
22803 /// horizontal operation performs the binary operation on successive elements
22804 /// of its first operand, then on successive elements of its second operand,
22805 /// returning the resulting values in a vector. For example, if
22806 /// A = < float a0, float a1, float a2, float a3 >
22808 /// B = < float b0, float b1, float b2, float b3 >
22809 /// then the result of doing a horizontal operation on A and B is
22810 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22811 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22812 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22813 /// set to A, RHS to B, and the routine returns 'true'.
22814 /// Note that the binary operation should have the property that if one of the
22815 /// operands is UNDEF then the result is UNDEF.
22816 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22817 // Look for the following pattern: if
22818 // A = < float a0, float a1, float a2, float a3 >
22819 // B = < float b0, float b1, float b2, float b3 >
22821 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22822 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22823 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22824 // which is A horizontal-op B.
22826 // At least one of the operands should be a vector shuffle.
22827 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22828 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22831 MVT VT = LHS.getSimpleValueType();
22833 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22834 "Unsupported vector type for horizontal add/sub");
22836 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22837 // operate independently on 128-bit lanes.
22838 unsigned NumElts = VT.getVectorNumElements();
22839 unsigned NumLanes = VT.getSizeInBits()/128;
22840 unsigned NumLaneElts = NumElts / NumLanes;
22841 assert((NumLaneElts % 2 == 0) &&
22842 "Vector type should have an even number of elements in each lane");
22843 unsigned HalfLaneElts = NumLaneElts/2;
22845 // View LHS in the form
22846 // LHS = VECTOR_SHUFFLE A, B, LMask
22847 // If LHS is not a shuffle then pretend it is the shuffle
22848 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22849 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22852 SmallVector<int, 16> LMask(NumElts);
22853 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22854 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22855 A = LHS.getOperand(0);
22856 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22857 B = LHS.getOperand(1);
22858 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22859 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22861 if (LHS.getOpcode() != ISD::UNDEF)
22863 for (unsigned i = 0; i != NumElts; ++i)
22867 // Likewise, view RHS in the form
22868 // RHS = VECTOR_SHUFFLE C, D, RMask
22870 SmallVector<int, 16> RMask(NumElts);
22871 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22872 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22873 C = RHS.getOperand(0);
22874 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22875 D = RHS.getOperand(1);
22876 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22877 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22879 if (RHS.getOpcode() != ISD::UNDEF)
22881 for (unsigned i = 0; i != NumElts; ++i)
22885 // Check that the shuffles are both shuffling the same vectors.
22886 if (!(A == C && B == D) && !(A == D && B == C))
22889 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22890 if (!A.getNode() && !B.getNode())
22893 // If A and B occur in reverse order in RHS, then "swap" them (which means
22894 // rewriting the mask).
22896 ShuffleVectorSDNode::commuteMask(RMask);
22898 // At this point LHS and RHS are equivalent to
22899 // LHS = VECTOR_SHUFFLE A, B, LMask
22900 // RHS = VECTOR_SHUFFLE A, B, RMask
22901 // Check that the masks correspond to performing a horizontal operation.
22902 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22903 for (unsigned i = 0; i != NumLaneElts; ++i) {
22904 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22906 // Ignore any UNDEF components.
22907 if (LIdx < 0 || RIdx < 0 ||
22908 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22909 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22912 // Check that successive elements are being operated on. If not, this is
22913 // not a horizontal operation.
22914 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22915 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22916 if (!(LIdx == Index && RIdx == Index + 1) &&
22917 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22922 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22923 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22927 /// Do target-specific dag combines on floating point adds.
22928 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22929 const X86Subtarget *Subtarget) {
22930 EVT VT = N->getValueType(0);
22931 SDValue LHS = N->getOperand(0);
22932 SDValue RHS = N->getOperand(1);
22934 // Try to synthesize horizontal adds from adds of shuffles.
22935 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22936 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22937 isHorizontalBinOp(LHS, RHS, true))
22938 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22942 /// Do target-specific dag combines on floating point subs.
22943 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22944 const X86Subtarget *Subtarget) {
22945 EVT VT = N->getValueType(0);
22946 SDValue LHS = N->getOperand(0);
22947 SDValue RHS = N->getOperand(1);
22949 // Try to synthesize horizontal subs from subs of shuffles.
22950 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22951 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22952 isHorizontalBinOp(LHS, RHS, false))
22953 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22957 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22958 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22959 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22961 // F[X]OR(0.0, x) -> x
22962 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22963 if (C->getValueAPF().isPosZero())
22964 return N->getOperand(1);
22966 // F[X]OR(x, 0.0) -> x
22967 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22968 if (C->getValueAPF().isPosZero())
22969 return N->getOperand(0);
22973 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22974 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22975 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22977 // Only perform optimizations if UnsafeMath is used.
22978 if (!DAG.getTarget().Options.UnsafeFPMath)
22981 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22982 // into FMINC and FMAXC, which are Commutative operations.
22983 unsigned NewOp = 0;
22984 switch (N->getOpcode()) {
22985 default: llvm_unreachable("unknown opcode");
22986 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22987 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22990 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22991 N->getOperand(0), N->getOperand(1));
22994 /// Do target-specific dag combines on X86ISD::FAND nodes.
22995 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22996 // FAND(0.0, x) -> 0.0
22997 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22998 if (C->getValueAPF().isPosZero())
22999 return N->getOperand(0);
23001 // FAND(x, 0.0) -> 0.0
23002 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23003 if (C->getValueAPF().isPosZero())
23004 return N->getOperand(1);
23009 /// Do target-specific dag combines on X86ISD::FANDN nodes
23010 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23011 // FANDN(0.0, x) -> x
23012 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23013 if (C->getValueAPF().isPosZero())
23014 return N->getOperand(1);
23016 // FANDN(x, 0.0) -> 0.0
23017 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23018 if (C->getValueAPF().isPosZero())
23019 return N->getOperand(1);
23024 static SDValue PerformBTCombine(SDNode *N,
23026 TargetLowering::DAGCombinerInfo &DCI) {
23027 // BT ignores high bits in the bit index operand.
23028 SDValue Op1 = N->getOperand(1);
23029 if (Op1.hasOneUse()) {
23030 unsigned BitWidth = Op1.getValueSizeInBits();
23031 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23032 APInt KnownZero, KnownOne;
23033 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23034 !DCI.isBeforeLegalizeOps());
23035 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23036 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23037 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23038 DCI.CommitTargetLoweringOpt(TLO);
23043 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23044 SDValue Op = N->getOperand(0);
23045 if (Op.getOpcode() == ISD::BITCAST)
23046 Op = Op.getOperand(0);
23047 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23048 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23049 VT.getVectorElementType().getSizeInBits() ==
23050 OpVT.getVectorElementType().getSizeInBits()) {
23051 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23056 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23057 const X86Subtarget *Subtarget) {
23058 EVT VT = N->getValueType(0);
23059 if (!VT.isVector())
23062 SDValue N0 = N->getOperand(0);
23063 SDValue N1 = N->getOperand(1);
23064 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23067 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23068 // both SSE and AVX2 since there is no sign-extended shift right
23069 // operation on a vector with 64-bit elements.
23070 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23071 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23072 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23073 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23074 SDValue N00 = N0.getOperand(0);
23076 // EXTLOAD has a better solution on AVX2,
23077 // it may be replaced with X86ISD::VSEXT node.
23078 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23079 if (!ISD::isNormalLoad(N00.getNode()))
23082 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23083 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23085 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23091 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23092 TargetLowering::DAGCombinerInfo &DCI,
23093 const X86Subtarget *Subtarget) {
23094 SDValue N0 = N->getOperand(0);
23095 EVT VT = N->getValueType(0);
23097 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23098 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23099 // This exposes the sext to the sdivrem lowering, so that it directly extends
23100 // from AH (which we otherwise need to do contortions to access).
23101 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23102 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23104 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23105 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23106 N0.getOperand(0), N0.getOperand(1));
23107 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23108 return R.getValue(1);
23111 if (!DCI.isBeforeLegalizeOps())
23114 if (!Subtarget->hasFp256())
23117 if (VT.isVector() && VT.getSizeInBits() == 256) {
23118 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23126 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23127 const X86Subtarget* Subtarget) {
23129 EVT VT = N->getValueType(0);
23131 // Let legalize expand this if it isn't a legal type yet.
23132 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23135 EVT ScalarVT = VT.getScalarType();
23136 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23137 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23140 SDValue A = N->getOperand(0);
23141 SDValue B = N->getOperand(1);
23142 SDValue C = N->getOperand(2);
23144 bool NegA = (A.getOpcode() == ISD::FNEG);
23145 bool NegB = (B.getOpcode() == ISD::FNEG);
23146 bool NegC = (C.getOpcode() == ISD::FNEG);
23148 // Negative multiplication when NegA xor NegB
23149 bool NegMul = (NegA != NegB);
23151 A = A.getOperand(0);
23153 B = B.getOperand(0);
23155 C = C.getOperand(0);
23159 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23161 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23163 return DAG.getNode(Opcode, dl, VT, A, B, C);
23166 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23167 TargetLowering::DAGCombinerInfo &DCI,
23168 const X86Subtarget *Subtarget) {
23169 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23170 // (and (i32 x86isd::setcc_carry), 1)
23171 // This eliminates the zext. This transformation is necessary because
23172 // ISD::SETCC is always legalized to i8.
23174 SDValue N0 = N->getOperand(0);
23175 EVT VT = N->getValueType(0);
23177 if (N0.getOpcode() == ISD::AND &&
23179 N0.getOperand(0).hasOneUse()) {
23180 SDValue N00 = N0.getOperand(0);
23181 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23182 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23183 if (!C || C->getZExtValue() != 1)
23185 return DAG.getNode(ISD::AND, dl, VT,
23186 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23187 N00.getOperand(0), N00.getOperand(1)),
23188 DAG.getConstant(1, VT));
23192 if (N0.getOpcode() == ISD::TRUNCATE &&
23194 N0.getOperand(0).hasOneUse()) {
23195 SDValue N00 = N0.getOperand(0);
23196 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23197 return DAG.getNode(ISD::AND, dl, VT,
23198 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23199 N00.getOperand(0), N00.getOperand(1)),
23200 DAG.getConstant(1, VT));
23203 if (VT.is256BitVector()) {
23204 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23209 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23210 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23211 // This exposes the zext to the udivrem lowering, so that it directly extends
23212 // from AH (which we otherwise need to do contortions to access).
23213 if (N0.getOpcode() == ISD::UDIVREM &&
23214 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23215 (VT == MVT::i32 || VT == MVT::i64)) {
23216 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23217 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23218 N0.getOperand(0), N0.getOperand(1));
23219 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23220 return R.getValue(1);
23226 // Optimize x == -y --> x+y == 0
23227 // x != -y --> x+y != 0
23228 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23229 const X86Subtarget* Subtarget) {
23230 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23231 SDValue LHS = N->getOperand(0);
23232 SDValue RHS = N->getOperand(1);
23233 EVT VT = N->getValueType(0);
23236 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23238 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23239 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23240 LHS.getOperand(1));
23241 return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23242 DAG.getConstant(0, addV.getValueType()), CC);
23244 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23245 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23246 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23247 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23248 RHS.getOperand(1));
23249 return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23250 DAG.getConstant(0, addV.getValueType()), CC);
23253 if (VT.getScalarType() == MVT::i1 &&
23254 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23256 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23257 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23258 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23260 if (!IsSEXT0 || !IsVZero1) {
23261 // Swap the operands and update the condition code.
23262 std::swap(LHS, RHS);
23263 CC = ISD::getSetCCSwappedOperands(CC);
23265 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23266 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23267 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23270 if (IsSEXT0 && IsVZero1) {
23271 assert(VT == LHS.getOperand(0).getValueType() &&
23272 "Uexpected operand type");
23273 if (CC == ISD::SETGT)
23274 return DAG.getConstant(0, VT);
23275 if (CC == ISD::SETLE)
23276 return DAG.getConstant(1, VT);
23277 if (CC == ISD::SETEQ || CC == ISD::SETGE)
23278 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23280 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23281 "Unexpected condition code!");
23282 return LHS.getOperand(0);
23289 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23290 SelectionDAG &DAG) {
23292 MVT VT = Load->getSimpleValueType(0);
23293 MVT EVT = VT.getVectorElementType();
23294 SDValue Addr = Load->getOperand(1);
23295 SDValue NewAddr = DAG.getNode(
23296 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23297 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23300 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23301 DAG.getMachineFunction().getMachineMemOperand(
23302 Load->getMemOperand(), 0, EVT.getStoreSize()));
23306 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23307 const X86Subtarget *Subtarget) {
23309 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23310 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23311 "X86insertps is only defined for v4x32");
23313 SDValue Ld = N->getOperand(1);
23314 if (MayFoldLoad(Ld)) {
23315 // Extract the countS bits from the immediate so we can get the proper
23316 // address when narrowing the vector load to a specific element.
23317 // When the second source op is a memory address, insertps doesn't use
23318 // countS and just gets an f32 from that address.
23319 unsigned DestIndex =
23320 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23322 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23324 // Create this as a scalar to vector to match the instruction pattern.
23325 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23326 // countS bits are ignored when loading from memory on insertps, which
23327 // means we don't need to explicitly set them to 0.
23328 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23329 LoadScalarToVector, N->getOperand(2));
23334 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23335 SDValue V0 = N->getOperand(0);
23336 SDValue V1 = N->getOperand(1);
23338 EVT VT = N->getValueType(0);
23340 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23341 // operands and changing the mask to 1. This saves us a bunch of
23342 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23343 // x86InstrInfo knows how to commute this back after instruction selection
23344 // if it would help register allocation.
23346 // TODO: If optimizing for size or a processor that doesn't suffer from
23347 // partial register update stalls, this should be transformed into a MOVSD
23348 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23350 if (VT == MVT::v2f64)
23351 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23352 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23353 SDValue NewMask = DAG.getConstant(1, MVT::i8);
23354 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23360 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23361 // as "sbb reg,reg", since it can be extended without zext and produces
23362 // an all-ones bit which is more useful than 0/1 in some cases.
23363 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23366 return DAG.getNode(ISD::AND, DL, VT,
23367 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23368 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23369 DAG.getConstant(1, VT));
23370 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23371 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23372 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23373 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23376 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23377 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23378 TargetLowering::DAGCombinerInfo &DCI,
23379 const X86Subtarget *Subtarget) {
23381 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23382 SDValue EFLAGS = N->getOperand(1);
23384 if (CC == X86::COND_A) {
23385 // Try to convert COND_A into COND_B in an attempt to facilitate
23386 // materializing "setb reg".
23388 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23389 // cannot take an immediate as its first operand.
23391 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23392 EFLAGS.getValueType().isInteger() &&
23393 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23394 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23395 EFLAGS.getNode()->getVTList(),
23396 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23397 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23398 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23402 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23403 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23405 if (CC == X86::COND_B)
23406 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23410 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23411 if (Flags.getNode()) {
23412 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23413 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23419 // Optimize branch condition evaluation.
23421 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23422 TargetLowering::DAGCombinerInfo &DCI,
23423 const X86Subtarget *Subtarget) {
23425 SDValue Chain = N->getOperand(0);
23426 SDValue Dest = N->getOperand(1);
23427 SDValue EFLAGS = N->getOperand(3);
23428 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23432 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23433 if (Flags.getNode()) {
23434 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23435 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23442 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23443 SelectionDAG &DAG) {
23444 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23445 // optimize away operation when it's from a constant.
23447 // The general transformation is:
23448 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23449 // AND(VECTOR_CMP(x,y), constant2)
23450 // constant2 = UNARYOP(constant)
23452 // Early exit if this isn't a vector operation, the operand of the
23453 // unary operation isn't a bitwise AND, or if the sizes of the operations
23454 // aren't the same.
23455 EVT VT = N->getValueType(0);
23456 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23457 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23458 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23461 // Now check that the other operand of the AND is a constant. We could
23462 // make the transformation for non-constant splats as well, but it's unclear
23463 // that would be a benefit as it would not eliminate any operations, just
23464 // perform one more step in scalar code before moving to the vector unit.
23465 if (BuildVectorSDNode *BV =
23466 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23467 // Bail out if the vector isn't a constant.
23468 if (!BV->isConstant())
23471 // Everything checks out. Build up the new and improved node.
23473 EVT IntVT = BV->getValueType(0);
23474 // Create a new constant of the appropriate type for the transformed
23476 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23477 // The AND node needs bitcasts to/from an integer vector type around it.
23478 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23479 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23480 N->getOperand(0)->getOperand(0), MaskConst);
23481 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23488 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23489 const X86Subtarget *Subtarget) {
23490 // First try to optimize away the conversion entirely when it's
23491 // conditionally from a constant. Vectors only.
23492 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23493 if (Res != SDValue())
23496 // Now move on to more general possibilities.
23497 SDValue Op0 = N->getOperand(0);
23498 EVT InVT = Op0->getValueType(0);
23500 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23501 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23503 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23504 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23505 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23508 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23509 // a 32-bit target where SSE doesn't support i64->FP operations.
23510 if (Op0.getOpcode() == ISD::LOAD) {
23511 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23512 EVT VT = Ld->getValueType(0);
23513 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23514 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23515 !Subtarget->is64Bit() && VT == MVT::i64) {
23516 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23517 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23518 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23525 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23526 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23527 X86TargetLowering::DAGCombinerInfo &DCI) {
23528 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23529 // the result is either zero or one (depending on the input carry bit).
23530 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23531 if (X86::isZeroNode(N->getOperand(0)) &&
23532 X86::isZeroNode(N->getOperand(1)) &&
23533 // We don't have a good way to replace an EFLAGS use, so only do this when
23535 SDValue(N, 1).use_empty()) {
23537 EVT VT = N->getValueType(0);
23538 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23539 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23540 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23541 DAG.getConstant(X86::COND_B,MVT::i8),
23543 DAG.getConstant(1, VT));
23544 return DCI.CombineTo(N, Res1, CarryOut);
23550 // fold (add Y, (sete X, 0)) -> adc 0, Y
23551 // (add Y, (setne X, 0)) -> sbb -1, Y
23552 // (sub (sete X, 0), Y) -> sbb 0, Y
23553 // (sub (setne X, 0), Y) -> adc -1, Y
23554 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23557 // Look through ZExts.
23558 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23559 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23562 SDValue SetCC = Ext.getOperand(0);
23563 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23566 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23567 if (CC != X86::COND_E && CC != X86::COND_NE)
23570 SDValue Cmp = SetCC.getOperand(1);
23571 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23572 !X86::isZeroNode(Cmp.getOperand(1)) ||
23573 !Cmp.getOperand(0).getValueType().isInteger())
23576 SDValue CmpOp0 = Cmp.getOperand(0);
23577 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23578 DAG.getConstant(1, CmpOp0.getValueType()));
23580 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23581 if (CC == X86::COND_NE)
23582 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23583 DL, OtherVal.getValueType(), OtherVal,
23584 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23585 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23586 DL, OtherVal.getValueType(), OtherVal,
23587 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23590 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23591 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23592 const X86Subtarget *Subtarget) {
23593 EVT VT = N->getValueType(0);
23594 SDValue Op0 = N->getOperand(0);
23595 SDValue Op1 = N->getOperand(1);
23597 // Try to synthesize horizontal adds from adds of shuffles.
23598 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23599 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23600 isHorizontalBinOp(Op0, Op1, true))
23601 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23603 return OptimizeConditionalInDecrement(N, DAG);
23606 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23607 const X86Subtarget *Subtarget) {
23608 SDValue Op0 = N->getOperand(0);
23609 SDValue Op1 = N->getOperand(1);
23611 // X86 can't encode an immediate LHS of a sub. See if we can push the
23612 // negation into a preceding instruction.
23613 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23614 // If the RHS of the sub is a XOR with one use and a constant, invert the
23615 // immediate. Then add one to the LHS of the sub so we can turn
23616 // X-Y -> X+~Y+1, saving one register.
23617 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23618 isa<ConstantSDNode>(Op1.getOperand(1))) {
23619 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23620 EVT VT = Op0.getValueType();
23621 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23623 DAG.getConstant(~XorC, VT));
23624 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23625 DAG.getConstant(C->getAPIntValue()+1, VT));
23629 // Try to synthesize horizontal adds from adds of shuffles.
23630 EVT VT = N->getValueType(0);
23631 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23632 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23633 isHorizontalBinOp(Op0, Op1, true))
23634 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23636 return OptimizeConditionalInDecrement(N, DAG);
23639 /// performVZEXTCombine - Performs build vector combines
23640 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23641 TargetLowering::DAGCombinerInfo &DCI,
23642 const X86Subtarget *Subtarget) {
23644 MVT VT = N->getSimpleValueType(0);
23645 SDValue Op = N->getOperand(0);
23646 MVT OpVT = Op.getSimpleValueType();
23647 MVT OpEltVT = OpVT.getVectorElementType();
23648 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23650 // (vzext (bitcast (vzext (x)) -> (vzext x)
23652 while (V.getOpcode() == ISD::BITCAST)
23653 V = V.getOperand(0);
23655 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23656 MVT InnerVT = V.getSimpleValueType();
23657 MVT InnerEltVT = InnerVT.getVectorElementType();
23659 // If the element sizes match exactly, we can just do one larger vzext. This
23660 // is always an exact type match as vzext operates on integer types.
23661 if (OpEltVT == InnerEltVT) {
23662 assert(OpVT == InnerVT && "Types must match for vzext!");
23663 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23666 // The only other way we can combine them is if only a single element of the
23667 // inner vzext is used in the input to the outer vzext.
23668 if (InnerEltVT.getSizeInBits() < InputBits)
23671 // In this case, the inner vzext is completely dead because we're going to
23672 // only look at bits inside of the low element. Just do the outer vzext on
23673 // a bitcast of the input to the inner.
23674 return DAG.getNode(X86ISD::VZEXT, DL, VT,
23675 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23678 // Check if we can bypass extracting and re-inserting an element of an input
23679 // vector. Essentialy:
23680 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23681 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23682 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23683 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23684 SDValue ExtractedV = V.getOperand(0);
23685 SDValue OrigV = ExtractedV.getOperand(0);
23686 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23687 if (ExtractIdx->getZExtValue() == 0) {
23688 MVT OrigVT = OrigV.getSimpleValueType();
23689 // Extract a subvector if necessary...
23690 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23691 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23692 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23693 OrigVT.getVectorNumElements() / Ratio);
23694 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23695 DAG.getIntPtrConstant(0));
23697 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23698 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23705 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23706 DAGCombinerInfo &DCI) const {
23707 SelectionDAG &DAG = DCI.DAG;
23708 switch (N->getOpcode()) {
23710 case ISD::EXTRACT_VECTOR_ELT:
23711 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23714 case X86ISD::SHRUNKBLEND:
23715 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23716 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
23717 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23718 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23719 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23720 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23721 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23724 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23725 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23726 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23727 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23728 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23729 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23730 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23731 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
23732 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23733 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23734 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23736 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23738 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23739 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23740 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23741 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23742 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23743 case ISD::ANY_EXTEND:
23744 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23745 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23746 case ISD::SIGN_EXTEND_INREG:
23747 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23748 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23749 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23750 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23751 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23752 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23753 case X86ISD::SHUFP: // Handle all target specific shuffles
23754 case X86ISD::PALIGNR:
23755 case X86ISD::UNPCKH:
23756 case X86ISD::UNPCKL:
23757 case X86ISD::MOVHLPS:
23758 case X86ISD::MOVLHPS:
23759 case X86ISD::PSHUFB:
23760 case X86ISD::PSHUFD:
23761 case X86ISD::PSHUFHW:
23762 case X86ISD::PSHUFLW:
23763 case X86ISD::MOVSS:
23764 case X86ISD::MOVSD:
23765 case X86ISD::VPERMILPI:
23766 case X86ISD::VPERM2X128:
23767 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23768 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23769 case ISD::INTRINSIC_WO_CHAIN:
23770 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23771 case X86ISD::INSERTPS: {
23772 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23773 return PerformINSERTPSCombine(N, DAG, Subtarget);
23776 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
23777 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23783 /// isTypeDesirableForOp - Return true if the target has native support for
23784 /// the specified value type and it is 'desirable' to use the type for the
23785 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23786 /// instruction encodings are longer and some i16 instructions are slow.
23787 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23788 if (!isTypeLegal(VT))
23790 if (VT != MVT::i16)
23797 case ISD::SIGN_EXTEND:
23798 case ISD::ZERO_EXTEND:
23799 case ISD::ANY_EXTEND:
23812 /// IsDesirableToPromoteOp - This method query the target whether it is
23813 /// beneficial for dag combiner to promote the specified node. If true, it
23814 /// should return the desired promotion type by reference.
23815 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23816 EVT VT = Op.getValueType();
23817 if (VT != MVT::i16)
23820 bool Promote = false;
23821 bool Commute = false;
23822 switch (Op.getOpcode()) {
23825 LoadSDNode *LD = cast<LoadSDNode>(Op);
23826 // If the non-extending load has a single use and it's not live out, then it
23827 // might be folded.
23828 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23829 Op.hasOneUse()*/) {
23830 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23831 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23832 // The only case where we'd want to promote LOAD (rather then it being
23833 // promoted as an operand is when it's only use is liveout.
23834 if (UI->getOpcode() != ISD::CopyToReg)
23841 case ISD::SIGN_EXTEND:
23842 case ISD::ZERO_EXTEND:
23843 case ISD::ANY_EXTEND:
23848 SDValue N0 = Op.getOperand(0);
23849 // Look out for (store (shl (load), x)).
23850 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23863 SDValue N0 = Op.getOperand(0);
23864 SDValue N1 = Op.getOperand(1);
23865 if (!Commute && MayFoldLoad(N1))
23867 // Avoid disabling potential load folding opportunities.
23868 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23870 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23880 //===----------------------------------------------------------------------===//
23881 // X86 Inline Assembly Support
23882 //===----------------------------------------------------------------------===//
23884 // Helper to match a string separated by whitespace.
23885 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23886 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23888 for (StringRef Piece : Pieces) {
23889 if (!S.startswith(Piece)) // Check if the piece matches.
23892 S = S.substr(Piece.size());
23893 StringRef::size_type Pos = S.find_first_not_of(" \t");
23894 if (Pos == 0) // We matched a prefix.
23903 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23905 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23906 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23907 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23908 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23910 if (AsmPieces.size() == 3)
23912 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23919 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23920 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23922 std::string AsmStr = IA->getAsmString();
23924 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23925 if (!Ty || Ty->getBitWidth() % 16 != 0)
23928 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23929 SmallVector<StringRef, 4> AsmPieces;
23930 SplitString(AsmStr, AsmPieces, ";\n");
23932 switch (AsmPieces.size()) {
23933 default: return false;
23935 // FIXME: this should verify that we are targeting a 486 or better. If not,
23936 // we will turn this bswap into something that will be lowered to logical
23937 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23938 // lower so don't worry about this.
23940 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23941 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23942 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23943 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23944 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23945 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23946 // No need to check constraints, nothing other than the equivalent of
23947 // "=r,0" would be valid here.
23948 return IntrinsicLowering::LowerToByteSwap(CI);
23951 // rorw $$8, ${0:w} --> llvm.bswap.i16
23952 if (CI->getType()->isIntegerTy(16) &&
23953 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23954 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23955 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23957 const std::string &ConstraintsStr = IA->getConstraintString();
23958 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23959 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23960 if (clobbersFlagRegisters(AsmPieces))
23961 return IntrinsicLowering::LowerToByteSwap(CI);
23965 if (CI->getType()->isIntegerTy(32) &&
23966 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23967 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23968 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23969 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23971 const std::string &ConstraintsStr = IA->getConstraintString();
23972 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23973 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23974 if (clobbersFlagRegisters(AsmPieces))
23975 return IntrinsicLowering::LowerToByteSwap(CI);
23978 if (CI->getType()->isIntegerTy(64)) {
23979 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23980 if (Constraints.size() >= 2 &&
23981 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23982 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23983 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23984 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23985 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23986 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23987 return IntrinsicLowering::LowerToByteSwap(CI);
23995 /// getConstraintType - Given a constraint letter, return the type of
23996 /// constraint it is for this target.
23997 X86TargetLowering::ConstraintType
23998 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23999 if (Constraint.size() == 1) {
24000 switch (Constraint[0]) {
24011 return C_RegisterClass;
24035 return TargetLowering::getConstraintType(Constraint);
24038 /// Examine constraint type and operand type and determine a weight value.
24039 /// This object must already have been set up with the operand type
24040 /// and the current alternative constraint selected.
24041 TargetLowering::ConstraintWeight
24042 X86TargetLowering::getSingleConstraintMatchWeight(
24043 AsmOperandInfo &info, const char *constraint) const {
24044 ConstraintWeight weight = CW_Invalid;
24045 Value *CallOperandVal = info.CallOperandVal;
24046 // If we don't have a value, we can't do a match,
24047 // but allow it at the lowest weight.
24048 if (!CallOperandVal)
24050 Type *type = CallOperandVal->getType();
24051 // Look at the constraint type.
24052 switch (*constraint) {
24054 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24065 if (CallOperandVal->getType()->isIntegerTy())
24066 weight = CW_SpecificReg;
24071 if (type->isFloatingPointTy())
24072 weight = CW_SpecificReg;
24075 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24076 weight = CW_SpecificReg;
24080 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24081 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24082 weight = CW_Register;
24085 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24086 if (C->getZExtValue() <= 31)
24087 weight = CW_Constant;
24091 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24092 if (C->getZExtValue() <= 63)
24093 weight = CW_Constant;
24097 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24098 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24099 weight = CW_Constant;
24103 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24104 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24105 weight = CW_Constant;
24109 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24110 if (C->getZExtValue() <= 3)
24111 weight = CW_Constant;
24115 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24116 if (C->getZExtValue() <= 0xff)
24117 weight = CW_Constant;
24122 if (dyn_cast<ConstantFP>(CallOperandVal)) {
24123 weight = CW_Constant;
24127 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24128 if ((C->getSExtValue() >= -0x80000000LL) &&
24129 (C->getSExtValue() <= 0x7fffffffLL))
24130 weight = CW_Constant;
24134 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24135 if (C->getZExtValue() <= 0xffffffff)
24136 weight = CW_Constant;
24143 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24144 /// with another that has more specific requirements based on the type of the
24145 /// corresponding operand.
24146 const char *X86TargetLowering::
24147 LowerXConstraint(EVT ConstraintVT) const {
24148 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24149 // 'f' like normal targets.
24150 if (ConstraintVT.isFloatingPoint()) {
24151 if (Subtarget->hasSSE2())
24153 if (Subtarget->hasSSE1())
24157 return TargetLowering::LowerXConstraint(ConstraintVT);
24160 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24161 /// vector. If it is invalid, don't add anything to Ops.
24162 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24163 std::string &Constraint,
24164 std::vector<SDValue>&Ops,
24165 SelectionDAG &DAG) const {
24168 // Only support length 1 constraints for now.
24169 if (Constraint.length() > 1) return;
24171 char ConstraintLetter = Constraint[0];
24172 switch (ConstraintLetter) {
24175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24176 if (C->getZExtValue() <= 31) {
24177 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24184 if (C->getZExtValue() <= 63) {
24185 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24192 if (isInt<8>(C->getSExtValue())) {
24193 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24199 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24200 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24201 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24202 Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24208 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24209 if (C->getZExtValue() <= 3) {
24210 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24216 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24217 if (C->getZExtValue() <= 255) {
24218 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24224 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24225 if (C->getZExtValue() <= 127) {
24226 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24232 // 32-bit signed value
24233 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24234 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24235 C->getSExtValue())) {
24236 // Widen to 64 bits here to get it sign extended.
24237 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24240 // FIXME gcc accepts some relocatable values here too, but only in certain
24241 // memory models; it's complicated.
24246 // 32-bit unsigned value
24247 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24248 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24249 C->getZExtValue())) {
24250 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24254 // FIXME gcc accepts some relocatable values here too, but only in certain
24255 // memory models; it's complicated.
24259 // Literal immediates are always ok.
24260 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24261 // Widen to 64 bits here to get it sign extended.
24262 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24266 // In any sort of PIC mode addresses need to be computed at runtime by
24267 // adding in a register or some sort of table lookup. These can't
24268 // be used as immediates.
24269 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24272 // If we are in non-pic codegen mode, we allow the address of a global (with
24273 // an optional displacement) to be used with 'i'.
24274 GlobalAddressSDNode *GA = nullptr;
24275 int64_t Offset = 0;
24277 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24279 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24280 Offset += GA->getOffset();
24282 } else if (Op.getOpcode() == ISD::ADD) {
24283 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24284 Offset += C->getZExtValue();
24285 Op = Op.getOperand(0);
24288 } else if (Op.getOpcode() == ISD::SUB) {
24289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24290 Offset += -C->getZExtValue();
24291 Op = Op.getOperand(0);
24296 // Otherwise, this isn't something we can handle, reject it.
24300 const GlobalValue *GV = GA->getGlobal();
24301 // If we require an extra load to get this address, as in PIC mode, we
24302 // can't accept it.
24303 if (isGlobalStubReference(
24304 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24307 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24308 GA->getValueType(0), Offset);
24313 if (Result.getNode()) {
24314 Ops.push_back(Result);
24317 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24320 std::pair<unsigned, const TargetRegisterClass *>
24321 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24322 const std::string &Constraint,
24324 // First, see if this is a constraint that directly corresponds to an LLVM
24326 if (Constraint.size() == 1) {
24327 // GCC Constraint Letters
24328 switch (Constraint[0]) {
24330 // TODO: Slight differences here in allocation order and leaving
24331 // RIP in the class. Do they matter any more here than they do
24332 // in the normal allocation?
24333 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24334 if (Subtarget->is64Bit()) {
24335 if (VT == MVT::i32 || VT == MVT::f32)
24336 return std::make_pair(0U, &X86::GR32RegClass);
24337 if (VT == MVT::i16)
24338 return std::make_pair(0U, &X86::GR16RegClass);
24339 if (VT == MVT::i8 || VT == MVT::i1)
24340 return std::make_pair(0U, &X86::GR8RegClass);
24341 if (VT == MVT::i64 || VT == MVT::f64)
24342 return std::make_pair(0U, &X86::GR64RegClass);
24345 // 32-bit fallthrough
24346 case 'Q': // Q_REGS
24347 if (VT == MVT::i32 || VT == MVT::f32)
24348 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24349 if (VT == MVT::i16)
24350 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24351 if (VT == MVT::i8 || VT == MVT::i1)
24352 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24353 if (VT == MVT::i64)
24354 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24356 case 'r': // GENERAL_REGS
24357 case 'l': // INDEX_REGS
24358 if (VT == MVT::i8 || VT == MVT::i1)
24359 return std::make_pair(0U, &X86::GR8RegClass);
24360 if (VT == MVT::i16)
24361 return std::make_pair(0U, &X86::GR16RegClass);
24362 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24363 return std::make_pair(0U, &X86::GR32RegClass);
24364 return std::make_pair(0U, &X86::GR64RegClass);
24365 case 'R': // LEGACY_REGS
24366 if (VT == MVT::i8 || VT == MVT::i1)
24367 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24368 if (VT == MVT::i16)
24369 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24370 if (VT == MVT::i32 || !Subtarget->is64Bit())
24371 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24372 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24373 case 'f': // FP Stack registers.
24374 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24375 // value to the correct fpstack register class.
24376 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24377 return std::make_pair(0U, &X86::RFP32RegClass);
24378 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24379 return std::make_pair(0U, &X86::RFP64RegClass);
24380 return std::make_pair(0U, &X86::RFP80RegClass);
24381 case 'y': // MMX_REGS if MMX allowed.
24382 if (!Subtarget->hasMMX()) break;
24383 return std::make_pair(0U, &X86::VR64RegClass);
24384 case 'Y': // SSE_REGS if SSE2 allowed
24385 if (!Subtarget->hasSSE2()) break;
24387 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24388 if (!Subtarget->hasSSE1()) break;
24390 switch (VT.SimpleTy) {
24392 // Scalar SSE types.
24395 return std::make_pair(0U, &X86::FR32RegClass);
24398 return std::make_pair(0U, &X86::FR64RegClass);
24406 return std::make_pair(0U, &X86::VR128RegClass);
24414 return std::make_pair(0U, &X86::VR256RegClass);
24419 return std::make_pair(0U, &X86::VR512RegClass);
24425 // Use the default implementation in TargetLowering to convert the register
24426 // constraint into a member of a register class.
24427 std::pair<unsigned, const TargetRegisterClass*> Res;
24428 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24430 // Not found as a standard register?
24432 // Map st(0) -> st(7) -> ST0
24433 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24434 tolower(Constraint[1]) == 's' &&
24435 tolower(Constraint[2]) == 't' &&
24436 Constraint[3] == '(' &&
24437 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24438 Constraint[5] == ')' &&
24439 Constraint[6] == '}') {
24441 Res.first = X86::FP0+Constraint[4]-'0';
24442 Res.second = &X86::RFP80RegClass;
24446 // GCC allows "st(0)" to be called just plain "st".
24447 if (StringRef("{st}").equals_lower(Constraint)) {
24448 Res.first = X86::FP0;
24449 Res.second = &X86::RFP80RegClass;
24454 if (StringRef("{flags}").equals_lower(Constraint)) {
24455 Res.first = X86::EFLAGS;
24456 Res.second = &X86::CCRRegClass;
24460 // 'A' means EAX + EDX.
24461 if (Constraint == "A") {
24462 Res.first = X86::EAX;
24463 Res.second = &X86::GR32_ADRegClass;
24469 // Otherwise, check to see if this is a register class of the wrong value
24470 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24471 // turn into {ax},{dx}.
24472 if (Res.second->hasType(VT))
24473 return Res; // Correct type already, nothing to do.
24475 // All of the single-register GCC register classes map their values onto
24476 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24477 // really want an 8-bit or 32-bit register, map to the appropriate register
24478 // class and return the appropriate register.
24479 if (Res.second == &X86::GR16RegClass) {
24480 if (VT == MVT::i8 || VT == MVT::i1) {
24481 unsigned DestReg = 0;
24482 switch (Res.first) {
24484 case X86::AX: DestReg = X86::AL; break;
24485 case X86::DX: DestReg = X86::DL; break;
24486 case X86::CX: DestReg = X86::CL; break;
24487 case X86::BX: DestReg = X86::BL; break;
24490 Res.first = DestReg;
24491 Res.second = &X86::GR8RegClass;
24493 } else if (VT == MVT::i32 || VT == MVT::f32) {
24494 unsigned DestReg = 0;
24495 switch (Res.first) {
24497 case X86::AX: DestReg = X86::EAX; break;
24498 case X86::DX: DestReg = X86::EDX; break;
24499 case X86::CX: DestReg = X86::ECX; break;
24500 case X86::BX: DestReg = X86::EBX; break;
24501 case X86::SI: DestReg = X86::ESI; break;
24502 case X86::DI: DestReg = X86::EDI; break;
24503 case X86::BP: DestReg = X86::EBP; break;
24504 case X86::SP: DestReg = X86::ESP; break;
24507 Res.first = DestReg;
24508 Res.second = &X86::GR32RegClass;
24510 } else if (VT == MVT::i64 || VT == MVT::f64) {
24511 unsigned DestReg = 0;
24512 switch (Res.first) {
24514 case X86::AX: DestReg = X86::RAX; break;
24515 case X86::DX: DestReg = X86::RDX; break;
24516 case X86::CX: DestReg = X86::RCX; break;
24517 case X86::BX: DestReg = X86::RBX; break;
24518 case X86::SI: DestReg = X86::RSI; break;
24519 case X86::DI: DestReg = X86::RDI; break;
24520 case X86::BP: DestReg = X86::RBP; break;
24521 case X86::SP: DestReg = X86::RSP; break;
24524 Res.first = DestReg;
24525 Res.second = &X86::GR64RegClass;
24528 } else if (Res.second == &X86::FR32RegClass ||
24529 Res.second == &X86::FR64RegClass ||
24530 Res.second == &X86::VR128RegClass ||
24531 Res.second == &X86::VR256RegClass ||
24532 Res.second == &X86::FR32XRegClass ||
24533 Res.second == &X86::FR64XRegClass ||
24534 Res.second == &X86::VR128XRegClass ||
24535 Res.second == &X86::VR256XRegClass ||
24536 Res.second == &X86::VR512RegClass) {
24537 // Handle references to XMM physical registers that got mapped into the
24538 // wrong class. This can happen with constraints like {xmm0} where the
24539 // target independent register mapper will just pick the first match it can
24540 // find, ignoring the required type.
24542 if (VT == MVT::f32 || VT == MVT::i32)
24543 Res.second = &X86::FR32RegClass;
24544 else if (VT == MVT::f64 || VT == MVT::i64)
24545 Res.second = &X86::FR64RegClass;
24546 else if (X86::VR128RegClass.hasType(VT))
24547 Res.second = &X86::VR128RegClass;
24548 else if (X86::VR256RegClass.hasType(VT))
24549 Res.second = &X86::VR256RegClass;
24550 else if (X86::VR512RegClass.hasType(VT))
24551 Res.second = &X86::VR512RegClass;
24557 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24559 // Scaling factors are not free at all.
24560 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24561 // will take 2 allocations in the out of order engine instead of 1
24562 // for plain addressing mode, i.e. inst (reg1).
24564 // vaddps (%rsi,%drx), %ymm0, %ymm1
24565 // Requires two allocations (one for the load, one for the computation)
24567 // vaddps (%rsi), %ymm0, %ymm1
24568 // Requires just 1 allocation, i.e., freeing allocations for other operations
24569 // and having less micro operations to execute.
24571 // For some X86 architectures, this is even worse because for instance for
24572 // stores, the complex addressing mode forces the instruction to use the
24573 // "load" ports instead of the dedicated "store" port.
24574 // E.g., on Haswell:
24575 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24576 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24577 if (isLegalAddressingMode(AM, Ty))
24578 // Scale represents reg2 * scale, thus account for 1
24579 // as soon as we use a second register.
24580 return AM.Scale != 0;
24584 bool X86TargetLowering::isTargetFTOL() const {
24585 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();