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/ADT/VariadicFunction.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71 "x86-recip-refinement-steps", cl::init(1),
72 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73 "result of the hardware reciprocal estimate instruction."),
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
80 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
81 SelectionDAG &DAG, SDLoc dl,
82 unsigned vectorWidth) {
83 assert((vectorWidth == 128 || vectorWidth == 256) &&
84 "Unsupported vector width");
85 EVT VT = Vec.getValueType();
86 EVT ElVT = VT.getVectorElementType();
87 unsigned Factor = VT.getSizeInBits()/vectorWidth;
88 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89 VT.getVectorNumElements()/Factor);
91 // Extract from UNDEF is UNDEF.
92 if (Vec.getOpcode() == ISD::UNDEF)
93 return DAG.getUNDEF(ResultVT);
95 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
96 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
98 // This is the index of the first element of the vectorWidth-bit chunk
100 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
103 // If the input is a buildvector just emit a smaller one.
104 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
105 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
106 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
109 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
110 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120 SelectionDAG &DAG, SDLoc dl) {
121 assert((Vec.getValueType().is256BitVector() ||
122 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128 SelectionDAG &DAG, SDLoc dl) {
129 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134 unsigned IdxVal, SelectionDAG &DAG,
135 SDLoc dl, unsigned vectorWidth) {
136 assert((vectorWidth == 128 || vectorWidth == 256) &&
137 "Unsupported vector width");
138 // Inserting UNDEF is Result
139 if (Vec.getOpcode() == ISD::UNDEF)
141 EVT VT = Vec.getValueType();
142 EVT ElVT = VT.getVectorElementType();
143 EVT ResultVT = Result.getValueType();
145 // Insert the relevant vectorWidth bits.
146 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
148 // This is the index of the first element of the vectorWidth-bit chunk
150 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
153 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
157 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference. Idx is an index in the 128 bits
161 /// we want. It need not be aligned to a 128-bit boundary. That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
164 SelectionDAG &DAG,SDLoc dl) {
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
170 SelectionDAG &DAG, SDLoc dl) {
171 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
172 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
175 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
176 /// instructions. This is used because creating CONCAT_VECTOR nodes of
177 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
178 /// large BUILD_VECTORS.
179 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
180 unsigned NumElems, SelectionDAG &DAG,
182 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
183 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
186 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
187 unsigned NumElems, SelectionDAG &DAG,
189 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
190 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
193 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
194 const X86Subtarget &STI)
195 : TargetLowering(TM), Subtarget(&STI) {
196 X86ScalarSSEf64 = Subtarget->hasSSE2();
197 X86ScalarSSEf32 = Subtarget->hasSSE1();
198 TD = getDataLayout();
200 // Set up the TargetLowering object.
201 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
203 // X86 is weird. It always uses i8 for shift amounts and setcc results.
204 setBooleanContents(ZeroOrOneBooleanContent);
205 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
206 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
208 // For 64-bit, since we have so many registers, use the ILP scheduler.
209 // For 32-bit, use the register pressure specific scheduling.
210 // For Atom, always use ILP scheduling.
211 if (Subtarget->isAtom())
212 setSchedulingPreference(Sched::ILP);
213 else if (Subtarget->is64Bit())
214 setSchedulingPreference(Sched::ILP);
216 setSchedulingPreference(Sched::RegPressure);
217 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
218 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
220 // Bypass expensive divides on Atom when compiling with O2.
221 if (TM.getOptLevel() >= CodeGenOpt::Default) {
222 if (Subtarget->hasSlowDivide32())
223 addBypassSlowDiv(32, 8);
224 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
225 addBypassSlowDiv(64, 16);
228 if (Subtarget->isTargetKnownWindowsMSVC()) {
229 // Setup Windows compiler runtime calls.
230 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
231 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
232 setLibcallName(RTLIB::SREM_I64, "_allrem");
233 setLibcallName(RTLIB::UREM_I64, "_aullrem");
234 setLibcallName(RTLIB::MUL_I64, "_allmul");
235 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
236 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
237 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
238 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
239 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
241 // The _ftol2 runtime function has an unusual calling conv, which
242 // is modeled by a special pseudo-instruction.
243 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
244 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
245 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
246 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
249 if (Subtarget->isTargetDarwin()) {
250 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
251 setUseUnderscoreSetJmp(false);
252 setUseUnderscoreLongJmp(false);
253 } else if (Subtarget->isTargetWindowsGNU()) {
254 // MS runtime is weird: it exports _setjmp, but longjmp!
255 setUseUnderscoreSetJmp(true);
256 setUseUnderscoreLongJmp(false);
258 setUseUnderscoreSetJmp(true);
259 setUseUnderscoreLongJmp(true);
262 // Set up the register classes.
263 addRegisterClass(MVT::i8, &X86::GR8RegClass);
264 addRegisterClass(MVT::i16, &X86::GR16RegClass);
265 addRegisterClass(MVT::i32, &X86::GR32RegClass);
266 if (Subtarget->is64Bit())
267 addRegisterClass(MVT::i64, &X86::GR64RegClass);
269 for (MVT VT : MVT::integer_valuetypes())
270 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
272 // We don't accept any truncstore of integer registers.
273 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
274 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
275 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
276 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
277 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
278 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
280 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
282 // SETOEQ and SETUNE require checking two conditions.
283 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
284 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
285 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
286 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
287 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
288 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
290 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
292 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
293 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
294 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
296 if (Subtarget->is64Bit()) {
297 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
298 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
299 } else if (!TM.Options.UseSoftFloat) {
300 // We have an algorithm for SSE2->double, and we turn this into a
301 // 64-bit FILD followed by conditional FADD for other targets.
302 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
303 // We have an algorithm for SSE2, and we turn this into a 64-bit
304 // FILD for other targets.
305 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
308 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
310 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
311 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
313 if (!TM.Options.UseSoftFloat) {
314 // SSE has no i16 to fp conversion, only i32
315 if (X86ScalarSSEf32) {
316 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
317 // f32 and f64 cases are Legal, f80 case is not
318 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
320 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
321 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
324 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
325 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
328 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
329 // are Legal, f80 is custom lowered.
330 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
331 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
333 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
335 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
336 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
338 if (X86ScalarSSEf32) {
339 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
340 // f32 and f64 cases are Legal, f80 case is not
341 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
343 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
344 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
347 // Handle FP_TO_UINT by promoting the destination to a larger signed
349 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
350 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
351 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
353 if (Subtarget->is64Bit()) {
354 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
355 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
356 } else if (!TM.Options.UseSoftFloat) {
357 // Since AVX is a superset of SSE3, only check for SSE here.
358 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
359 // Expand FP_TO_UINT into a select.
360 // FIXME: We would like to use a Custom expander here eventually to do
361 // the optimal thing for SSE vs. the default expansion in the legalizer.
362 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
364 // With SSE3 we can use fisttpll to convert to a signed i64; without
365 // SSE, we're stuck with a fistpll.
366 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
369 if (isTargetFTOL()) {
370 // Use the _ftol2 runtime function, which has a pseudo-instruction
371 // to handle its weird calling convention.
372 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
375 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
376 if (!X86ScalarSSEf64) {
377 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
378 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
379 if (Subtarget->is64Bit()) {
380 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
381 // Without SSE, i64->f64 goes through memory.
382 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
386 // Scalar integer divide and remainder are lowered to use operations that
387 // produce two results, to match the available instructions. This exposes
388 // the two-result form to trivial CSE, which is able to combine x/y and x%y
389 // into a single instruction.
391 // Scalar integer multiply-high is also lowered to use two-result
392 // operations, to match the available instructions. However, plain multiply
393 // (low) operations are left as Legal, as there are single-result
394 // instructions for this in x86. Using the two-result multiply instructions
395 // when both high and low results are needed must be arranged by dagcombine.
396 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
398 setOperationAction(ISD::MULHS, VT, Expand);
399 setOperationAction(ISD::MULHU, VT, Expand);
400 setOperationAction(ISD::SDIV, VT, Expand);
401 setOperationAction(ISD::UDIV, VT, Expand);
402 setOperationAction(ISD::SREM, VT, Expand);
403 setOperationAction(ISD::UREM, VT, Expand);
405 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
406 setOperationAction(ISD::ADDC, VT, Custom);
407 setOperationAction(ISD::ADDE, VT, Custom);
408 setOperationAction(ISD::SUBC, VT, Custom);
409 setOperationAction(ISD::SUBE, VT, Custom);
412 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
413 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
414 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
415 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
416 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
417 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
418 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
419 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
420 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
421 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
422 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
423 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
424 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
425 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
426 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
427 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
428 if (Subtarget->is64Bit())
429 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
430 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
431 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
432 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
433 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
434 setOperationAction(ISD::FREM , MVT::f32 , Expand);
435 setOperationAction(ISD::FREM , MVT::f64 , Expand);
436 setOperationAction(ISD::FREM , MVT::f80 , Expand);
437 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
439 // Promote the i8 variants and force them on up to i32 which has a shorter
441 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
442 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
443 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
444 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
445 if (Subtarget->hasBMI()) {
446 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
447 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
448 if (Subtarget->is64Bit())
449 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
451 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
452 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
453 if (Subtarget->is64Bit())
454 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
457 if (Subtarget->hasLZCNT()) {
458 // When promoting the i8 variants, force them to i32 for a shorter
460 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
461 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
462 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
463 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
464 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
465 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
466 if (Subtarget->is64Bit())
467 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
469 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
470 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
471 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
475 if (Subtarget->is64Bit()) {
476 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
477 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
481 // Special handling for half-precision floating point conversions.
482 // If we don't have F16C support, then lower half float conversions
483 // into library calls.
484 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
485 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
486 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
489 // There's never any support for operations beyond MVT::f32.
490 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
491 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
492 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
493 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
495 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
496 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
497 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
498 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
499 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
500 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
502 if (Subtarget->hasPOPCNT()) {
503 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
505 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
506 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
507 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
508 if (Subtarget->is64Bit())
509 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
512 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
514 if (!Subtarget->hasMOVBE())
515 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
517 // These should be promoted to a larger select which is supported.
518 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
519 // X86 wants to expand cmov itself.
520 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
521 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
522 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
524 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
525 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
527 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
528 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
530 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
531 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
532 if (Subtarget->is64Bit()) {
533 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
534 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
536 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
537 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
538 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
539 // support continuation, user-level threading, and etc.. As a result, no
540 // other SjLj exception interfaces are implemented and please don't build
541 // your own exception handling based on them.
542 // LLVM/Clang supports zero-cost DWARF exception handling.
543 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
544 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
547 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
548 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
549 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
550 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
551 if (Subtarget->is64Bit())
552 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
553 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
554 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
555 if (Subtarget->is64Bit()) {
556 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
557 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
558 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
559 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
560 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
562 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
563 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
564 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
565 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
566 if (Subtarget->is64Bit()) {
567 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
568 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
569 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
572 if (Subtarget->hasSSE1())
573 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
575 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
577 // Expand certain atomics
578 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
580 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
581 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
582 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
585 if (Subtarget->hasCmpxchg16b()) {
586 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
589 // FIXME - use subtarget debug flags
590 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
591 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
592 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
595 if (Subtarget->is64Bit()) {
596 setExceptionPointerRegister(X86::RAX);
597 setExceptionSelectorRegister(X86::RDX);
599 setExceptionPointerRegister(X86::EAX);
600 setExceptionSelectorRegister(X86::EDX);
602 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
603 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
605 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
606 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
608 setOperationAction(ISD::TRAP, MVT::Other, Legal);
609 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
611 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
612 setOperationAction(ISD::VASTART , MVT::Other, Custom);
613 setOperationAction(ISD::VAEND , MVT::Other, Expand);
614 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
615 // TargetInfo::X86_64ABIBuiltinVaList
616 setOperationAction(ISD::VAARG , MVT::Other, Custom);
617 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
619 // TargetInfo::CharPtrBuiltinVaList
620 setOperationAction(ISD::VAARG , MVT::Other, Expand);
621 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
624 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
625 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
627 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
629 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
630 // f32 and f64 use SSE.
631 // Set up the FP register classes.
632 addRegisterClass(MVT::f32, &X86::FR32RegClass);
633 addRegisterClass(MVT::f64, &X86::FR64RegClass);
635 // Use ANDPD to simulate FABS.
636 setOperationAction(ISD::FABS , MVT::f64, Custom);
637 setOperationAction(ISD::FABS , MVT::f32, Custom);
639 // Use XORP to simulate FNEG.
640 setOperationAction(ISD::FNEG , MVT::f64, Custom);
641 setOperationAction(ISD::FNEG , MVT::f32, Custom);
643 // Use ANDPD and ORPD to simulate FCOPYSIGN.
644 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
645 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
647 // Lower this to FGETSIGNx86 plus an AND.
648 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
649 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
651 // We don't support sin/cos/fmod
652 setOperationAction(ISD::FSIN , MVT::f64, Expand);
653 setOperationAction(ISD::FCOS , MVT::f64, Expand);
654 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
655 setOperationAction(ISD::FSIN , MVT::f32, Expand);
656 setOperationAction(ISD::FCOS , MVT::f32, Expand);
657 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
659 // Expand FP immediates into loads from the stack, except for the special
661 addLegalFPImmediate(APFloat(+0.0)); // xorpd
662 addLegalFPImmediate(APFloat(+0.0f)); // xorps
663 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
664 // Use SSE for f32, x87 for f64.
665 // Set up the FP register classes.
666 addRegisterClass(MVT::f32, &X86::FR32RegClass);
667 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
669 // Use ANDPS to simulate FABS.
670 setOperationAction(ISD::FABS , MVT::f32, Custom);
672 // Use XORP to simulate FNEG.
673 setOperationAction(ISD::FNEG , MVT::f32, Custom);
675 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
677 // Use ANDPS and ORPS to simulate FCOPYSIGN.
678 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
679 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
681 // We don't support sin/cos/fmod
682 setOperationAction(ISD::FSIN , MVT::f32, Expand);
683 setOperationAction(ISD::FCOS , MVT::f32, Expand);
684 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
686 // Special cases we handle for FP constants.
687 addLegalFPImmediate(APFloat(+0.0f)); // xorps
688 addLegalFPImmediate(APFloat(+0.0)); // FLD0
689 addLegalFPImmediate(APFloat(+1.0)); // FLD1
690 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
691 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
693 if (!TM.Options.UnsafeFPMath) {
694 setOperationAction(ISD::FSIN , MVT::f64, Expand);
695 setOperationAction(ISD::FCOS , MVT::f64, Expand);
696 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
698 } else if (!TM.Options.UseSoftFloat) {
699 // f32 and f64 in x87.
700 // Set up the FP register classes.
701 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
702 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
704 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
705 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
706 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
707 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
709 if (!TM.Options.UnsafeFPMath) {
710 setOperationAction(ISD::FSIN , MVT::f64, Expand);
711 setOperationAction(ISD::FSIN , MVT::f32, Expand);
712 setOperationAction(ISD::FCOS , MVT::f64, Expand);
713 setOperationAction(ISD::FCOS , MVT::f32, Expand);
714 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
715 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
717 addLegalFPImmediate(APFloat(+0.0)); // FLD0
718 addLegalFPImmediate(APFloat(+1.0)); // FLD1
719 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
720 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
721 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
722 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
723 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
724 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
727 // We don't support FMA.
728 setOperationAction(ISD::FMA, MVT::f64, Expand);
729 setOperationAction(ISD::FMA, MVT::f32, Expand);
731 // Long double always uses X87.
732 if (!TM.Options.UseSoftFloat) {
733 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
734 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
735 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
737 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
738 addLegalFPImmediate(TmpFlt); // FLD0
740 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
743 APFloat TmpFlt2(+1.0);
744 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
746 addLegalFPImmediate(TmpFlt2); // FLD1
747 TmpFlt2.changeSign();
748 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
751 if (!TM.Options.UnsafeFPMath) {
752 setOperationAction(ISD::FSIN , MVT::f80, Expand);
753 setOperationAction(ISD::FCOS , MVT::f80, Expand);
754 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
757 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
758 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
759 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
760 setOperationAction(ISD::FRINT, MVT::f80, Expand);
761 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
762 setOperationAction(ISD::FMA, MVT::f80, Expand);
765 // Always use a library call for pow.
766 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
767 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
768 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
770 setOperationAction(ISD::FLOG, MVT::f80, Expand);
771 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
772 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
773 setOperationAction(ISD::FEXP, MVT::f80, Expand);
774 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
775 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
776 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
778 // First set operation action for all vector types to either promote
779 // (for widening) or expand (for scalarization). Then we will selectively
780 // turn on ones that can be effectively codegen'd.
781 for (MVT VT : MVT::vector_valuetypes()) {
782 setOperationAction(ISD::ADD , VT, Expand);
783 setOperationAction(ISD::SUB , VT, Expand);
784 setOperationAction(ISD::FADD, VT, Expand);
785 setOperationAction(ISD::FNEG, VT, Expand);
786 setOperationAction(ISD::FSUB, VT, Expand);
787 setOperationAction(ISD::MUL , VT, Expand);
788 setOperationAction(ISD::FMUL, VT, Expand);
789 setOperationAction(ISD::SDIV, VT, Expand);
790 setOperationAction(ISD::UDIV, VT, Expand);
791 setOperationAction(ISD::FDIV, VT, Expand);
792 setOperationAction(ISD::SREM, VT, Expand);
793 setOperationAction(ISD::UREM, VT, Expand);
794 setOperationAction(ISD::LOAD, VT, Expand);
795 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
796 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
797 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
798 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
799 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
800 setOperationAction(ISD::FABS, VT, Expand);
801 setOperationAction(ISD::FSIN, VT, Expand);
802 setOperationAction(ISD::FSINCOS, VT, Expand);
803 setOperationAction(ISD::FCOS, VT, Expand);
804 setOperationAction(ISD::FSINCOS, VT, Expand);
805 setOperationAction(ISD::FREM, VT, Expand);
806 setOperationAction(ISD::FMA, VT, Expand);
807 setOperationAction(ISD::FPOWI, VT, Expand);
808 setOperationAction(ISD::FSQRT, VT, Expand);
809 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
810 setOperationAction(ISD::FFLOOR, VT, Expand);
811 setOperationAction(ISD::FCEIL, VT, Expand);
812 setOperationAction(ISD::FTRUNC, VT, Expand);
813 setOperationAction(ISD::FRINT, VT, Expand);
814 setOperationAction(ISD::FNEARBYINT, VT, Expand);
815 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
816 setOperationAction(ISD::MULHS, VT, Expand);
817 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
818 setOperationAction(ISD::MULHU, VT, Expand);
819 setOperationAction(ISD::SDIVREM, VT, Expand);
820 setOperationAction(ISD::UDIVREM, VT, Expand);
821 setOperationAction(ISD::FPOW, VT, Expand);
822 setOperationAction(ISD::CTPOP, VT, Expand);
823 setOperationAction(ISD::CTTZ, VT, Expand);
824 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
825 setOperationAction(ISD::CTLZ, VT, Expand);
826 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
827 setOperationAction(ISD::SHL, VT, Expand);
828 setOperationAction(ISD::SRA, VT, Expand);
829 setOperationAction(ISD::SRL, VT, Expand);
830 setOperationAction(ISD::ROTL, VT, Expand);
831 setOperationAction(ISD::ROTR, VT, Expand);
832 setOperationAction(ISD::BSWAP, VT, Expand);
833 setOperationAction(ISD::SETCC, VT, Expand);
834 setOperationAction(ISD::FLOG, VT, Expand);
835 setOperationAction(ISD::FLOG2, VT, Expand);
836 setOperationAction(ISD::FLOG10, VT, Expand);
837 setOperationAction(ISD::FEXP, VT, Expand);
838 setOperationAction(ISD::FEXP2, VT, Expand);
839 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
840 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
841 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
842 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
843 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
844 setOperationAction(ISD::TRUNCATE, VT, Expand);
845 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
846 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
847 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
848 setOperationAction(ISD::VSELECT, VT, Expand);
849 setOperationAction(ISD::SELECT_CC, VT, Expand);
850 for (MVT InnerVT : MVT::vector_valuetypes()) {
851 setTruncStoreAction(InnerVT, VT, Expand);
853 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
854 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
856 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
857 // types, we have to deal with them whether we ask for Expansion or not.
858 // Setting Expand causes its own optimisation problems though, so leave
860 if (VT.getVectorElementType() == MVT::i1)
861 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
865 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
866 // with -msoft-float, disable use of MMX as well.
867 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
868 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
869 // No operations on x86mmx supported, everything uses intrinsics.
872 // MMX-sized vectors (other than x86mmx) are expected to be expanded
873 // into smaller operations.
874 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
875 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
876 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
877 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
878 setOperationAction(ISD::AND, MVT::v8i8, Expand);
879 setOperationAction(ISD::AND, MVT::v4i16, Expand);
880 setOperationAction(ISD::AND, MVT::v2i32, Expand);
881 setOperationAction(ISD::AND, MVT::v1i64, Expand);
882 setOperationAction(ISD::OR, MVT::v8i8, Expand);
883 setOperationAction(ISD::OR, MVT::v4i16, Expand);
884 setOperationAction(ISD::OR, MVT::v2i32, Expand);
885 setOperationAction(ISD::OR, MVT::v1i64, Expand);
886 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
887 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
888 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
889 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
890 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
891 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
892 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
895 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
896 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
897 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
898 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
899 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
900 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
901 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
902 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
904 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
905 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
907 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
908 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
909 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
910 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
911 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
912 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
913 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
914 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
915 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
917 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
919 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
920 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
923 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
924 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
926 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
927 // registers cannot be used even for integer operations.
928 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
929 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
930 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
931 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
933 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
934 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
935 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
936 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
937 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
938 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
939 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
940 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
941 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
942 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
943 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
944 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
945 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
946 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
947 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
948 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
949 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
950 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
951 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
953 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
954 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
956 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
957 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
958 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
959 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
961 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
967 // Only provide customized ctpop vector bit twiddling for vector types we
968 // know to perform better than using the popcnt instructions on each vector
969 // element. If popcnt isn't supported, always provide the custom version.
970 if (!Subtarget->hasPOPCNT()) {
971 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
972 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
975 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
976 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
977 MVT VT = (MVT::SimpleValueType)i;
978 // Do not attempt to custom lower non-power-of-2 vectors
979 if (!isPowerOf2_32(VT.getVectorNumElements()))
981 // Do not attempt to custom lower non-128-bit vectors
982 if (!VT.is128BitVector())
984 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
985 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
986 setOperationAction(ISD::VSELECT, VT, Custom);
987 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
990 // We support custom legalizing of sext and anyext loads for specific
991 // memory vector types which we can load as a scalar (or sequence of
992 // scalars) and extend in-register to a legal 128-bit vector type. For sext
993 // loads these must work with a single scalar load.
994 for (MVT VT : MVT::integer_vector_valuetypes()) {
995 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
996 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
997 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
998 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
999 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
1000 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
1001 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
1002 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
1003 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
1006 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1007 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1008 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1009 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1010 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1011 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1015 if (Subtarget->is64Bit()) {
1016 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1020 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1021 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1022 MVT VT = (MVT::SimpleValueType)i;
1024 // Do not attempt to promote non-128-bit vectors
1025 if (!VT.is128BitVector())
1028 setOperationAction(ISD::AND, VT, Promote);
1029 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1030 setOperationAction(ISD::OR, VT, Promote);
1031 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1032 setOperationAction(ISD::XOR, VT, Promote);
1033 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1034 setOperationAction(ISD::LOAD, VT, Promote);
1035 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1036 setOperationAction(ISD::SELECT, VT, Promote);
1037 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1040 // Custom lower v2i64 and v2f64 selects.
1041 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1042 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1043 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1044 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1046 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1047 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1049 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1050 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1051 // As there is no 64-bit GPR available, we need build a special custom
1052 // sequence to convert from v2i32 to v2f32.
1053 if (!Subtarget->is64Bit())
1054 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1056 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1057 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1059 for (MVT VT : MVT::fp_vector_valuetypes())
1060 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1062 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1063 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1064 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1067 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1068 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1069 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1070 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1071 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1072 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1073 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1074 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1075 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1076 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1077 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1079 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1080 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1081 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1082 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1083 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1084 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1085 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1086 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1087 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1088 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1090 // FIXME: Do we need to handle scalar-to-vector here?
1091 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1093 // We directly match byte blends in the backend as they match the VSELECT
1095 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1097 // SSE41 brings specific instructions for doing vector sign extend even in
1098 // cases where we don't have SRA.
1099 for (MVT VT : MVT::integer_vector_valuetypes()) {
1100 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1101 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1102 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1105 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1106 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1107 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1108 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1109 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1110 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1111 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1113 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1114 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1115 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1116 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1117 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1118 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1120 // i8 and i16 vectors are custom because the source register and source
1121 // source memory operand types are not the same width. f32 vectors are
1122 // custom since the immediate controlling the insert encodes additional
1124 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1125 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1126 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1127 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1129 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1130 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1131 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1132 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1134 // FIXME: these should be Legal, but that's only for the case where
1135 // the index is constant. For now custom expand to deal with that.
1136 if (Subtarget->is64Bit()) {
1137 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1138 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1142 if (Subtarget->hasSSE2()) {
1143 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1144 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1146 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1147 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1149 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1150 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1152 // In the customized shift lowering, the legal cases in AVX2 will be
1154 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1155 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1157 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1158 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1160 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1163 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1164 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1165 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1166 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1167 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1168 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1169 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1171 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1172 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1173 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1175 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1176 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1177 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1178 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1179 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1180 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1181 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1182 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1183 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1184 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1185 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1186 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1188 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1189 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1190 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1191 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1192 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1193 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1194 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1195 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1196 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1197 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1198 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1199 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1201 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1202 // even though v8i16 is a legal type.
1203 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1204 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1205 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1207 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1208 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1209 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1211 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1212 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1214 for (MVT VT : MVT::fp_vector_valuetypes())
1215 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1217 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1218 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1220 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1221 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1223 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1224 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1226 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1227 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1228 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1229 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1231 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1232 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1233 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1235 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1236 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1238 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1239 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1240 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1241 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1242 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1243 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1244 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1245 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1246 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1248 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1249 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1250 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1251 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1252 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1253 setOperationAction(ISD::FMA, MVT::f32, Legal);
1254 setOperationAction(ISD::FMA, MVT::f64, Legal);
1257 if (Subtarget->hasInt256()) {
1258 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1259 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1260 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1261 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1263 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1264 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1265 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1266 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1268 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1269 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1270 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1271 // Don't lower v32i8 because there is no 128-bit byte mul
1273 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1274 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1275 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1276 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1278 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1279 // when we have a 256bit-wide blend with immediate.
1280 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1282 // Only provide customized ctpop vector bit twiddling for vector types we
1283 // know to perform better than using the popcnt instructions on each
1284 // vector element. If popcnt isn't supported, always provide the custom
1286 if (!Subtarget->hasPOPCNT())
1287 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1289 // Custom CTPOP always performs better on natively supported v8i32
1290 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1292 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1293 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1294 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1295 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1296 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1297 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1298 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1300 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1301 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1302 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1303 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1304 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1305 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1307 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1308 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1309 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1310 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1312 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1313 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1314 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1315 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1317 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1318 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1319 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1320 // Don't lower v32i8 because there is no 128-bit byte mul
1323 // In the customized shift lowering, the legal cases in AVX2 will be
1325 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1326 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1328 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1329 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1331 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1333 // Custom lower several nodes for 256-bit types.
1334 for (MVT VT : MVT::vector_valuetypes()) {
1335 if (VT.getScalarSizeInBits() >= 32) {
1336 setOperationAction(ISD::MLOAD, VT, Legal);
1337 setOperationAction(ISD::MSTORE, VT, Legal);
1339 // Extract subvector is special because the value type
1340 // (result) is 128-bit but the source is 256-bit wide.
1341 if (VT.is128BitVector()) {
1342 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1344 // Do not attempt to custom lower other non-256-bit vectors
1345 if (!VT.is256BitVector())
1348 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1349 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1350 setOperationAction(ISD::VSELECT, VT, Custom);
1351 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1353 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1354 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1355 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1358 if (Subtarget->hasInt256())
1359 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1362 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1363 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1364 MVT VT = (MVT::SimpleValueType)i;
1366 // Do not attempt to promote non-256-bit vectors
1367 if (!VT.is256BitVector())
1370 setOperationAction(ISD::AND, VT, Promote);
1371 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1372 setOperationAction(ISD::OR, VT, Promote);
1373 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1374 setOperationAction(ISD::XOR, VT, Promote);
1375 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1376 setOperationAction(ISD::LOAD, VT, Promote);
1377 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1378 setOperationAction(ISD::SELECT, VT, Promote);
1379 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1383 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1384 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1385 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1386 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1387 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1389 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1390 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1391 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1393 for (MVT VT : MVT::fp_vector_valuetypes())
1394 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1396 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1397 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1398 setOperationAction(ISD::XOR, MVT::i1, Legal);
1399 setOperationAction(ISD::OR, MVT::i1, Legal);
1400 setOperationAction(ISD::AND, MVT::i1, Legal);
1401 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1402 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1403 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1404 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1405 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1407 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1408 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1409 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1410 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1411 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1412 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1414 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1415 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1416 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1417 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1418 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1419 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1420 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1421 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1423 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1424 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1425 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1426 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1427 if (Subtarget->is64Bit()) {
1428 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1429 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1430 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1431 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1433 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1434 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1435 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1436 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1437 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1438 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1439 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1440 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1441 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1442 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1443 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1444 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1445 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1446 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1448 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1449 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1450 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1451 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1452 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1453 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1454 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1455 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1456 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1457 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1458 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1459 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1460 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1462 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1463 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1464 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1465 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1466 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1467 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1468 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1469 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1470 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1471 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1474 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1475 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1476 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1477 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1478 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1480 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1481 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1483 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1485 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1486 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1487 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1488 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1489 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1490 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1491 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1492 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1493 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1495 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1496 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1498 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1499 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1501 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1503 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1504 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1506 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1507 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1509 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1510 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1512 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1513 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1514 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1515 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1516 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1517 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1519 if (Subtarget->hasCDI()) {
1520 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1521 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1524 // Custom lower several nodes.
1525 for (MVT VT : MVT::vector_valuetypes()) {
1526 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1527 // Extract subvector is special because the value type
1528 // (result) is 256/128-bit but the source is 512-bit wide.
1529 if (VT.is128BitVector() || VT.is256BitVector()) {
1530 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1532 if (VT.getVectorElementType() == MVT::i1)
1533 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1535 // Do not attempt to custom lower other non-512-bit vectors
1536 if (!VT.is512BitVector())
1539 if ( EltSize >= 32) {
1540 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1541 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1542 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1543 setOperationAction(ISD::VSELECT, VT, Legal);
1544 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1545 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1546 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1547 setOperationAction(ISD::MLOAD, VT, Legal);
1548 setOperationAction(ISD::MSTORE, VT, Legal);
1551 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1552 MVT VT = (MVT::SimpleValueType)i;
1554 // Do not attempt to promote non-512-bit vectors.
1555 if (!VT.is512BitVector())
1558 setOperationAction(ISD::SELECT, VT, Promote);
1559 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1563 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1564 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1565 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1567 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1568 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1570 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1571 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1572 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1573 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1574 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1575 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1576 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1577 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1578 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1580 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1581 const MVT VT = (MVT::SimpleValueType)i;
1583 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1585 // Do not attempt to promote non-512-bit vectors.
1586 if (!VT.is512BitVector())
1590 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1591 setOperationAction(ISD::VSELECT, VT, Legal);
1596 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1597 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1598 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1600 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1601 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1602 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Legal);
1604 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1605 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1606 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1607 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1608 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1609 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1612 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1613 // of this type with custom code.
1614 for (MVT VT : MVT::vector_valuetypes())
1615 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1617 // We want to custom lower some of our intrinsics.
1618 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1619 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1620 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1621 if (!Subtarget->is64Bit())
1622 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1624 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1625 // handle type legalization for these operations here.
1627 // FIXME: We really should do custom legalization for addition and
1628 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1629 // than generic legalization for 64-bit multiplication-with-overflow, though.
1630 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1631 // Add/Sub/Mul with overflow operations are custom lowered.
1633 setOperationAction(ISD::SADDO, VT, Custom);
1634 setOperationAction(ISD::UADDO, VT, Custom);
1635 setOperationAction(ISD::SSUBO, VT, Custom);
1636 setOperationAction(ISD::USUBO, VT, Custom);
1637 setOperationAction(ISD::SMULO, VT, Custom);
1638 setOperationAction(ISD::UMULO, VT, Custom);
1642 if (!Subtarget->is64Bit()) {
1643 // These libcalls are not available in 32-bit.
1644 setLibcallName(RTLIB::SHL_I128, nullptr);
1645 setLibcallName(RTLIB::SRL_I128, nullptr);
1646 setLibcallName(RTLIB::SRA_I128, nullptr);
1649 // Combine sin / cos into one node or libcall if possible.
1650 if (Subtarget->hasSinCos()) {
1651 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1652 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1653 if (Subtarget->isTargetDarwin()) {
1654 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1655 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1656 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1657 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1661 if (Subtarget->isTargetWin64()) {
1662 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1663 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1664 setOperationAction(ISD::SREM, MVT::i128, Custom);
1665 setOperationAction(ISD::UREM, MVT::i128, Custom);
1666 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1667 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1670 // We have target-specific dag combine patterns for the following nodes:
1671 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1672 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1673 setTargetDAGCombine(ISD::BITCAST);
1674 setTargetDAGCombine(ISD::VSELECT);
1675 setTargetDAGCombine(ISD::SELECT);
1676 setTargetDAGCombine(ISD::SHL);
1677 setTargetDAGCombine(ISD::SRA);
1678 setTargetDAGCombine(ISD::SRL);
1679 setTargetDAGCombine(ISD::OR);
1680 setTargetDAGCombine(ISD::AND);
1681 setTargetDAGCombine(ISD::ADD);
1682 setTargetDAGCombine(ISD::FADD);
1683 setTargetDAGCombine(ISD::FSUB);
1684 setTargetDAGCombine(ISD::FMA);
1685 setTargetDAGCombine(ISD::SUB);
1686 setTargetDAGCombine(ISD::LOAD);
1687 setTargetDAGCombine(ISD::MLOAD);
1688 setTargetDAGCombine(ISD::STORE);
1689 setTargetDAGCombine(ISD::MSTORE);
1690 setTargetDAGCombine(ISD::ZERO_EXTEND);
1691 setTargetDAGCombine(ISD::ANY_EXTEND);
1692 setTargetDAGCombine(ISD::SIGN_EXTEND);
1693 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1694 setTargetDAGCombine(ISD::TRUNCATE);
1695 setTargetDAGCombine(ISD::SINT_TO_FP);
1696 setTargetDAGCombine(ISD::SETCC);
1697 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1698 setTargetDAGCombine(ISD::BUILD_VECTOR);
1699 setTargetDAGCombine(ISD::MUL);
1700 setTargetDAGCombine(ISD::XOR);
1702 computeRegisterProperties();
1704 // On Darwin, -Os means optimize for size without hurting performance,
1705 // do not reduce the limit.
1706 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1707 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1708 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1709 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1710 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1711 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1712 setPrefLoopAlignment(4); // 2^4 bytes.
1714 // Predictable cmov don't hurt on atom because it's in-order.
1715 PredictableSelectIsExpensive = !Subtarget->isAtom();
1716 EnableExtLdPromotion = true;
1717 setPrefFunctionAlignment(4); // 2^4 bytes.
1719 verifyIntrinsicTables();
1722 // This has so far only been implemented for 64-bit MachO.
1723 bool X86TargetLowering::useLoadStackGuardNode() const {
1724 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1727 TargetLoweringBase::LegalizeTypeAction
1728 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1729 if (ExperimentalVectorWideningLegalization &&
1730 VT.getVectorNumElements() != 1 &&
1731 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1732 return TypeWidenVector;
1734 return TargetLoweringBase::getPreferredVectorAction(VT);
1737 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1739 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1741 const unsigned NumElts = VT.getVectorNumElements();
1742 const EVT EltVT = VT.getVectorElementType();
1743 if (VT.is512BitVector()) {
1744 if (Subtarget->hasAVX512())
1745 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1746 EltVT == MVT::f32 || EltVT == MVT::f64)
1748 case 8: return MVT::v8i1;
1749 case 16: return MVT::v16i1;
1751 if (Subtarget->hasBWI())
1752 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1754 case 32: return MVT::v32i1;
1755 case 64: return MVT::v64i1;
1759 if (VT.is256BitVector() || VT.is128BitVector()) {
1760 if (Subtarget->hasVLX())
1761 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1762 EltVT == MVT::f32 || EltVT == MVT::f64)
1764 case 2: return MVT::v2i1;
1765 case 4: return MVT::v4i1;
1766 case 8: return MVT::v8i1;
1768 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1769 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1771 case 8: return MVT::v8i1;
1772 case 16: return MVT::v16i1;
1773 case 32: return MVT::v32i1;
1777 return VT.changeVectorElementTypeToInteger();
1780 /// Helper for getByValTypeAlignment to determine
1781 /// the desired ByVal argument alignment.
1782 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1785 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1786 if (VTy->getBitWidth() == 128)
1788 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1789 unsigned EltAlign = 0;
1790 getMaxByValAlign(ATy->getElementType(), EltAlign);
1791 if (EltAlign > MaxAlign)
1792 MaxAlign = EltAlign;
1793 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1794 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1795 unsigned EltAlign = 0;
1796 getMaxByValAlign(STy->getElementType(i), EltAlign);
1797 if (EltAlign > MaxAlign)
1798 MaxAlign = EltAlign;
1805 /// Return the desired alignment for ByVal aggregate
1806 /// function arguments in the caller parameter area. For X86, aggregates
1807 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1808 /// are at 4-byte boundaries.
1809 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1810 if (Subtarget->is64Bit()) {
1811 // Max of 8 and alignment of type.
1812 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1819 if (Subtarget->hasSSE1())
1820 getMaxByValAlign(Ty, Align);
1824 /// Returns the target specific optimal type for load
1825 /// and store operations as a result of memset, memcpy, and memmove
1826 /// lowering. If DstAlign is zero that means it's safe to destination
1827 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1828 /// means there isn't a need to check it against alignment requirement,
1829 /// probably because the source does not need to be loaded. If 'IsMemset' is
1830 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1831 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1832 /// source is constant so it does not need to be loaded.
1833 /// It returns EVT::Other if the type should be determined using generic
1834 /// target-independent logic.
1836 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1837 unsigned DstAlign, unsigned SrcAlign,
1838 bool IsMemset, bool ZeroMemset,
1840 MachineFunction &MF) const {
1841 const Function *F = MF.getFunction();
1842 if ((!IsMemset || ZeroMemset) &&
1843 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1845 (Subtarget->isUnalignedMemAccessFast() ||
1846 ((DstAlign == 0 || DstAlign >= 16) &&
1847 (SrcAlign == 0 || SrcAlign >= 16)))) {
1849 if (Subtarget->hasInt256())
1851 if (Subtarget->hasFp256())
1854 if (Subtarget->hasSSE2())
1856 if (Subtarget->hasSSE1())
1858 } else if (!MemcpyStrSrc && Size >= 8 &&
1859 !Subtarget->is64Bit() &&
1860 Subtarget->hasSSE2()) {
1861 // Do not use f64 to lower memcpy if source is string constant. It's
1862 // better to use i32 to avoid the loads.
1866 if (Subtarget->is64Bit() && Size >= 8)
1871 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1873 return X86ScalarSSEf32;
1874 else if (VT == MVT::f64)
1875 return X86ScalarSSEf64;
1880 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1885 *Fast = Subtarget->isUnalignedMemAccessFast();
1889 /// Return the entry encoding for a jump table in the
1890 /// current function. The returned value is a member of the
1891 /// MachineJumpTableInfo::JTEntryKind enum.
1892 unsigned X86TargetLowering::getJumpTableEncoding() const {
1893 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1895 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1896 Subtarget->isPICStyleGOT())
1897 return MachineJumpTableInfo::EK_Custom32;
1899 // Otherwise, use the normal jump table encoding heuristics.
1900 return TargetLowering::getJumpTableEncoding();
1904 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1905 const MachineBasicBlock *MBB,
1906 unsigned uid,MCContext &Ctx) const{
1907 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1908 Subtarget->isPICStyleGOT());
1909 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1911 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1912 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1915 /// Returns relocation base for the given PIC jumptable.
1916 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1917 SelectionDAG &DAG) const {
1918 if (!Subtarget->is64Bit())
1919 // This doesn't have SDLoc associated with it, but is not really the
1920 // same as a Register.
1921 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1925 /// This returns the relocation base for the given PIC jumptable,
1926 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1927 const MCExpr *X86TargetLowering::
1928 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1929 MCContext &Ctx) const {
1930 // X86-64 uses RIP relative addressing based on the jump table label.
1931 if (Subtarget->isPICStyleRIPRel())
1932 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1934 // Otherwise, the reference is relative to the PIC base.
1935 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1938 // FIXME: Why this routine is here? Move to RegInfo!
1939 std::pair<const TargetRegisterClass*, uint8_t>
1940 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1941 const TargetRegisterClass *RRC = nullptr;
1943 switch (VT.SimpleTy) {
1945 return TargetLowering::findRepresentativeClass(VT);
1946 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1947 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1950 RRC = &X86::VR64RegClass;
1952 case MVT::f32: case MVT::f64:
1953 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1954 case MVT::v4f32: case MVT::v2f64:
1955 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1957 RRC = &X86::VR128RegClass;
1960 return std::make_pair(RRC, Cost);
1963 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1964 unsigned &Offset) const {
1965 if (!Subtarget->isTargetLinux())
1968 if (Subtarget->is64Bit()) {
1969 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1971 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1983 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1984 unsigned DestAS) const {
1985 assert(SrcAS != DestAS && "Expected different address spaces!");
1987 return SrcAS < 256 && DestAS < 256;
1990 //===----------------------------------------------------------------------===//
1991 // Return Value Calling Convention Implementation
1992 //===----------------------------------------------------------------------===//
1994 #include "X86GenCallingConv.inc"
1997 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1998 MachineFunction &MF, bool isVarArg,
1999 const SmallVectorImpl<ISD::OutputArg> &Outs,
2000 LLVMContext &Context) const {
2001 SmallVector<CCValAssign, 16> RVLocs;
2002 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2003 return CCInfo.CheckReturn(Outs, RetCC_X86);
2006 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2007 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2012 X86TargetLowering::LowerReturn(SDValue Chain,
2013 CallingConv::ID CallConv, bool isVarArg,
2014 const SmallVectorImpl<ISD::OutputArg> &Outs,
2015 const SmallVectorImpl<SDValue> &OutVals,
2016 SDLoc dl, SelectionDAG &DAG) const {
2017 MachineFunction &MF = DAG.getMachineFunction();
2018 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2020 SmallVector<CCValAssign, 16> RVLocs;
2021 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2022 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2025 SmallVector<SDValue, 6> RetOps;
2026 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2027 // Operand #1 = Bytes To Pop
2028 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
2031 // Copy the result values into the output registers.
2032 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2033 CCValAssign &VA = RVLocs[i];
2034 assert(VA.isRegLoc() && "Can only return in registers!");
2035 SDValue ValToCopy = OutVals[i];
2036 EVT ValVT = ValToCopy.getValueType();
2038 // Promote values to the appropriate types.
2039 if (VA.getLocInfo() == CCValAssign::SExt)
2040 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2041 else if (VA.getLocInfo() == CCValAssign::ZExt)
2042 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2043 else if (VA.getLocInfo() == CCValAssign::AExt)
2044 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2045 else if (VA.getLocInfo() == CCValAssign::BCvt)
2046 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2048 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2049 "Unexpected FP-extend for return value.");
2051 // If this is x86-64, and we disabled SSE, we can't return FP values,
2052 // or SSE or MMX vectors.
2053 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2054 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2055 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2056 report_fatal_error("SSE register return with SSE disabled");
2058 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2059 // llvm-gcc has never done it right and no one has noticed, so this
2060 // should be OK for now.
2061 if (ValVT == MVT::f64 &&
2062 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2063 report_fatal_error("SSE2 register return with SSE2 disabled");
2065 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2066 // the RET instruction and handled by the FP Stackifier.
2067 if (VA.getLocReg() == X86::FP0 ||
2068 VA.getLocReg() == X86::FP1) {
2069 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2070 // change the value to the FP stack register class.
2071 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2072 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2073 RetOps.push_back(ValToCopy);
2074 // Don't emit a copytoreg.
2078 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2079 // which is returned in RAX / RDX.
2080 if (Subtarget->is64Bit()) {
2081 if (ValVT == MVT::x86mmx) {
2082 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2083 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2084 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2086 // If we don't have SSE2 available, convert to v4f32 so the generated
2087 // register is legal.
2088 if (!Subtarget->hasSSE2())
2089 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2094 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2095 Flag = Chain.getValue(1);
2096 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2099 // The x86-64 ABIs require that for returning structs by value we copy
2100 // the sret argument into %rax/%eax (depending on ABI) for the return.
2101 // Win32 requires us to put the sret argument to %eax as well.
2102 // We saved the argument into a virtual register in the entry block,
2103 // so now we copy the value out and into %rax/%eax.
2105 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2106 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2107 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2108 // either case FuncInfo->setSRetReturnReg() will have been called.
2109 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2110 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2111 "No need for an sret register");
2112 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2115 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2116 X86::RAX : X86::EAX;
2117 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2118 Flag = Chain.getValue(1);
2120 // RAX/EAX now acts like a return value.
2121 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2124 RetOps[0] = Chain; // Update chain.
2126 // Add the flag if we have it.
2128 RetOps.push_back(Flag);
2130 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2133 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2134 if (N->getNumValues() != 1)
2136 if (!N->hasNUsesOfValue(1, 0))
2139 SDValue TCChain = Chain;
2140 SDNode *Copy = *N->use_begin();
2141 if (Copy->getOpcode() == ISD::CopyToReg) {
2142 // If the copy has a glue operand, we conservatively assume it isn't safe to
2143 // perform a tail call.
2144 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2146 TCChain = Copy->getOperand(0);
2147 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2150 bool HasRet = false;
2151 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2153 if (UI->getOpcode() != X86ISD::RET_FLAG)
2155 // If we are returning more than one value, we can definitely
2156 // not make a tail call see PR19530
2157 if (UI->getNumOperands() > 4)
2159 if (UI->getNumOperands() == 4 &&
2160 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2173 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2174 ISD::NodeType ExtendKind) const {
2176 // TODO: Is this also valid on 32-bit?
2177 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2178 ReturnMVT = MVT::i8;
2180 ReturnMVT = MVT::i32;
2182 EVT MinVT = getRegisterType(Context, ReturnMVT);
2183 return VT.bitsLT(MinVT) ? MinVT : VT;
2186 /// Lower the result values of a call into the
2187 /// appropriate copies out of appropriate physical registers.
2190 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2191 CallingConv::ID CallConv, bool isVarArg,
2192 const SmallVectorImpl<ISD::InputArg> &Ins,
2193 SDLoc dl, SelectionDAG &DAG,
2194 SmallVectorImpl<SDValue> &InVals) const {
2196 // Assign locations to each value returned by this call.
2197 SmallVector<CCValAssign, 16> RVLocs;
2198 bool Is64Bit = Subtarget->is64Bit();
2199 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2201 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2203 // Copy all of the result registers out of their specified physreg.
2204 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2205 CCValAssign &VA = RVLocs[i];
2206 EVT CopyVT = VA.getValVT();
2208 // If this is x86-64, and we disabled SSE, we can't return FP values
2209 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2210 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2211 report_fatal_error("SSE register return with SSE disabled");
2214 // If we prefer to use the value in xmm registers, copy it out as f80 and
2215 // use a truncate to move it from fp stack reg to xmm reg.
2216 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2217 isScalarFPTypeInSSEReg(VA.getValVT()))
2220 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2221 CopyVT, InFlag).getValue(1);
2222 SDValue Val = Chain.getValue(0);
2224 if (CopyVT != VA.getValVT())
2225 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2226 // This truncation won't change the value.
2227 DAG.getIntPtrConstant(1));
2229 InFlag = Chain.getValue(2);
2230 InVals.push_back(Val);
2236 //===----------------------------------------------------------------------===//
2237 // C & StdCall & Fast Calling Convention implementation
2238 //===----------------------------------------------------------------------===//
2239 // StdCall calling convention seems to be standard for many Windows' API
2240 // routines and around. It differs from C calling convention just a little:
2241 // callee should clean up the stack, not caller. Symbols should be also
2242 // decorated in some fancy way :) It doesn't support any vector arguments.
2243 // For info on fast calling convention see Fast Calling Convention (tail call)
2244 // implementation LowerX86_32FastCCCallTo.
2246 /// CallIsStructReturn - Determines whether a call uses struct return
2248 enum StructReturnType {
2253 static StructReturnType
2254 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2256 return NotStructReturn;
2258 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2259 if (!Flags.isSRet())
2260 return NotStructReturn;
2261 if (Flags.isInReg())
2262 return RegStructReturn;
2263 return StackStructReturn;
2266 /// Determines whether a function uses struct return semantics.
2267 static StructReturnType
2268 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2270 return NotStructReturn;
2272 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2273 if (!Flags.isSRet())
2274 return NotStructReturn;
2275 if (Flags.isInReg())
2276 return RegStructReturn;
2277 return StackStructReturn;
2280 /// Make a copy of an aggregate at address specified by "Src" to address
2281 /// "Dst" with size and alignment information specified by the specific
2282 /// parameter attribute. The copy will be passed as a byval function parameter.
2284 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2285 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2287 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2289 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2290 /*isVolatile*/false, /*AlwaysInline=*/true,
2291 MachinePointerInfo(), MachinePointerInfo());
2294 /// Return true if the calling convention is one that
2295 /// supports tail call optimization.
2296 static bool IsTailCallConvention(CallingConv::ID CC) {
2297 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2298 CC == CallingConv::HiPE);
2301 /// \brief Return true if the calling convention is a C calling convention.
2302 static bool IsCCallConvention(CallingConv::ID CC) {
2303 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2304 CC == CallingConv::X86_64_SysV);
2307 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2308 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2312 CallingConv::ID CalleeCC = CS.getCallingConv();
2313 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2319 /// Return true if the function is being made into
2320 /// a tailcall target by changing its ABI.
2321 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2322 bool GuaranteedTailCallOpt) {
2323 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2327 X86TargetLowering::LowerMemArgument(SDValue Chain,
2328 CallingConv::ID CallConv,
2329 const SmallVectorImpl<ISD::InputArg> &Ins,
2330 SDLoc dl, SelectionDAG &DAG,
2331 const CCValAssign &VA,
2332 MachineFrameInfo *MFI,
2334 // Create the nodes corresponding to a load from this parameter slot.
2335 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2336 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2337 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2338 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2341 // If value is passed by pointer we have address passed instead of the value
2343 if (VA.getLocInfo() == CCValAssign::Indirect)
2344 ValVT = VA.getLocVT();
2346 ValVT = VA.getValVT();
2348 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2349 // changed with more analysis.
2350 // In case of tail call optimization mark all arguments mutable. Since they
2351 // could be overwritten by lowering of arguments in case of a tail call.
2352 if (Flags.isByVal()) {
2353 unsigned Bytes = Flags.getByValSize();
2354 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2355 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2356 return DAG.getFrameIndex(FI, getPointerTy());
2358 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2359 VA.getLocMemOffset(), isImmutable);
2360 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2361 return DAG.getLoad(ValVT, dl, Chain, FIN,
2362 MachinePointerInfo::getFixedStack(FI),
2363 false, false, false, 0);
2367 // FIXME: Get this from tablegen.
2368 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2369 const X86Subtarget *Subtarget) {
2370 assert(Subtarget->is64Bit());
2372 if (Subtarget->isCallingConvWin64(CallConv)) {
2373 static const MCPhysReg GPR64ArgRegsWin64[] = {
2374 X86::RCX, X86::RDX, X86::R8, X86::R9
2376 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2379 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2380 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2382 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2385 // FIXME: Get this from tablegen.
2386 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2387 CallingConv::ID CallConv,
2388 const X86Subtarget *Subtarget) {
2389 assert(Subtarget->is64Bit());
2390 if (Subtarget->isCallingConvWin64(CallConv)) {
2391 // The XMM registers which might contain var arg parameters are shadowed
2392 // in their paired GPR. So we only need to save the GPR to their home
2394 // TODO: __vectorcall will change this.
2398 const Function *Fn = MF.getFunction();
2399 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2400 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2401 "SSE register cannot be used when SSE is disabled!");
2402 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2403 !Subtarget->hasSSE1())
2404 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2408 static const MCPhysReg XMMArgRegs64Bit[] = {
2409 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2410 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2412 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2416 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2417 CallingConv::ID CallConv,
2419 const SmallVectorImpl<ISD::InputArg> &Ins,
2422 SmallVectorImpl<SDValue> &InVals)
2424 MachineFunction &MF = DAG.getMachineFunction();
2425 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2427 const Function* Fn = MF.getFunction();
2428 if (Fn->hasExternalLinkage() &&
2429 Subtarget->isTargetCygMing() &&
2430 Fn->getName() == "main")
2431 FuncInfo->setForceFramePointer(true);
2433 MachineFrameInfo *MFI = MF.getFrameInfo();
2434 bool Is64Bit = Subtarget->is64Bit();
2435 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2437 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2438 "Var args not supported with calling convention fastcc, ghc or hipe");
2440 // Assign locations to all of the incoming arguments.
2441 SmallVector<CCValAssign, 16> ArgLocs;
2442 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2444 // Allocate shadow area for Win64
2446 CCInfo.AllocateStack(32, 8);
2448 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2450 unsigned LastVal = ~0U;
2452 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2453 CCValAssign &VA = ArgLocs[i];
2454 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2456 assert(VA.getValNo() != LastVal &&
2457 "Don't support value assigned to multiple locs yet");
2459 LastVal = VA.getValNo();
2461 if (VA.isRegLoc()) {
2462 EVT RegVT = VA.getLocVT();
2463 const TargetRegisterClass *RC;
2464 if (RegVT == MVT::i32)
2465 RC = &X86::GR32RegClass;
2466 else if (Is64Bit && RegVT == MVT::i64)
2467 RC = &X86::GR64RegClass;
2468 else if (RegVT == MVT::f32)
2469 RC = &X86::FR32RegClass;
2470 else if (RegVT == MVT::f64)
2471 RC = &X86::FR64RegClass;
2472 else if (RegVT.is512BitVector())
2473 RC = &X86::VR512RegClass;
2474 else if (RegVT.is256BitVector())
2475 RC = &X86::VR256RegClass;
2476 else if (RegVT.is128BitVector())
2477 RC = &X86::VR128RegClass;
2478 else if (RegVT == MVT::x86mmx)
2479 RC = &X86::VR64RegClass;
2480 else if (RegVT == MVT::i1)
2481 RC = &X86::VK1RegClass;
2482 else if (RegVT == MVT::v8i1)
2483 RC = &X86::VK8RegClass;
2484 else if (RegVT == MVT::v16i1)
2485 RC = &X86::VK16RegClass;
2486 else if (RegVT == MVT::v32i1)
2487 RC = &X86::VK32RegClass;
2488 else if (RegVT == MVT::v64i1)
2489 RC = &X86::VK64RegClass;
2491 llvm_unreachable("Unknown argument type!");
2493 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2494 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2496 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2497 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2499 if (VA.getLocInfo() == CCValAssign::SExt)
2500 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2501 DAG.getValueType(VA.getValVT()));
2502 else if (VA.getLocInfo() == CCValAssign::ZExt)
2503 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2504 DAG.getValueType(VA.getValVT()));
2505 else if (VA.getLocInfo() == CCValAssign::BCvt)
2506 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2508 if (VA.isExtInLoc()) {
2509 // Handle MMX values passed in XMM regs.
2510 if (RegVT.isVector())
2511 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2513 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2516 assert(VA.isMemLoc());
2517 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2520 // If value is passed via pointer - do a load.
2521 if (VA.getLocInfo() == CCValAssign::Indirect)
2522 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2523 MachinePointerInfo(), false, false, false, 0);
2525 InVals.push_back(ArgValue);
2528 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2529 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2530 // The x86-64 ABIs require that for returning structs by value we copy
2531 // the sret argument into %rax/%eax (depending on ABI) for the return.
2532 // Win32 requires us to put the sret argument to %eax as well.
2533 // Save the argument into a virtual register so that we can access it
2534 // from the return points.
2535 if (Ins[i].Flags.isSRet()) {
2536 unsigned Reg = FuncInfo->getSRetReturnReg();
2538 MVT PtrTy = getPointerTy();
2539 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2540 FuncInfo->setSRetReturnReg(Reg);
2542 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2543 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2549 unsigned StackSize = CCInfo.getNextStackOffset();
2550 // Align stack specially for tail calls.
2551 if (FuncIsMadeTailCallSafe(CallConv,
2552 MF.getTarget().Options.GuaranteedTailCallOpt))
2553 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2555 // If the function takes variable number of arguments, make a frame index for
2556 // the start of the first vararg value... for expansion of llvm.va_start. We
2557 // can skip this if there are no va_start calls.
2558 if (MFI->hasVAStart() &&
2559 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2560 CallConv != CallingConv::X86_ThisCall))) {
2561 FuncInfo->setVarArgsFrameIndex(
2562 MFI->CreateFixedObject(1, StackSize, true));
2565 // Figure out if XMM registers are in use.
2566 assert(!(MF.getTarget().Options.UseSoftFloat &&
2567 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2568 "SSE register cannot be used when SSE is disabled!");
2570 // 64-bit calling conventions support varargs and register parameters, so we
2571 // have to do extra work to spill them in the prologue.
2572 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2573 // Find the first unallocated argument registers.
2574 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2575 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2576 unsigned NumIntRegs =
2577 CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2578 unsigned NumXMMRegs =
2579 CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2580 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2581 "SSE register cannot be used when SSE is disabled!");
2583 // Gather all the live in physical registers.
2584 SmallVector<SDValue, 6> LiveGPRs;
2585 SmallVector<SDValue, 8> LiveXMMRegs;
2587 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2588 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2590 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2592 if (!ArgXMMs.empty()) {
2593 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2594 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2595 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2596 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2597 LiveXMMRegs.push_back(
2598 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2603 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2604 // Get to the caller-allocated home save location. Add 8 to account
2605 // for the return address.
2606 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2607 FuncInfo->setRegSaveFrameIndex(
2608 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2609 // Fixup to set vararg frame on shadow area (4 x i64).
2611 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2613 // For X86-64, if there are vararg parameters that are passed via
2614 // registers, then we must store them to their spots on the stack so
2615 // they may be loaded by deferencing the result of va_next.
2616 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2617 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2618 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2619 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2622 // Store the integer parameter registers.
2623 SmallVector<SDValue, 8> MemOps;
2624 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2626 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2627 for (SDValue Val : LiveGPRs) {
2628 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2629 DAG.getIntPtrConstant(Offset));
2631 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2632 MachinePointerInfo::getFixedStack(
2633 FuncInfo->getRegSaveFrameIndex(), Offset),
2635 MemOps.push_back(Store);
2639 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2640 // Now store the XMM (fp + vector) parameter registers.
2641 SmallVector<SDValue, 12> SaveXMMOps;
2642 SaveXMMOps.push_back(Chain);
2643 SaveXMMOps.push_back(ALVal);
2644 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2645 FuncInfo->getRegSaveFrameIndex()));
2646 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2647 FuncInfo->getVarArgsFPOffset()));
2648 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2650 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2651 MVT::Other, SaveXMMOps));
2654 if (!MemOps.empty())
2655 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2658 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2659 // Find the largest legal vector type.
2660 MVT VecVT = MVT::Other;
2661 // FIXME: Only some x86_32 calling conventions support AVX512.
2662 if (Subtarget->hasAVX512() &&
2663 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2664 CallConv == CallingConv::Intel_OCL_BI)))
2665 VecVT = MVT::v16f32;
2666 else if (Subtarget->hasAVX())
2668 else if (Subtarget->hasSSE2())
2671 // We forward some GPRs and some vector types.
2672 SmallVector<MVT, 2> RegParmTypes;
2673 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2674 RegParmTypes.push_back(IntVT);
2675 if (VecVT != MVT::Other)
2676 RegParmTypes.push_back(VecVT);
2678 // Compute the set of forwarded registers. The rest are scratch.
2679 SmallVectorImpl<ForwardedRegister> &Forwards =
2680 FuncInfo->getForwardedMustTailRegParms();
2681 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2683 // Conservatively forward AL on x86_64, since it might be used for varargs.
2684 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2685 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2686 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2689 // Copy all forwards from physical to virtual registers.
2690 for (ForwardedRegister &F : Forwards) {
2691 // FIXME: Can we use a less constrained schedule?
2692 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2693 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2694 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2698 // Some CCs need callee pop.
2699 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2700 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2701 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2703 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2704 // If this is an sret function, the return should pop the hidden pointer.
2705 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2706 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2707 argsAreStructReturn(Ins) == StackStructReturn)
2708 FuncInfo->setBytesToPopOnReturn(4);
2712 // RegSaveFrameIndex is X86-64 only.
2713 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2714 if (CallConv == CallingConv::X86_FastCall ||
2715 CallConv == CallingConv::X86_ThisCall)
2716 // fastcc functions can't have varargs.
2717 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2720 FuncInfo->setArgumentStackSize(StackSize);
2726 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2727 SDValue StackPtr, SDValue Arg,
2728 SDLoc dl, SelectionDAG &DAG,
2729 const CCValAssign &VA,
2730 ISD::ArgFlagsTy Flags) const {
2731 unsigned LocMemOffset = VA.getLocMemOffset();
2732 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2733 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2734 if (Flags.isByVal())
2735 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2737 return DAG.getStore(Chain, dl, Arg, PtrOff,
2738 MachinePointerInfo::getStack(LocMemOffset),
2742 /// Emit a load of return address if tail call
2743 /// optimization is performed and it is required.
2745 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2746 SDValue &OutRetAddr, SDValue Chain,
2747 bool IsTailCall, bool Is64Bit,
2748 int FPDiff, SDLoc dl) const {
2749 // Adjust the Return address stack slot.
2750 EVT VT = getPointerTy();
2751 OutRetAddr = getReturnAddressFrameIndex(DAG);
2753 // Load the "old" Return address.
2754 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2755 false, false, false, 0);
2756 return SDValue(OutRetAddr.getNode(), 1);
2759 /// Emit a store of the return address if tail call
2760 /// optimization is performed and it is required (FPDiff!=0).
2761 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2762 SDValue Chain, SDValue RetAddrFrIdx,
2763 EVT PtrVT, unsigned SlotSize,
2764 int FPDiff, SDLoc dl) {
2765 // Store the return address to the appropriate stack slot.
2766 if (!FPDiff) return Chain;
2767 // Calculate the new stack slot for the return address.
2768 int NewReturnAddrFI =
2769 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2771 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2772 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2773 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2779 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2780 SmallVectorImpl<SDValue> &InVals) const {
2781 SelectionDAG &DAG = CLI.DAG;
2783 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2784 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2785 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2786 SDValue Chain = CLI.Chain;
2787 SDValue Callee = CLI.Callee;
2788 CallingConv::ID CallConv = CLI.CallConv;
2789 bool &isTailCall = CLI.IsTailCall;
2790 bool isVarArg = CLI.IsVarArg;
2792 MachineFunction &MF = DAG.getMachineFunction();
2793 bool Is64Bit = Subtarget->is64Bit();
2794 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2795 StructReturnType SR = callIsStructReturn(Outs);
2796 bool IsSibcall = false;
2797 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2799 if (MF.getTarget().Options.DisableTailCalls)
2802 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2804 // Force this to be a tail call. The verifier rules are enough to ensure
2805 // that we can lower this successfully without moving the return address
2808 } else if (isTailCall) {
2809 // Check if it's really possible to do a tail call.
2810 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2811 isVarArg, SR != NotStructReturn,
2812 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2813 Outs, OutVals, Ins, DAG);
2815 // Sibcalls are automatically detected tailcalls which do not require
2817 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2824 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2825 "Var args not supported with calling convention fastcc, ghc or hipe");
2827 // Analyze operands of the call, assigning locations to each operand.
2828 SmallVector<CCValAssign, 16> ArgLocs;
2829 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2831 // Allocate shadow area for Win64
2833 CCInfo.AllocateStack(32, 8);
2835 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2837 // Get a count of how many bytes are to be pushed on the stack.
2838 unsigned NumBytes = CCInfo.getNextStackOffset();
2840 // This is a sibcall. The memory operands are available in caller's
2841 // own caller's stack.
2843 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2844 IsTailCallConvention(CallConv))
2845 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2848 if (isTailCall && !IsSibcall && !IsMustTail) {
2849 // Lower arguments at fp - stackoffset + fpdiff.
2850 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2852 FPDiff = NumBytesCallerPushed - NumBytes;
2854 // Set the delta of movement of the returnaddr stackslot.
2855 // But only set if delta is greater than previous delta.
2856 if (FPDiff < X86Info->getTCReturnAddrDelta())
2857 X86Info->setTCReturnAddrDelta(FPDiff);
2860 unsigned NumBytesToPush = NumBytes;
2861 unsigned NumBytesToPop = NumBytes;
2863 // If we have an inalloca argument, all stack space has already been allocated
2864 // for us and be right at the top of the stack. We don't support multiple
2865 // arguments passed in memory when using inalloca.
2866 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2868 if (!ArgLocs.back().isMemLoc())
2869 report_fatal_error("cannot use inalloca attribute on a register "
2871 if (ArgLocs.back().getLocMemOffset() != 0)
2872 report_fatal_error("any parameter with the inalloca attribute must be "
2873 "the only memory argument");
2877 Chain = DAG.getCALLSEQ_START(
2878 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2880 SDValue RetAddrFrIdx;
2881 // Load return address for tail calls.
2882 if (isTailCall && FPDiff)
2883 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2884 Is64Bit, FPDiff, dl);
2886 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2887 SmallVector<SDValue, 8> MemOpChains;
2890 // Walk the register/memloc assignments, inserting copies/loads. In the case
2891 // of tail call optimization arguments are handle later.
2892 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2893 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2894 // Skip inalloca arguments, they have already been written.
2895 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2896 if (Flags.isInAlloca())
2899 CCValAssign &VA = ArgLocs[i];
2900 EVT RegVT = VA.getLocVT();
2901 SDValue Arg = OutVals[i];
2902 bool isByVal = Flags.isByVal();
2904 // Promote the value if needed.
2905 switch (VA.getLocInfo()) {
2906 default: llvm_unreachable("Unknown loc info!");
2907 case CCValAssign::Full: break;
2908 case CCValAssign::SExt:
2909 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2911 case CCValAssign::ZExt:
2912 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2914 case CCValAssign::AExt:
2915 if (RegVT.is128BitVector()) {
2916 // Special case: passing MMX values in XMM registers.
2917 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2918 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2919 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2921 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2923 case CCValAssign::BCvt:
2924 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2926 case CCValAssign::Indirect: {
2927 // Store the argument.
2928 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2929 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2930 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2931 MachinePointerInfo::getFixedStack(FI),
2938 if (VA.isRegLoc()) {
2939 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2940 if (isVarArg && IsWin64) {
2941 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2942 // shadow reg if callee is a varargs function.
2943 unsigned ShadowReg = 0;
2944 switch (VA.getLocReg()) {
2945 case X86::XMM0: ShadowReg = X86::RCX; break;
2946 case X86::XMM1: ShadowReg = X86::RDX; break;
2947 case X86::XMM2: ShadowReg = X86::R8; break;
2948 case X86::XMM3: ShadowReg = X86::R9; break;
2951 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2953 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2954 assert(VA.isMemLoc());
2955 if (!StackPtr.getNode())
2956 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2958 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2959 dl, DAG, VA, Flags));
2963 if (!MemOpChains.empty())
2964 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2966 if (Subtarget->isPICStyleGOT()) {
2967 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2970 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2971 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2973 // If we are tail calling and generating PIC/GOT style code load the
2974 // address of the callee into ECX. The value in ecx is used as target of
2975 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2976 // for tail calls on PIC/GOT architectures. Normally we would just put the
2977 // address of GOT into ebx and then call target@PLT. But for tail calls
2978 // ebx would be restored (since ebx is callee saved) before jumping to the
2981 // Note: The actual moving to ECX is done further down.
2982 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2983 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2984 !G->getGlobal()->hasProtectedVisibility())
2985 Callee = LowerGlobalAddress(Callee, DAG);
2986 else if (isa<ExternalSymbolSDNode>(Callee))
2987 Callee = LowerExternalSymbol(Callee, DAG);
2991 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2992 // From AMD64 ABI document:
2993 // For calls that may call functions that use varargs or stdargs
2994 // (prototype-less calls or calls to functions containing ellipsis (...) in
2995 // the declaration) %al is used as hidden argument to specify the number
2996 // of SSE registers used. The contents of %al do not need to match exactly
2997 // the number of registers, but must be an ubound on the number of SSE
2998 // registers used and is in the range 0 - 8 inclusive.
3000 // Count the number of XMM registers allocated.
3001 static const MCPhysReg XMMArgRegs[] = {
3002 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3003 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3005 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
3006 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3007 && "SSE registers cannot be used when SSE is disabled");
3009 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3010 DAG.getConstant(NumXMMRegs, MVT::i8)));
3013 if (isVarArg && IsMustTail) {
3014 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3015 for (const auto &F : Forwards) {
3016 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3017 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3021 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3022 // don't need this because the eligibility check rejects calls that require
3023 // shuffling arguments passed in memory.
3024 if (!IsSibcall && isTailCall) {
3025 // Force all the incoming stack arguments to be loaded from the stack
3026 // before any new outgoing arguments are stored to the stack, because the
3027 // outgoing stack slots may alias the incoming argument stack slots, and
3028 // the alias isn't otherwise explicit. This is slightly more conservative
3029 // than necessary, because it means that each store effectively depends
3030 // on every argument instead of just those arguments it would clobber.
3031 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3033 SmallVector<SDValue, 8> MemOpChains2;
3036 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3037 CCValAssign &VA = ArgLocs[i];
3040 assert(VA.isMemLoc());
3041 SDValue Arg = OutVals[i];
3042 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3043 // Skip inalloca arguments. They don't require any work.
3044 if (Flags.isInAlloca())
3046 // Create frame index.
3047 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3048 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3049 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3050 FIN = DAG.getFrameIndex(FI, getPointerTy());
3052 if (Flags.isByVal()) {
3053 // Copy relative to framepointer.
3054 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3055 if (!StackPtr.getNode())
3056 StackPtr = DAG.getCopyFromReg(Chain, dl,
3057 RegInfo->getStackRegister(),
3059 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3061 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3065 // Store relative to framepointer.
3066 MemOpChains2.push_back(
3067 DAG.getStore(ArgChain, dl, Arg, FIN,
3068 MachinePointerInfo::getFixedStack(FI),
3073 if (!MemOpChains2.empty())
3074 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3076 // Store the return address to the appropriate stack slot.
3077 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3078 getPointerTy(), RegInfo->getSlotSize(),
3082 // Build a sequence of copy-to-reg nodes chained together with token chain
3083 // and flag operands which copy the outgoing args into registers.
3085 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3086 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3087 RegsToPass[i].second, InFlag);
3088 InFlag = Chain.getValue(1);
3091 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3092 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3093 // In the 64-bit large code model, we have to make all calls
3094 // through a register, since the call instruction's 32-bit
3095 // pc-relative offset may not be large enough to hold the whole
3097 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3098 // If the callee is a GlobalAddress node (quite common, every direct call
3099 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3101 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3103 // We should use extra load for direct calls to dllimported functions in
3105 const GlobalValue *GV = G->getGlobal();
3106 if (!GV->hasDLLImportStorageClass()) {
3107 unsigned char OpFlags = 0;
3108 bool ExtraLoad = false;
3109 unsigned WrapperKind = ISD::DELETED_NODE;
3111 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3112 // external symbols most go through the PLT in PIC mode. If the symbol
3113 // has hidden or protected visibility, or if it is static or local, then
3114 // we don't need to use the PLT - we can directly call it.
3115 if (Subtarget->isTargetELF() &&
3116 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3117 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3118 OpFlags = X86II::MO_PLT;
3119 } else if (Subtarget->isPICStyleStubAny() &&
3120 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3121 (!Subtarget->getTargetTriple().isMacOSX() ||
3122 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3123 // PC-relative references to external symbols should go through $stub,
3124 // unless we're building with the leopard linker or later, which
3125 // automatically synthesizes these stubs.
3126 OpFlags = X86II::MO_DARWIN_STUB;
3127 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3128 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3129 // If the function is marked as non-lazy, generate an indirect call
3130 // which loads from the GOT directly. This avoids runtime overhead
3131 // at the cost of eager binding (and one extra byte of encoding).
3132 OpFlags = X86II::MO_GOTPCREL;
3133 WrapperKind = X86ISD::WrapperRIP;
3137 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3138 G->getOffset(), OpFlags);
3140 // Add a wrapper if needed.
3141 if (WrapperKind != ISD::DELETED_NODE)
3142 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3143 // Add extra indirection if needed.
3145 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3146 MachinePointerInfo::getGOT(),
3147 false, false, false, 0);
3149 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3150 unsigned char OpFlags = 0;
3152 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3153 // external symbols should go through the PLT.
3154 if (Subtarget->isTargetELF() &&
3155 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3156 OpFlags = X86II::MO_PLT;
3157 } else if (Subtarget->isPICStyleStubAny() &&
3158 (!Subtarget->getTargetTriple().isMacOSX() ||
3159 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3160 // PC-relative references to external symbols should go through $stub,
3161 // unless we're building with the leopard linker or later, which
3162 // automatically synthesizes these stubs.
3163 OpFlags = X86II::MO_DARWIN_STUB;
3166 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3168 } else if (Subtarget->isTarget64BitILP32() &&
3169 Callee->getValueType(0) == MVT::i32) {
3170 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3171 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3174 // Returns a chain & a flag for retval copy to use.
3175 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3176 SmallVector<SDValue, 8> Ops;
3178 if (!IsSibcall && isTailCall) {
3179 Chain = DAG.getCALLSEQ_END(Chain,
3180 DAG.getIntPtrConstant(NumBytesToPop, true),
3181 DAG.getIntPtrConstant(0, true), InFlag, dl);
3182 InFlag = Chain.getValue(1);
3185 Ops.push_back(Chain);
3186 Ops.push_back(Callee);
3189 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3191 // Add argument registers to the end of the list so that they are known live
3193 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3194 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3195 RegsToPass[i].second.getValueType()));
3197 // Add a register mask operand representing the call-preserved registers.
3198 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3199 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3200 assert(Mask && "Missing call preserved mask for calling convention");
3201 Ops.push_back(DAG.getRegisterMask(Mask));
3203 if (InFlag.getNode())
3204 Ops.push_back(InFlag);
3208 //// If this is the first return lowered for this function, add the regs
3209 //// to the liveout set for the function.
3210 // This isn't right, although it's probably harmless on x86; liveouts
3211 // should be computed from returns not tail calls. Consider a void
3212 // function making a tail call to a function returning int.
3213 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3216 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3217 InFlag = Chain.getValue(1);
3219 // Create the CALLSEQ_END node.
3220 unsigned NumBytesForCalleeToPop;
3221 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3222 DAG.getTarget().Options.GuaranteedTailCallOpt))
3223 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3224 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3225 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3226 SR == StackStructReturn)
3227 // If this is a call to a struct-return function, the callee
3228 // pops the hidden struct pointer, so we have to push it back.
3229 // This is common for Darwin/X86, Linux & Mingw32 targets.
3230 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3231 NumBytesForCalleeToPop = 4;
3233 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3235 // Returns a flag for retval copy to use.
3237 Chain = DAG.getCALLSEQ_END(Chain,
3238 DAG.getIntPtrConstant(NumBytesToPop, true),
3239 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3242 InFlag = Chain.getValue(1);
3245 // Handle result values, copying them out of physregs into vregs that we
3247 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3248 Ins, dl, DAG, InVals);
3251 //===----------------------------------------------------------------------===//
3252 // Fast Calling Convention (tail call) implementation
3253 //===----------------------------------------------------------------------===//
3255 // Like std call, callee cleans arguments, convention except that ECX is
3256 // reserved for storing the tail called function address. Only 2 registers are
3257 // free for argument passing (inreg). Tail call optimization is performed
3259 // * tailcallopt is enabled
3260 // * caller/callee are fastcc
3261 // On X86_64 architecture with GOT-style position independent code only local
3262 // (within module) calls are supported at the moment.
3263 // To keep the stack aligned according to platform abi the function
3264 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3265 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3266 // If a tail called function callee has more arguments than the caller the
3267 // caller needs to make sure that there is room to move the RETADDR to. This is
3268 // achieved by reserving an area the size of the argument delta right after the
3269 // original RETADDR, but before the saved framepointer or the spilled registers
3270 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3282 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3283 /// for a 16 byte align requirement.
3285 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3286 SelectionDAG& DAG) const {
3287 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3288 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3289 unsigned StackAlignment = TFI.getStackAlignment();
3290 uint64_t AlignMask = StackAlignment - 1;
3291 int64_t Offset = StackSize;
3292 unsigned SlotSize = RegInfo->getSlotSize();
3293 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3294 // Number smaller than 12 so just add the difference.
3295 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3297 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3298 Offset = ((~AlignMask) & Offset) + StackAlignment +
3299 (StackAlignment-SlotSize);
3304 /// MatchingStackOffset - Return true if the given stack call argument is
3305 /// already available in the same position (relatively) of the caller's
3306 /// incoming argument stack.
3308 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3309 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3310 const X86InstrInfo *TII) {
3311 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3313 if (Arg.getOpcode() == ISD::CopyFromReg) {
3314 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3315 if (!TargetRegisterInfo::isVirtualRegister(VR))
3317 MachineInstr *Def = MRI->getVRegDef(VR);
3320 if (!Flags.isByVal()) {
3321 if (!TII->isLoadFromStackSlot(Def, FI))
3324 unsigned Opcode = Def->getOpcode();
3325 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3326 Opcode == X86::LEA64_32r) &&
3327 Def->getOperand(1).isFI()) {
3328 FI = Def->getOperand(1).getIndex();
3329 Bytes = Flags.getByValSize();
3333 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3334 if (Flags.isByVal())
3335 // ByVal argument is passed in as a pointer but it's now being
3336 // dereferenced. e.g.
3337 // define @foo(%struct.X* %A) {
3338 // tail call @bar(%struct.X* byval %A)
3341 SDValue Ptr = Ld->getBasePtr();
3342 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3345 FI = FINode->getIndex();
3346 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3347 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3348 FI = FINode->getIndex();
3349 Bytes = Flags.getByValSize();
3353 assert(FI != INT_MAX);
3354 if (!MFI->isFixedObjectIndex(FI))
3356 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3359 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3360 /// for tail call optimization. Targets which want to do tail call
3361 /// optimization should implement this function.
3363 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3364 CallingConv::ID CalleeCC,
3366 bool isCalleeStructRet,
3367 bool isCallerStructRet,
3369 const SmallVectorImpl<ISD::OutputArg> &Outs,
3370 const SmallVectorImpl<SDValue> &OutVals,
3371 const SmallVectorImpl<ISD::InputArg> &Ins,
3372 SelectionDAG &DAG) const {
3373 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3376 // If -tailcallopt is specified, make fastcc functions tail-callable.
3377 const MachineFunction &MF = DAG.getMachineFunction();
3378 const Function *CallerF = MF.getFunction();
3380 // If the function return type is x86_fp80 and the callee return type is not,
3381 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3382 // perform a tailcall optimization here.
3383 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3386 CallingConv::ID CallerCC = CallerF->getCallingConv();
3387 bool CCMatch = CallerCC == CalleeCC;
3388 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3389 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3391 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3392 if (IsTailCallConvention(CalleeCC) && CCMatch)
3397 // Look for obvious safe cases to perform tail call optimization that do not
3398 // require ABI changes. This is what gcc calls sibcall.
3400 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3401 // emit a special epilogue.
3402 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3403 if (RegInfo->needsStackRealignment(MF))
3406 // Also avoid sibcall optimization if either caller or callee uses struct
3407 // return semantics.
3408 if (isCalleeStructRet || isCallerStructRet)
3411 // An stdcall/thiscall caller is expected to clean up its arguments; the
3412 // callee isn't going to do that.
3413 // FIXME: this is more restrictive than needed. We could produce a tailcall
3414 // when the stack adjustment matches. For example, with a thiscall that takes
3415 // only one argument.
3416 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3417 CallerCC == CallingConv::X86_ThisCall))
3420 // Do not sibcall optimize vararg calls unless all arguments are passed via
3422 if (isVarArg && !Outs.empty()) {
3424 // Optimizing for varargs on Win64 is unlikely to be safe without
3425 // additional testing.
3426 if (IsCalleeWin64 || IsCallerWin64)
3429 SmallVector<CCValAssign, 16> ArgLocs;
3430 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3433 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3434 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3435 if (!ArgLocs[i].isRegLoc())
3439 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3440 // stack. Therefore, if it's not used by the call it is not safe to optimize
3441 // this into a sibcall.
3442 bool Unused = false;
3443 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3450 SmallVector<CCValAssign, 16> RVLocs;
3451 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3453 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3454 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3455 CCValAssign &VA = RVLocs[i];
3456 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3461 // If the calling conventions do not match, then we'd better make sure the
3462 // results are returned in the same way as what the caller expects.
3464 SmallVector<CCValAssign, 16> RVLocs1;
3465 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3467 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3469 SmallVector<CCValAssign, 16> RVLocs2;
3470 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3472 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3474 if (RVLocs1.size() != RVLocs2.size())
3476 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3477 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3479 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3481 if (RVLocs1[i].isRegLoc()) {
3482 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3485 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3491 // If the callee takes no arguments then go on to check the results of the
3493 if (!Outs.empty()) {
3494 // Check if stack adjustment is needed. For now, do not do this if any
3495 // argument is passed on the stack.
3496 SmallVector<CCValAssign, 16> ArgLocs;
3497 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3500 // Allocate shadow area for Win64
3502 CCInfo.AllocateStack(32, 8);
3504 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3505 if (CCInfo.getNextStackOffset()) {
3506 MachineFunction &MF = DAG.getMachineFunction();
3507 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3510 // Check if the arguments are already laid out in the right way as
3511 // the caller's fixed stack objects.
3512 MachineFrameInfo *MFI = MF.getFrameInfo();
3513 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3514 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3515 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3516 CCValAssign &VA = ArgLocs[i];
3517 SDValue Arg = OutVals[i];
3518 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3519 if (VA.getLocInfo() == CCValAssign::Indirect)
3521 if (!VA.isRegLoc()) {
3522 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3529 // If the tailcall address may be in a register, then make sure it's
3530 // possible to register allocate for it. In 32-bit, the call address can
3531 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3532 // callee-saved registers are restored. These happen to be the same
3533 // registers used to pass 'inreg' arguments so watch out for those.
3534 if (!Subtarget->is64Bit() &&
3535 ((!isa<GlobalAddressSDNode>(Callee) &&
3536 !isa<ExternalSymbolSDNode>(Callee)) ||
3537 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3538 unsigned NumInRegs = 0;
3539 // In PIC we need an extra register to formulate the address computation
3541 unsigned MaxInRegs =
3542 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3544 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3545 CCValAssign &VA = ArgLocs[i];
3548 unsigned Reg = VA.getLocReg();
3551 case X86::EAX: case X86::EDX: case X86::ECX:
3552 if (++NumInRegs == MaxInRegs)
3564 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3565 const TargetLibraryInfo *libInfo) const {
3566 return X86::createFastISel(funcInfo, libInfo);
3569 //===----------------------------------------------------------------------===//
3570 // Other Lowering Hooks
3571 //===----------------------------------------------------------------------===//
3573 static bool MayFoldLoad(SDValue Op) {
3574 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3577 static bool MayFoldIntoStore(SDValue Op) {
3578 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3581 static bool isTargetShuffle(unsigned Opcode) {
3583 default: return false;
3584 case X86ISD::BLENDI:
3585 case X86ISD::PSHUFB:
3586 case X86ISD::PSHUFD:
3587 case X86ISD::PSHUFHW:
3588 case X86ISD::PSHUFLW:
3590 case X86ISD::PALIGNR:
3591 case X86ISD::MOVLHPS:
3592 case X86ISD::MOVLHPD:
3593 case X86ISD::MOVHLPS:
3594 case X86ISD::MOVLPS:
3595 case X86ISD::MOVLPD:
3596 case X86ISD::MOVSHDUP:
3597 case X86ISD::MOVSLDUP:
3598 case X86ISD::MOVDDUP:
3601 case X86ISD::UNPCKL:
3602 case X86ISD::UNPCKH:
3603 case X86ISD::VPERMILPI:
3604 case X86ISD::VPERM2X128:
3605 case X86ISD::VPERMI:
3610 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3611 SDValue V1, unsigned TargetMask,
3612 SelectionDAG &DAG) {
3614 default: llvm_unreachable("Unknown x86 shuffle node");
3615 case X86ISD::PSHUFD:
3616 case X86ISD::PSHUFHW:
3617 case X86ISD::PSHUFLW:
3618 case X86ISD::VPERMILPI:
3619 case X86ISD::VPERMI:
3620 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3624 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3625 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3627 default: llvm_unreachable("Unknown x86 shuffle node");
3628 case X86ISD::MOVLHPS:
3629 case X86ISD::MOVLHPD:
3630 case X86ISD::MOVHLPS:
3631 case X86ISD::MOVLPS:
3632 case X86ISD::MOVLPD:
3635 case X86ISD::UNPCKL:
3636 case X86ISD::UNPCKH:
3637 return DAG.getNode(Opc, dl, VT, V1, V2);
3641 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3642 MachineFunction &MF = DAG.getMachineFunction();
3643 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3644 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3645 int ReturnAddrIndex = FuncInfo->getRAIndex();
3647 if (ReturnAddrIndex == 0) {
3648 // Set up a frame object for the return address.
3649 unsigned SlotSize = RegInfo->getSlotSize();
3650 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3653 FuncInfo->setRAIndex(ReturnAddrIndex);
3656 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3659 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3660 bool hasSymbolicDisplacement) {
3661 // Offset should fit into 32 bit immediate field.
3662 if (!isInt<32>(Offset))
3665 // If we don't have a symbolic displacement - we don't have any extra
3667 if (!hasSymbolicDisplacement)
3670 // FIXME: Some tweaks might be needed for medium code model.
3671 if (M != CodeModel::Small && M != CodeModel::Kernel)
3674 // For small code model we assume that latest object is 16MB before end of 31
3675 // bits boundary. We may also accept pretty large negative constants knowing
3676 // that all objects are in the positive half of address space.
3677 if (M == CodeModel::Small && Offset < 16*1024*1024)
3680 // For kernel code model we know that all object resist in the negative half
3681 // of 32bits address space. We may not accept negative offsets, since they may
3682 // be just off and we may accept pretty large positive ones.
3683 if (M == CodeModel::Kernel && Offset >= 0)
3689 /// isCalleePop - Determines whether the callee is required to pop its
3690 /// own arguments. Callee pop is necessary to support tail calls.
3691 bool X86::isCalleePop(CallingConv::ID CallingConv,
3692 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3693 switch (CallingConv) {
3696 case CallingConv::X86_StdCall:
3697 case CallingConv::X86_FastCall:
3698 case CallingConv::X86_ThisCall:
3700 case CallingConv::Fast:
3701 case CallingConv::GHC:
3702 case CallingConv::HiPE:
3709 /// \brief Return true if the condition is an unsigned comparison operation.
3710 static bool isX86CCUnsigned(unsigned X86CC) {
3712 default: llvm_unreachable("Invalid integer condition!");
3713 case X86::COND_E: return true;
3714 case X86::COND_G: return false;
3715 case X86::COND_GE: return false;
3716 case X86::COND_L: return false;
3717 case X86::COND_LE: return false;
3718 case X86::COND_NE: return true;
3719 case X86::COND_B: return true;
3720 case X86::COND_A: return true;
3721 case X86::COND_BE: return true;
3722 case X86::COND_AE: return true;
3724 llvm_unreachable("covered switch fell through?!");
3727 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3728 /// specific condition code, returning the condition code and the LHS/RHS of the
3729 /// comparison to make.
3730 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3731 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3733 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3734 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3735 // X > -1 -> X == 0, jump !sign.
3736 RHS = DAG.getConstant(0, RHS.getValueType());
3737 return X86::COND_NS;
3739 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3740 // X < 0 -> X == 0, jump on sign.
3743 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3745 RHS = DAG.getConstant(0, RHS.getValueType());
3746 return X86::COND_LE;
3750 switch (SetCCOpcode) {
3751 default: llvm_unreachable("Invalid integer condition!");
3752 case ISD::SETEQ: return X86::COND_E;
3753 case ISD::SETGT: return X86::COND_G;
3754 case ISD::SETGE: return X86::COND_GE;
3755 case ISD::SETLT: return X86::COND_L;
3756 case ISD::SETLE: return X86::COND_LE;
3757 case ISD::SETNE: return X86::COND_NE;
3758 case ISD::SETULT: return X86::COND_B;
3759 case ISD::SETUGT: return X86::COND_A;
3760 case ISD::SETULE: return X86::COND_BE;
3761 case ISD::SETUGE: return X86::COND_AE;
3765 // First determine if it is required or is profitable to flip the operands.
3767 // If LHS is a foldable load, but RHS is not, flip the condition.
3768 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3769 !ISD::isNON_EXTLoad(RHS.getNode())) {
3770 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3771 std::swap(LHS, RHS);
3774 switch (SetCCOpcode) {
3780 std::swap(LHS, RHS);
3784 // On a floating point condition, the flags are set as follows:
3786 // 0 | 0 | 0 | X > Y
3787 // 0 | 0 | 1 | X < Y
3788 // 1 | 0 | 0 | X == Y
3789 // 1 | 1 | 1 | unordered
3790 switch (SetCCOpcode) {
3791 default: llvm_unreachable("Condcode should be pre-legalized away");
3793 case ISD::SETEQ: return X86::COND_E;
3794 case ISD::SETOLT: // flipped
3796 case ISD::SETGT: return X86::COND_A;
3797 case ISD::SETOLE: // flipped
3799 case ISD::SETGE: return X86::COND_AE;
3800 case ISD::SETUGT: // flipped
3802 case ISD::SETLT: return X86::COND_B;
3803 case ISD::SETUGE: // flipped
3805 case ISD::SETLE: return X86::COND_BE;
3807 case ISD::SETNE: return X86::COND_NE;
3808 case ISD::SETUO: return X86::COND_P;
3809 case ISD::SETO: return X86::COND_NP;
3811 case ISD::SETUNE: return X86::COND_INVALID;
3815 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3816 /// code. Current x86 isa includes the following FP cmov instructions:
3817 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3818 static bool hasFPCMov(unsigned X86CC) {
3834 /// isFPImmLegal - Returns true if the target can instruction select the
3835 /// specified FP immediate natively. If false, the legalizer will
3836 /// materialize the FP immediate as a load from a constant pool.
3837 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3838 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3839 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3845 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3846 ISD::LoadExtType ExtTy,
3848 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3849 // relocation target a movq or addq instruction: don't let the load shrink.
3850 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3851 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3852 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3853 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3857 /// \brief Returns true if it is beneficial to convert a load of a constant
3858 /// to just the constant itself.
3859 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3861 assert(Ty->isIntegerTy());
3863 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3864 if (BitSize == 0 || BitSize > 64)
3869 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3870 unsigned Index) const {
3871 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3874 return (Index == 0 || Index == ResVT.getVectorNumElements());
3877 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3878 // Speculate cttz only if we can directly use TZCNT.
3879 return Subtarget->hasBMI();
3882 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3883 // Speculate ctlz only if we can directly use LZCNT.
3884 return Subtarget->hasLZCNT();
3887 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3888 /// the specified range (L, H].
3889 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3890 return (Val < 0) || (Val >= Low && Val < Hi);
3893 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3894 /// specified value.
3895 static bool isUndefOrEqual(int Val, int CmpVal) {
3896 return (Val < 0 || Val == CmpVal);
3899 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3900 /// from position Pos and ending in Pos+Size, falls within the specified
3901 /// sequential range (Low, Low+Size]. or is undef.
3902 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3903 unsigned Pos, unsigned Size, int Low) {
3904 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3905 if (!isUndefOrEqual(Mask[i], Low))
3910 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3911 /// the two vector operands have swapped position.
3912 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3913 unsigned NumElems) {
3914 for (unsigned i = 0; i != NumElems; ++i) {
3918 else if (idx < (int)NumElems)
3919 Mask[i] = idx + NumElems;
3921 Mask[i] = idx - NumElems;
3925 /// isVEXTRACTIndex - Return true if the specified
3926 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3927 /// suitable for instruction that extract 128 or 256 bit vectors
3928 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3929 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3930 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3933 // The index should be aligned on a vecWidth-bit boundary.
3935 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3937 MVT VT = N->getSimpleValueType(0);
3938 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3939 bool Result = (Index * ElSize) % vecWidth == 0;
3944 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3945 /// operand specifies a subvector insert that is suitable for input to
3946 /// insertion of 128 or 256-bit subvectors
3947 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3948 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3949 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3951 // The index should be aligned on a vecWidth-bit boundary.
3953 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3955 MVT VT = N->getSimpleValueType(0);
3956 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3957 bool Result = (Index * ElSize) % vecWidth == 0;
3962 bool X86::isVINSERT128Index(SDNode *N) {
3963 return isVINSERTIndex(N, 128);
3966 bool X86::isVINSERT256Index(SDNode *N) {
3967 return isVINSERTIndex(N, 256);
3970 bool X86::isVEXTRACT128Index(SDNode *N) {
3971 return isVEXTRACTIndex(N, 128);
3974 bool X86::isVEXTRACT256Index(SDNode *N) {
3975 return isVEXTRACTIndex(N, 256);
3978 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3979 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3980 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3981 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3984 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3986 MVT VecVT = N->getOperand(0).getSimpleValueType();
3987 MVT ElVT = VecVT.getVectorElementType();
3989 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3990 return Index / NumElemsPerChunk;
3993 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3994 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3995 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3996 llvm_unreachable("Illegal insert subvector for VINSERT");
3999 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4001 MVT VecVT = N->getSimpleValueType(0);
4002 MVT ElVT = VecVT.getVectorElementType();
4004 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4005 return Index / NumElemsPerChunk;
4008 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4009 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4010 /// and VINSERTI128 instructions.
4011 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4012 return getExtractVEXTRACTImmediate(N, 128);
4015 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4016 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4017 /// and VINSERTI64x4 instructions.
4018 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4019 return getExtractVEXTRACTImmediate(N, 256);
4022 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4023 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4024 /// and VINSERTI128 instructions.
4025 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4026 return getInsertVINSERTImmediate(N, 128);
4029 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4030 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4031 /// and VINSERTI64x4 instructions.
4032 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4033 return getInsertVINSERTImmediate(N, 256);
4036 /// isZero - Returns true if Elt is a constant integer zero
4037 static bool isZero(SDValue V) {
4038 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4039 return C && C->isNullValue();
4042 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4044 bool X86::isZeroNode(SDValue Elt) {
4047 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4048 return CFP->getValueAPF().isPosZero();
4052 /// getZeroVector - Returns a vector of specified type with all zero elements.
4054 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4055 SelectionDAG &DAG, SDLoc dl) {
4056 assert(VT.isVector() && "Expected a vector type");
4058 // Always build SSE zero vectors as <4 x i32> bitcasted
4059 // to their dest type. This ensures they get CSE'd.
4061 if (VT.is128BitVector()) { // SSE
4062 if (Subtarget->hasSSE2()) { // SSE2
4063 SDValue Cst = DAG.getConstant(0, MVT::i32);
4064 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4066 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4067 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4069 } else if (VT.is256BitVector()) { // AVX
4070 if (Subtarget->hasInt256()) { // AVX2
4071 SDValue Cst = DAG.getConstant(0, MVT::i32);
4072 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4073 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4075 // 256-bit logic and arithmetic instructions in AVX are all
4076 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4077 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4078 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4079 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4081 } else if (VT.is512BitVector()) { // AVX-512
4082 SDValue Cst = DAG.getConstant(0, MVT::i32);
4083 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4084 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4085 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4086 } else if (VT.getScalarType() == MVT::i1) {
4087 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4088 SDValue Cst = DAG.getConstant(0, MVT::i1);
4089 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4090 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4092 llvm_unreachable("Unexpected vector type");
4094 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4097 /// getOnesVector - Returns a vector of specified type with all bits set.
4098 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4099 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4100 /// Then bitcast to their original type, ensuring they get CSE'd.
4101 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4103 assert(VT.isVector() && "Expected a vector type");
4105 SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4107 if (VT.is256BitVector()) {
4108 if (HasInt256) { // AVX2
4109 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4110 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4112 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4113 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4115 } else if (VT.is128BitVector()) {
4116 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4118 llvm_unreachable("Unexpected vector type");
4120 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4123 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4124 /// operation of specified width.
4125 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4127 unsigned NumElems = VT.getVectorNumElements();
4128 SmallVector<int, 8> Mask;
4129 Mask.push_back(NumElems);
4130 for (unsigned i = 1; i != NumElems; ++i)
4132 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4135 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4136 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4138 unsigned NumElems = VT.getVectorNumElements();
4139 SmallVector<int, 8> Mask;
4140 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4142 Mask.push_back(i + NumElems);
4144 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4147 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4148 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4150 unsigned NumElems = VT.getVectorNumElements();
4151 SmallVector<int, 8> Mask;
4152 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4153 Mask.push_back(i + Half);
4154 Mask.push_back(i + NumElems + Half);
4156 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4159 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4160 /// vector of zero or undef vector. This produces a shuffle where the low
4161 /// element of V2 is swizzled into the zero/undef vector, landing at element
4162 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4163 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4165 const X86Subtarget *Subtarget,
4166 SelectionDAG &DAG) {
4167 MVT VT = V2.getSimpleValueType();
4169 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4170 unsigned NumElems = VT.getVectorNumElements();
4171 SmallVector<int, 16> MaskVec;
4172 for (unsigned i = 0; i != NumElems; ++i)
4173 // If this is the insertion idx, put the low elt of V2 here.
4174 MaskVec.push_back(i == Idx ? NumElems : i);
4175 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4178 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4179 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4180 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4181 /// shuffles which use a single input multiple times, and in those cases it will
4182 /// adjust the mask to only have indices within that single input.
4183 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4184 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4185 unsigned NumElems = VT.getVectorNumElements();
4189 bool IsFakeUnary = false;
4190 switch(N->getOpcode()) {
4191 case X86ISD::BLENDI:
4192 ImmN = N->getOperand(N->getNumOperands()-1);
4193 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196 ImmN = N->getOperand(N->getNumOperands()-1);
4197 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4198 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4200 case X86ISD::UNPCKH:
4201 DecodeUNPCKHMask(VT, Mask);
4202 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4204 case X86ISD::UNPCKL:
4205 DecodeUNPCKLMask(VT, Mask);
4206 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4208 case X86ISD::MOVHLPS:
4209 DecodeMOVHLPSMask(NumElems, Mask);
4210 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4212 case X86ISD::MOVLHPS:
4213 DecodeMOVLHPSMask(NumElems, Mask);
4214 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4216 case X86ISD::PALIGNR:
4217 ImmN = N->getOperand(N->getNumOperands()-1);
4218 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4220 case X86ISD::PSHUFD:
4221 case X86ISD::VPERMILPI:
4222 ImmN = N->getOperand(N->getNumOperands()-1);
4223 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4226 case X86ISD::PSHUFHW:
4227 ImmN = N->getOperand(N->getNumOperands()-1);
4228 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4231 case X86ISD::PSHUFLW:
4232 ImmN = N->getOperand(N->getNumOperands()-1);
4233 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4236 case X86ISD::PSHUFB: {
4238 SDValue MaskNode = N->getOperand(1);
4239 while (MaskNode->getOpcode() == ISD::BITCAST)
4240 MaskNode = MaskNode->getOperand(0);
4242 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4243 // If we have a build-vector, then things are easy.
4244 EVT VT = MaskNode.getValueType();
4245 assert(VT.isVector() &&
4246 "Can't produce a non-vector with a build_vector!");
4247 if (!VT.isInteger())
4250 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4252 SmallVector<uint64_t, 32> RawMask;
4253 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4254 SDValue Op = MaskNode->getOperand(i);
4255 if (Op->getOpcode() == ISD::UNDEF) {
4256 RawMask.push_back((uint64_t)SM_SentinelUndef);
4259 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4262 APInt MaskElement = CN->getAPIntValue();
4264 // We now have to decode the element which could be any integer size and
4265 // extract each byte of it.
4266 for (int j = 0; j < NumBytesPerElement; ++j) {
4267 // Note that this is x86 and so always little endian: the low byte is
4268 // the first byte of the mask.
4269 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4270 MaskElement = MaskElement.lshr(8);
4273 DecodePSHUFBMask(RawMask, Mask);
4277 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4281 SDValue Ptr = MaskLoad->getBasePtr();
4282 if (Ptr->getOpcode() == X86ISD::Wrapper)
4283 Ptr = Ptr->getOperand(0);
4285 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4286 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4289 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4290 DecodePSHUFBMask(C, Mask);
4298 case X86ISD::VPERMI:
4299 ImmN = N->getOperand(N->getNumOperands()-1);
4300 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4305 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4307 case X86ISD::VPERM2X128:
4308 ImmN = N->getOperand(N->getNumOperands()-1);
4309 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4310 if (Mask.empty()) return false;
4312 case X86ISD::MOVSLDUP:
4313 DecodeMOVSLDUPMask(VT, Mask);
4316 case X86ISD::MOVSHDUP:
4317 DecodeMOVSHDUPMask(VT, Mask);
4320 case X86ISD::MOVDDUP:
4321 DecodeMOVDDUPMask(VT, Mask);
4324 case X86ISD::MOVLHPD:
4325 case X86ISD::MOVLPD:
4326 case X86ISD::MOVLPS:
4327 // Not yet implemented
4329 default: llvm_unreachable("unknown target shuffle node");
4332 // If we have a fake unary shuffle, the shuffle mask is spread across two
4333 // inputs that are actually the same node. Re-map the mask to always point
4334 // into the first input.
4337 if (M >= (int)Mask.size())
4343 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4344 /// element of the result of the vector shuffle.
4345 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4348 return SDValue(); // Limit search depth.
4350 SDValue V = SDValue(N, 0);
4351 EVT VT = V.getValueType();
4352 unsigned Opcode = V.getOpcode();
4354 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4355 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4356 int Elt = SV->getMaskElt(Index);
4359 return DAG.getUNDEF(VT.getVectorElementType());
4361 unsigned NumElems = VT.getVectorNumElements();
4362 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4363 : SV->getOperand(1);
4364 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4367 // Recurse into target specific vector shuffles to find scalars.
4368 if (isTargetShuffle(Opcode)) {
4369 MVT ShufVT = V.getSimpleValueType();
4370 unsigned NumElems = ShufVT.getVectorNumElements();
4371 SmallVector<int, 16> ShuffleMask;
4374 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4377 int Elt = ShuffleMask[Index];
4379 return DAG.getUNDEF(ShufVT.getVectorElementType());
4381 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4383 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4387 // Actual nodes that may contain scalar elements
4388 if (Opcode == ISD::BITCAST) {
4389 V = V.getOperand(0);
4390 EVT SrcVT = V.getValueType();
4391 unsigned NumElems = VT.getVectorNumElements();
4393 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4397 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4398 return (Index == 0) ? V.getOperand(0)
4399 : DAG.getUNDEF(VT.getVectorElementType());
4401 if (V.getOpcode() == ISD::BUILD_VECTOR)
4402 return V.getOperand(Index);
4407 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4409 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4410 unsigned NumNonZero, unsigned NumZero,
4412 const X86Subtarget* Subtarget,
4413 const TargetLowering &TLI) {
4420 for (unsigned i = 0; i < 16; ++i) {
4421 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4422 if (ThisIsNonZero && First) {
4424 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4426 V = DAG.getUNDEF(MVT::v8i16);
4431 SDValue ThisElt, LastElt;
4432 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4433 if (LastIsNonZero) {
4434 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4435 MVT::i16, Op.getOperand(i-1));
4437 if (ThisIsNonZero) {
4438 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4439 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4440 ThisElt, DAG.getConstant(8, MVT::i8));
4442 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4446 if (ThisElt.getNode())
4447 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4448 DAG.getIntPtrConstant(i/2));
4452 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4455 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4457 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4458 unsigned NumNonZero, unsigned NumZero,
4460 const X86Subtarget* Subtarget,
4461 const TargetLowering &TLI) {
4468 for (unsigned i = 0; i < 8; ++i) {
4469 bool isNonZero = (NonZeros & (1 << i)) != 0;
4473 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4475 V = DAG.getUNDEF(MVT::v8i16);
4478 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4479 MVT::v8i16, V, Op.getOperand(i),
4480 DAG.getIntPtrConstant(i));
4487 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4488 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4489 const X86Subtarget *Subtarget,
4490 const TargetLowering &TLI) {
4491 // Find all zeroable elements.
4492 std::bitset<4> Zeroable;
4493 for (int i=0; i < 4; ++i) {
4494 SDValue Elt = Op->getOperand(i);
4495 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4497 assert(Zeroable.size() - Zeroable.count() > 1 &&
4498 "We expect at least two non-zero elements!");
4500 // We only know how to deal with build_vector nodes where elements are either
4501 // zeroable or extract_vector_elt with constant index.
4502 SDValue FirstNonZero;
4503 unsigned FirstNonZeroIdx;
4504 for (unsigned i=0; i < 4; ++i) {
4507 SDValue Elt = Op->getOperand(i);
4508 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4509 !isa<ConstantSDNode>(Elt.getOperand(1)))
4511 // Make sure that this node is extracting from a 128-bit vector.
4512 MVT VT = Elt.getOperand(0).getSimpleValueType();
4513 if (!VT.is128BitVector())
4515 if (!FirstNonZero.getNode()) {
4517 FirstNonZeroIdx = i;
4521 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4522 SDValue V1 = FirstNonZero.getOperand(0);
4523 MVT VT = V1.getSimpleValueType();
4525 // See if this build_vector can be lowered as a blend with zero.
4527 unsigned EltMaskIdx, EltIdx;
4529 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4530 if (Zeroable[EltIdx]) {
4531 // The zero vector will be on the right hand side.
4532 Mask[EltIdx] = EltIdx+4;
4536 Elt = Op->getOperand(EltIdx);
4537 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4538 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4539 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4541 Mask[EltIdx] = EltIdx;
4545 // Let the shuffle legalizer deal with blend operations.
4546 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4547 if (V1.getSimpleValueType() != VT)
4548 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4549 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4552 // See if we can lower this build_vector to a INSERTPS.
4553 if (!Subtarget->hasSSE41())
4556 SDValue V2 = Elt.getOperand(0);
4557 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4560 bool CanFold = true;
4561 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4565 SDValue Current = Op->getOperand(i);
4566 SDValue SrcVector = Current->getOperand(0);
4569 CanFold = SrcVector == V1 &&
4570 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4576 assert(V1.getNode() && "Expected at least two non-zero elements!");
4577 if (V1.getSimpleValueType() != MVT::v4f32)
4578 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4579 if (V2.getSimpleValueType() != MVT::v4f32)
4580 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4582 // Ok, we can emit an INSERTPS instruction.
4583 unsigned ZMask = Zeroable.to_ulong();
4585 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4586 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4587 SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4588 DAG.getIntPtrConstant(InsertPSMask));
4589 return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4592 /// Return a vector logical shift node.
4593 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4594 unsigned NumBits, SelectionDAG &DAG,
4595 const TargetLowering &TLI, SDLoc dl) {
4596 assert(VT.is128BitVector() && "Unknown type for VShift");
4597 MVT ShVT = MVT::v2i64;
4598 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4599 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4600 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4601 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4602 SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4603 return DAG.getNode(ISD::BITCAST, dl, VT,
4604 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4608 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4610 // Check if the scalar load can be widened into a vector load. And if
4611 // the address is "base + cst" see if the cst can be "absorbed" into
4612 // the shuffle mask.
4613 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4614 SDValue Ptr = LD->getBasePtr();
4615 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4617 EVT PVT = LD->getValueType(0);
4618 if (PVT != MVT::i32 && PVT != MVT::f32)
4623 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4624 FI = FINode->getIndex();
4626 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4627 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4628 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4629 Offset = Ptr.getConstantOperandVal(1);
4630 Ptr = Ptr.getOperand(0);
4635 // FIXME: 256-bit vector instructions don't require a strict alignment,
4636 // improve this code to support it better.
4637 unsigned RequiredAlign = VT.getSizeInBits()/8;
4638 SDValue Chain = LD->getChain();
4639 // Make sure the stack object alignment is at least 16 or 32.
4640 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4641 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4642 if (MFI->isFixedObjectIndex(FI)) {
4643 // Can't change the alignment. FIXME: It's possible to compute
4644 // the exact stack offset and reference FI + adjust offset instead.
4645 // If someone *really* cares about this. That's the way to implement it.
4648 MFI->setObjectAlignment(FI, RequiredAlign);
4652 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4653 // Ptr + (Offset & ~15).
4656 if ((Offset % RequiredAlign) & 3)
4658 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4660 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4661 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4663 int EltNo = (Offset - StartOffset) >> 2;
4664 unsigned NumElems = VT.getVectorNumElements();
4666 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4667 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4668 LD->getPointerInfo().getWithOffset(StartOffset),
4669 false, false, false, 0);
4671 SmallVector<int, 8> Mask(NumElems, EltNo);
4673 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4679 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4680 /// elements can be replaced by a single large load which has the same value as
4681 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4683 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4685 /// FIXME: we'd also like to handle the case where the last elements are zero
4686 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4687 /// There's even a handy isZeroNode for that purpose.
4688 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4689 SDLoc &DL, SelectionDAG &DAG,
4690 bool isAfterLegalize) {
4691 unsigned NumElems = Elts.size();
4693 LoadSDNode *LDBase = nullptr;
4694 unsigned LastLoadedElt = -1U;
4696 // For each element in the initializer, see if we've found a load or an undef.
4697 // If we don't find an initial load element, or later load elements are
4698 // non-consecutive, bail out.
4699 for (unsigned i = 0; i < NumElems; ++i) {
4700 SDValue Elt = Elts[i];
4701 // Look through a bitcast.
4702 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4703 Elt = Elt.getOperand(0);
4704 if (!Elt.getNode() ||
4705 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4708 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4710 LDBase = cast<LoadSDNode>(Elt.getNode());
4714 if (Elt.getOpcode() == ISD::UNDEF)
4717 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4718 EVT LdVT = Elt.getValueType();
4719 // Each loaded element must be the correct fractional portion of the
4720 // requested vector load.
4721 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4723 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4728 // If we have found an entire vector of loads and undefs, then return a large
4729 // load of the entire vector width starting at the base pointer. If we found
4730 // consecutive loads for the low half, generate a vzext_load node.
4731 if (LastLoadedElt == NumElems - 1) {
4732 assert(LDBase && "Did not find base load for merging consecutive loads");
4733 EVT EltVT = LDBase->getValueType(0);
4734 // Ensure that the input vector size for the merged loads matches the
4735 // cumulative size of the input elements.
4736 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4739 if (isAfterLegalize &&
4740 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4743 SDValue NewLd = SDValue();
4745 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4746 LDBase->getPointerInfo(), LDBase->isVolatile(),
4747 LDBase->isNonTemporal(), LDBase->isInvariant(),
4748 LDBase->getAlignment());
4750 if (LDBase->hasAnyUseOfValue(1)) {
4751 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4753 SDValue(NewLd.getNode(), 1));
4754 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4755 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4756 SDValue(NewLd.getNode(), 1));
4762 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4763 //of a v4i32 / v4f32. It's probably worth generalizing.
4764 EVT EltVT = VT.getVectorElementType();
4765 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4766 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4767 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4768 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4770 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4771 LDBase->getPointerInfo(),
4772 LDBase->getAlignment(),
4773 false/*isVolatile*/, true/*ReadMem*/,
4776 // Make sure the newly-created LOAD is in the same position as LDBase in
4777 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4778 // update uses of LDBase's output chain to use the TokenFactor.
4779 if (LDBase->hasAnyUseOfValue(1)) {
4780 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4781 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4782 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4783 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4784 SDValue(ResNode.getNode(), 1));
4787 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4792 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4793 /// to generate a splat value for the following cases:
4794 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4795 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4796 /// a scalar load, or a constant.
4797 /// The VBROADCAST node is returned when a pattern is found,
4798 /// or SDValue() otherwise.
4799 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4800 SelectionDAG &DAG) {
4801 // VBROADCAST requires AVX.
4802 // TODO: Splats could be generated for non-AVX CPUs using SSE
4803 // instructions, but there's less potential gain for only 128-bit vectors.
4804 if (!Subtarget->hasAVX())
4807 MVT VT = Op.getSimpleValueType();
4810 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4811 "Unsupported vector type for broadcast.");
4816 switch (Op.getOpcode()) {
4818 // Unknown pattern found.
4821 case ISD::BUILD_VECTOR: {
4822 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4823 BitVector UndefElements;
4824 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4826 // We need a splat of a single value to use broadcast, and it doesn't
4827 // make any sense if the value is only in one element of the vector.
4828 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4832 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4833 Ld.getOpcode() == ISD::ConstantFP);
4835 // Make sure that all of the users of a non-constant load are from the
4836 // BUILD_VECTOR node.
4837 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4842 case ISD::VECTOR_SHUFFLE: {
4843 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4845 // Shuffles must have a splat mask where the first element is
4847 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4850 SDValue Sc = Op.getOperand(0);
4851 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4852 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4854 if (!Subtarget->hasInt256())
4857 // Use the register form of the broadcast instruction available on AVX2.
4858 if (VT.getSizeInBits() >= 256)
4859 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4860 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4863 Ld = Sc.getOperand(0);
4864 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4865 Ld.getOpcode() == ISD::ConstantFP);
4867 // The scalar_to_vector node and the suspected
4868 // load node must have exactly one user.
4869 // Constants may have multiple users.
4871 // AVX-512 has register version of the broadcast
4872 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4873 Ld.getValueType().getSizeInBits() >= 32;
4874 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4881 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4882 bool IsGE256 = (VT.getSizeInBits() >= 256);
4884 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4885 // instruction to save 8 or more bytes of constant pool data.
4886 // TODO: If multiple splats are generated to load the same constant,
4887 // it may be detrimental to overall size. There needs to be a way to detect
4888 // that condition to know if this is truly a size win.
4889 const Function *F = DAG.getMachineFunction().getFunction();
4890 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4892 // Handle broadcasting a single constant scalar from the constant pool
4894 // On Sandybridge (no AVX2), it is still better to load a constant vector
4895 // from the constant pool and not to broadcast it from a scalar.
4896 // But override that restriction when optimizing for size.
4897 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4898 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4899 EVT CVT = Ld.getValueType();
4900 assert(!CVT.isVector() && "Must not broadcast a vector type");
4902 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4903 // For size optimization, also splat v2f64 and v2i64, and for size opt
4904 // with AVX2, also splat i8 and i16.
4905 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4906 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4907 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4908 const Constant *C = nullptr;
4909 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4910 C = CI->getConstantIntValue();
4911 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4912 C = CF->getConstantFPValue();
4914 assert(C && "Invalid constant type");
4916 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4917 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4918 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4919 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4920 MachinePointerInfo::getConstantPool(),
4921 false, false, false, Alignment);
4923 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4927 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4929 // Handle AVX2 in-register broadcasts.
4930 if (!IsLoad && Subtarget->hasInt256() &&
4931 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4932 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4934 // The scalar source must be a normal load.
4938 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4939 (Subtarget->hasVLX() && ScalarSize == 64))
4940 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4942 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4943 // double since there is no vbroadcastsd xmm
4944 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4945 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4946 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4949 // Unsupported broadcast.
4953 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4954 /// underlying vector and index.
4956 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4958 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4960 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4961 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4964 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4966 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4968 // (extract_vector_elt (vector_shuffle<2,u,u,u>
4969 // (extract_subvector (v8f32 %vreg0), Constant<4>),
4972 // In this case the vector is the extract_subvector expression and the index
4973 // is 2, as specified by the shuffle.
4974 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4975 SDValue ShuffleVec = SVOp->getOperand(0);
4976 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4977 assert(ShuffleVecVT.getVectorElementType() ==
4978 ExtractedFromVec.getSimpleValueType().getVectorElementType());
4980 int ShuffleIdx = SVOp->getMaskElt(Idx);
4981 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4982 ExtractedFromVec = ShuffleVec;
4988 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4989 MVT VT = Op.getSimpleValueType();
4991 // Skip if insert_vec_elt is not supported.
4992 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4993 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4997 unsigned NumElems = Op.getNumOperands();
5001 SmallVector<unsigned, 4> InsertIndices;
5002 SmallVector<int, 8> Mask(NumElems, -1);
5004 for (unsigned i = 0; i != NumElems; ++i) {
5005 unsigned Opc = Op.getOperand(i).getOpcode();
5007 if (Opc == ISD::UNDEF)
5010 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5011 // Quit if more than 1 elements need inserting.
5012 if (InsertIndices.size() > 1)
5015 InsertIndices.push_back(i);
5019 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5020 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5021 // Quit if non-constant index.
5022 if (!isa<ConstantSDNode>(ExtIdx))
5024 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5026 // Quit if extracted from vector of different type.
5027 if (ExtractedFromVec.getValueType() != VT)
5030 if (!VecIn1.getNode())
5031 VecIn1 = ExtractedFromVec;
5032 else if (VecIn1 != ExtractedFromVec) {
5033 if (!VecIn2.getNode())
5034 VecIn2 = ExtractedFromVec;
5035 else if (VecIn2 != ExtractedFromVec)
5036 // Quit if more than 2 vectors to shuffle
5040 if (ExtractedFromVec == VecIn1)
5042 else if (ExtractedFromVec == VecIn2)
5043 Mask[i] = Idx + NumElems;
5046 if (!VecIn1.getNode())
5049 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5050 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5051 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5052 unsigned Idx = InsertIndices[i];
5053 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5054 DAG.getIntPtrConstant(Idx));
5060 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5062 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5064 MVT VT = Op.getSimpleValueType();
5065 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5066 "Unexpected type in LowerBUILD_VECTORvXi1!");
5069 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5070 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5071 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5072 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5075 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5076 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5077 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5078 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5081 bool AllContants = true;
5082 uint64_t Immediate = 0;
5083 int NonConstIdx = -1;
5084 bool IsSplat = true;
5085 unsigned NumNonConsts = 0;
5086 unsigned NumConsts = 0;
5087 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5088 SDValue In = Op.getOperand(idx);
5089 if (In.getOpcode() == ISD::UNDEF)
5091 if (!isa<ConstantSDNode>(In)) {
5092 AllContants = false;
5097 if (cast<ConstantSDNode>(In)->getZExtValue())
5098 Immediate |= (1ULL << idx);
5100 if (In != Op.getOperand(0))
5105 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5106 DAG.getConstant(Immediate, MVT::i16));
5107 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5108 DAG.getIntPtrConstant(0));
5111 if (NumNonConsts == 1 && NonConstIdx != 0) {
5114 SDValue VecAsImm = DAG.getConstant(Immediate,
5115 MVT::getIntegerVT(VT.getSizeInBits()));
5116 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5119 DstVec = DAG.getUNDEF(VT);
5120 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5121 Op.getOperand(NonConstIdx),
5122 DAG.getIntPtrConstant(NonConstIdx));
5124 if (!IsSplat && (NonConstIdx != 0))
5125 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5126 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5129 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5130 DAG.getConstant(-1, SelectVT),
5131 DAG.getConstant(0, SelectVT));
5133 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5134 DAG.getConstant((Immediate | 1), SelectVT),
5135 DAG.getConstant(Immediate, SelectVT));
5136 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5139 /// \brief Return true if \p N implements a horizontal binop and return the
5140 /// operands for the horizontal binop into V0 and V1.
5142 /// This is a helper function of PerformBUILD_VECTORCombine.
5143 /// This function checks that the build_vector \p N in input implements a
5144 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5145 /// operation to match.
5146 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5147 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5148 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5151 /// This function only analyzes elements of \p N whose indices are
5152 /// in range [BaseIdx, LastIdx).
5153 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5155 unsigned BaseIdx, unsigned LastIdx,
5156 SDValue &V0, SDValue &V1) {
5157 EVT VT = N->getValueType(0);
5159 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5160 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5161 "Invalid Vector in input!");
5163 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5164 bool CanFold = true;
5165 unsigned ExpectedVExtractIdx = BaseIdx;
5166 unsigned NumElts = LastIdx - BaseIdx;
5167 V0 = DAG.getUNDEF(VT);
5168 V1 = DAG.getUNDEF(VT);
5170 // Check if N implements a horizontal binop.
5171 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5172 SDValue Op = N->getOperand(i + BaseIdx);
5175 if (Op->getOpcode() == ISD::UNDEF) {
5176 // Update the expected vector extract index.
5177 if (i * 2 == NumElts)
5178 ExpectedVExtractIdx = BaseIdx;
5179 ExpectedVExtractIdx += 2;
5183 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5188 SDValue Op0 = Op.getOperand(0);
5189 SDValue Op1 = Op.getOperand(1);
5191 // Try to match the following pattern:
5192 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5193 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5194 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5195 Op0.getOperand(0) == Op1.getOperand(0) &&
5196 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5197 isa<ConstantSDNode>(Op1.getOperand(1)));
5201 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5202 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5204 if (i * 2 < NumElts) {
5205 if (V0.getOpcode() == ISD::UNDEF)
5206 V0 = Op0.getOperand(0);
5208 if (V1.getOpcode() == ISD::UNDEF)
5209 V1 = Op0.getOperand(0);
5210 if (i * 2 == NumElts)
5211 ExpectedVExtractIdx = BaseIdx;
5214 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5215 if (I0 == ExpectedVExtractIdx)
5216 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5217 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5218 // Try to match the following dag sequence:
5219 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5220 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5224 ExpectedVExtractIdx += 2;
5230 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5231 /// a concat_vector.
5233 /// This is a helper function of PerformBUILD_VECTORCombine.
5234 /// This function expects two 256-bit vectors called V0 and V1.
5235 /// At first, each vector is split into two separate 128-bit vectors.
5236 /// Then, the resulting 128-bit vectors are used to implement two
5237 /// horizontal binary operations.
5239 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5241 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5242 /// the two new horizontal binop.
5243 /// When Mode is set, the first horizontal binop dag node would take as input
5244 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5245 /// horizontal binop dag node would take as input the lower 128-bit of V1
5246 /// and the upper 128-bit of V1.
5248 /// HADD V0_LO, V0_HI
5249 /// HADD V1_LO, V1_HI
5251 /// Otherwise, the first horizontal binop dag node takes as input the lower
5252 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5253 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5255 /// HADD V0_LO, V1_LO
5256 /// HADD V0_HI, V1_HI
5258 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5259 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5260 /// the upper 128-bits of the result.
5261 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5262 SDLoc DL, SelectionDAG &DAG,
5263 unsigned X86Opcode, bool Mode,
5264 bool isUndefLO, bool isUndefHI) {
5265 EVT VT = V0.getValueType();
5266 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5267 "Invalid nodes in input!");
5269 unsigned NumElts = VT.getVectorNumElements();
5270 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5271 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5272 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5273 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5274 EVT NewVT = V0_LO.getValueType();
5276 SDValue LO = DAG.getUNDEF(NewVT);
5277 SDValue HI = DAG.getUNDEF(NewVT);
5280 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5281 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5282 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5283 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5284 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5286 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5287 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5288 V1_LO->getOpcode() != ISD::UNDEF))
5289 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5291 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5292 V1_HI->getOpcode() != ISD::UNDEF))
5293 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5296 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5299 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5300 /// sequence of 'vadd + vsub + blendi'.
5301 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5302 const X86Subtarget *Subtarget) {
5304 EVT VT = BV->getValueType(0);
5305 unsigned NumElts = VT.getVectorNumElements();
5306 SDValue InVec0 = DAG.getUNDEF(VT);
5307 SDValue InVec1 = DAG.getUNDEF(VT);
5309 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5310 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5312 // Odd-numbered elements in the input build vector are obtained from
5313 // adding two integer/float elements.
5314 // Even-numbered elements in the input build vector are obtained from
5315 // subtracting two integer/float elements.
5316 unsigned ExpectedOpcode = ISD::FSUB;
5317 unsigned NextExpectedOpcode = ISD::FADD;
5318 bool AddFound = false;
5319 bool SubFound = false;
5321 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5322 SDValue Op = BV->getOperand(i);
5324 // Skip 'undef' values.
5325 unsigned Opcode = Op.getOpcode();
5326 if (Opcode == ISD::UNDEF) {
5327 std::swap(ExpectedOpcode, NextExpectedOpcode);
5331 // Early exit if we found an unexpected opcode.
5332 if (Opcode != ExpectedOpcode)
5335 SDValue Op0 = Op.getOperand(0);
5336 SDValue Op1 = Op.getOperand(1);
5338 // Try to match the following pattern:
5339 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5340 // Early exit if we cannot match that sequence.
5341 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5342 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5343 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5344 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5345 Op0.getOperand(1) != Op1.getOperand(1))
5348 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5352 // We found a valid add/sub node. Update the information accordingly.
5358 // Update InVec0 and InVec1.
5359 if (InVec0.getOpcode() == ISD::UNDEF)
5360 InVec0 = Op0.getOperand(0);
5361 if (InVec1.getOpcode() == ISD::UNDEF)
5362 InVec1 = Op1.getOperand(0);
5364 // Make sure that operands in input to each add/sub node always
5365 // come from a same pair of vectors.
5366 if (InVec0 != Op0.getOperand(0)) {
5367 if (ExpectedOpcode == ISD::FSUB)
5370 // FADD is commutable. Try to commute the operands
5371 // and then test again.
5372 std::swap(Op0, Op1);
5373 if (InVec0 != Op0.getOperand(0))
5377 if (InVec1 != Op1.getOperand(0))
5380 // Update the pair of expected opcodes.
5381 std::swap(ExpectedOpcode, NextExpectedOpcode);
5384 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5385 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5386 InVec1.getOpcode() != ISD::UNDEF)
5387 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5392 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5393 const X86Subtarget *Subtarget) {
5395 EVT VT = N->getValueType(0);
5396 unsigned NumElts = VT.getVectorNumElements();
5397 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5398 SDValue InVec0, InVec1;
5400 // Try to match an ADDSUB.
5401 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5402 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5403 SDValue Value = matchAddSub(BV, DAG, Subtarget);
5404 if (Value.getNode())
5408 // Try to match horizontal ADD/SUB.
5409 unsigned NumUndefsLO = 0;
5410 unsigned NumUndefsHI = 0;
5411 unsigned Half = NumElts/2;
5413 // Count the number of UNDEF operands in the build_vector in input.
5414 for (unsigned i = 0, e = Half; i != e; ++i)
5415 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5418 for (unsigned i = Half, e = NumElts; i != e; ++i)
5419 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5422 // Early exit if this is either a build_vector of all UNDEFs or all the
5423 // operands but one are UNDEF.
5424 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5427 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5428 // Try to match an SSE3 float HADD/HSUB.
5429 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5430 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5432 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5433 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5434 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5435 // Try to match an SSSE3 integer HADD/HSUB.
5436 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5437 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5439 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5440 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5443 if (!Subtarget->hasAVX())
5446 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5447 // Try to match an AVX horizontal add/sub of packed single/double
5448 // precision floating point values from 256-bit vectors.
5449 SDValue InVec2, InVec3;
5450 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5451 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5452 ((InVec0.getOpcode() == ISD::UNDEF ||
5453 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5454 ((InVec1.getOpcode() == ISD::UNDEF ||
5455 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5456 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5458 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5459 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5460 ((InVec0.getOpcode() == ISD::UNDEF ||
5461 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5462 ((InVec1.getOpcode() == ISD::UNDEF ||
5463 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5464 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5465 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5466 // Try to match an AVX2 horizontal add/sub of signed integers.
5467 SDValue InVec2, InVec3;
5469 bool CanFold = true;
5471 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5472 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5473 ((InVec0.getOpcode() == ISD::UNDEF ||
5474 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5475 ((InVec1.getOpcode() == ISD::UNDEF ||
5476 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5477 X86Opcode = X86ISD::HADD;
5478 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5479 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5480 ((InVec0.getOpcode() == ISD::UNDEF ||
5481 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5482 ((InVec1.getOpcode() == ISD::UNDEF ||
5483 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5484 X86Opcode = X86ISD::HSUB;
5489 // Fold this build_vector into a single horizontal add/sub.
5490 // Do this only if the target has AVX2.
5491 if (Subtarget->hasAVX2())
5492 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5494 // Do not try to expand this build_vector into a pair of horizontal
5495 // add/sub if we can emit a pair of scalar add/sub.
5496 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5499 // Convert this build_vector into a pair of horizontal binop followed by
5501 bool isUndefLO = NumUndefsLO == Half;
5502 bool isUndefHI = NumUndefsHI == Half;
5503 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5504 isUndefLO, isUndefHI);
5508 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5509 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5511 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5512 X86Opcode = X86ISD::HADD;
5513 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5514 X86Opcode = X86ISD::HSUB;
5515 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5516 X86Opcode = X86ISD::FHADD;
5517 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5518 X86Opcode = X86ISD::FHSUB;
5522 // Don't try to expand this build_vector into a pair of horizontal add/sub
5523 // if we can simply emit a pair of scalar add/sub.
5524 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5527 // Convert this build_vector into two horizontal add/sub followed by
5529 bool isUndefLO = NumUndefsLO == Half;
5530 bool isUndefHI = NumUndefsHI == Half;
5531 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5532 isUndefLO, isUndefHI);
5539 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5542 MVT VT = Op.getSimpleValueType();
5543 MVT ExtVT = VT.getVectorElementType();
5544 unsigned NumElems = Op.getNumOperands();
5546 // Generate vectors for predicate vectors.
5547 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5548 return LowerBUILD_VECTORvXi1(Op, DAG);
5550 // Vectors containing all zeros can be matched by pxor and xorps later
5551 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5552 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5553 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5554 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5557 return getZeroVector(VT, Subtarget, DAG, dl);
5560 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5561 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5562 // vpcmpeqd on 256-bit vectors.
5563 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5564 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5567 if (!VT.is512BitVector())
5568 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5571 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5572 if (Broadcast.getNode())
5575 unsigned EVTBits = ExtVT.getSizeInBits();
5577 unsigned NumZero = 0;
5578 unsigned NumNonZero = 0;
5579 unsigned NonZeros = 0;
5580 bool IsAllConstants = true;
5581 SmallSet<SDValue, 8> Values;
5582 for (unsigned i = 0; i < NumElems; ++i) {
5583 SDValue Elt = Op.getOperand(i);
5584 if (Elt.getOpcode() == ISD::UNDEF)
5587 if (Elt.getOpcode() != ISD::Constant &&
5588 Elt.getOpcode() != ISD::ConstantFP)
5589 IsAllConstants = false;
5590 if (X86::isZeroNode(Elt))
5593 NonZeros |= (1 << i);
5598 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5599 if (NumNonZero == 0)
5600 return DAG.getUNDEF(VT);
5602 // Special case for single non-zero, non-undef, element.
5603 if (NumNonZero == 1) {
5604 unsigned Idx = countTrailingZeros(NonZeros);
5605 SDValue Item = Op.getOperand(Idx);
5607 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5608 // the value are obviously zero, truncate the value to i32 and do the
5609 // insertion that way. Only do this if the value is non-constant or if the
5610 // value is a constant being inserted into element 0. It is cheaper to do
5611 // a constant pool load than it is to do a movd + shuffle.
5612 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5613 (!IsAllConstants || Idx == 0)) {
5614 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5616 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5617 EVT VecVT = MVT::v4i32;
5619 // Truncate the value (which may itself be a constant) to i32, and
5620 // convert it to a vector with movd (S2V+shuffle to zero extend).
5621 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5622 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5624 ISD::BITCAST, dl, VT,
5625 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5629 // If we have a constant or non-constant insertion into the low element of
5630 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5631 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5632 // depending on what the source datatype is.
5635 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5637 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5638 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5639 if (VT.is256BitVector() || VT.is512BitVector()) {
5640 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5641 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5642 Item, DAG.getIntPtrConstant(0));
5644 assert(VT.is128BitVector() && "Expected an SSE value type!");
5645 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5646 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5647 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5650 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5651 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5652 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5653 if (VT.is256BitVector()) {
5654 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5655 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5657 assert(VT.is128BitVector() && "Expected an SSE value type!");
5658 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5660 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5664 // Is it a vector logical left shift?
5665 if (NumElems == 2 && Idx == 1 &&
5666 X86::isZeroNode(Op.getOperand(0)) &&
5667 !X86::isZeroNode(Op.getOperand(1))) {
5668 unsigned NumBits = VT.getSizeInBits();
5669 return getVShift(true, VT,
5670 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5671 VT, Op.getOperand(1)),
5672 NumBits/2, DAG, *this, dl);
5675 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5678 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5679 // is a non-constant being inserted into an element other than the low one,
5680 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5681 // movd/movss) to move this into the low element, then shuffle it into
5683 if (EVTBits == 32) {
5684 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5685 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5689 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5690 if (Values.size() == 1) {
5691 if (EVTBits == 32) {
5692 // Instead of a shuffle like this:
5693 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5694 // Check if it's possible to issue this instead.
5695 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5696 unsigned Idx = countTrailingZeros(NonZeros);
5697 SDValue Item = Op.getOperand(Idx);
5698 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5699 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5704 // A vector full of immediates; various special cases are already
5705 // handled, so this is best done with a single constant-pool load.
5709 // For AVX-length vectors, see if we can use a vector load to get all of the
5710 // elements, otherwise build the individual 128-bit pieces and use
5711 // shuffles to put them in place.
5712 if (VT.is256BitVector() || VT.is512BitVector()) {
5713 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5715 // Check for a build vector of consecutive loads.
5716 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5719 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5721 // Build both the lower and upper subvector.
5722 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5723 makeArrayRef(&V[0], NumElems/2));
5724 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5725 makeArrayRef(&V[NumElems / 2], NumElems/2));
5727 // Recreate the wider vector with the lower and upper part.
5728 if (VT.is256BitVector())
5729 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5730 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5733 // Let legalizer expand 2-wide build_vectors.
5734 if (EVTBits == 64) {
5735 if (NumNonZero == 1) {
5736 // One half is zero or undef.
5737 unsigned Idx = countTrailingZeros(NonZeros);
5738 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5739 Op.getOperand(Idx));
5740 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5745 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5746 if (EVTBits == 8 && NumElems == 16) {
5747 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5749 if (V.getNode()) return V;
5752 if (EVTBits == 16 && NumElems == 8) {
5753 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5755 if (V.getNode()) return V;
5758 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5759 if (EVTBits == 32 && NumElems == 4) {
5760 SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5765 // If element VT is == 32 bits, turn it into a number of shuffles.
5766 SmallVector<SDValue, 8> V(NumElems);
5767 if (NumElems == 4 && NumZero > 0) {
5768 for (unsigned i = 0; i < 4; ++i) {
5769 bool isZero = !(NonZeros & (1 << i));
5771 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5773 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5776 for (unsigned i = 0; i < 2; ++i) {
5777 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5780 V[i] = V[i*2]; // Must be a zero vector.
5783 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5786 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5789 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5794 bool Reverse1 = (NonZeros & 0x3) == 2;
5795 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5799 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5800 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5802 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5805 if (Values.size() > 1 && VT.is128BitVector()) {
5806 // Check for a build vector of consecutive loads.
5807 for (unsigned i = 0; i < NumElems; ++i)
5808 V[i] = Op.getOperand(i);
5810 // Check for elements which are consecutive loads.
5811 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5815 // Check for a build vector from mostly shuffle plus few inserting.
5816 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5820 // For SSE 4.1, use insertps to put the high elements into the low element.
5821 if (Subtarget->hasSSE41()) {
5823 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5824 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5826 Result = DAG.getUNDEF(VT);
5828 for (unsigned i = 1; i < NumElems; ++i) {
5829 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5830 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5831 Op.getOperand(i), DAG.getIntPtrConstant(i));
5836 // Otherwise, expand into a number of unpckl*, start by extending each of
5837 // our (non-undef) elements to the full vector width with the element in the
5838 // bottom slot of the vector (which generates no code for SSE).
5839 for (unsigned i = 0; i < NumElems; ++i) {
5840 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5841 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5843 V[i] = DAG.getUNDEF(VT);
5846 // Next, we iteratively mix elements, e.g. for v4f32:
5847 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5848 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5849 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5850 unsigned EltStride = NumElems >> 1;
5851 while (EltStride != 0) {
5852 for (unsigned i = 0; i < EltStride; ++i) {
5853 // If V[i+EltStride] is undef and this is the first round of mixing,
5854 // then it is safe to just drop this shuffle: V[i] is already in the
5855 // right place, the one element (since it's the first round) being
5856 // inserted as undef can be dropped. This isn't safe for successive
5857 // rounds because they will permute elements within both vectors.
5858 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5859 EltStride == NumElems/2)
5862 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5871 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5872 // to create 256-bit vectors from two other 128-bit ones.
5873 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5875 MVT ResVT = Op.getSimpleValueType();
5877 assert((ResVT.is256BitVector() ||
5878 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5880 SDValue V1 = Op.getOperand(0);
5881 SDValue V2 = Op.getOperand(1);
5882 unsigned NumElems = ResVT.getVectorNumElements();
5883 if(ResVT.is256BitVector())
5884 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5886 if (Op.getNumOperands() == 4) {
5887 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5888 ResVT.getVectorNumElements()/2);
5889 SDValue V3 = Op.getOperand(2);
5890 SDValue V4 = Op.getOperand(3);
5891 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5892 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5894 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5897 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5898 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
5899 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5900 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5901 Op.getNumOperands() == 4)));
5903 // AVX can use the vinsertf128 instruction to create 256-bit vectors
5904 // from two other 128-bit ones.
5906 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5907 return LowerAVXCONCAT_VECTORS(Op, DAG);
5911 //===----------------------------------------------------------------------===//
5912 // Vector shuffle lowering
5914 // This is an experimental code path for lowering vector shuffles on x86. It is
5915 // designed to handle arbitrary vector shuffles and blends, gracefully
5916 // degrading performance as necessary. It works hard to recognize idiomatic
5917 // shuffles and lower them to optimal instruction patterns without leaving
5918 // a framework that allows reasonably efficient handling of all vector shuffle
5920 //===----------------------------------------------------------------------===//
5922 /// \brief Tiny helper function to identify a no-op mask.
5924 /// This is a somewhat boring predicate function. It checks whether the mask
5925 /// array input, which is assumed to be a single-input shuffle mask of the kind
5926 /// used by the X86 shuffle instructions (not a fully general
5927 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5928 /// in-place shuffle are 'no-op's.
5929 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5930 for (int i = 0, Size = Mask.size(); i < Size; ++i)
5931 if (Mask[i] != -1 && Mask[i] != i)
5936 /// \brief Helper function to classify a mask as a single-input mask.
5938 /// This isn't a generic single-input test because in the vector shuffle
5939 /// lowering we canonicalize single inputs to be the first input operand. This
5940 /// means we can more quickly test for a single input by only checking whether
5941 /// an input from the second operand exists. We also assume that the size of
5942 /// mask corresponds to the size of the input vectors which isn't true in the
5943 /// fully general case.
5944 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5946 if (M >= (int)Mask.size())
5951 /// \brief Test whether there are elements crossing 128-bit lanes in this
5954 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5955 /// and we routinely test for these.
5956 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5957 int LaneSize = 128 / VT.getScalarSizeInBits();
5958 int Size = Mask.size();
5959 for (int i = 0; i < Size; ++i)
5960 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5965 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5967 /// This checks a shuffle mask to see if it is performing the same
5968 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5969 /// that it is also not lane-crossing. It may however involve a blend from the
5970 /// same lane of a second vector.
5972 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5973 /// non-trivial to compute in the face of undef lanes. The representation is
5974 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5975 /// entries from both V1 and V2 inputs to the wider mask.
5977 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5978 SmallVectorImpl<int> &RepeatedMask) {
5979 int LaneSize = 128 / VT.getScalarSizeInBits();
5980 RepeatedMask.resize(LaneSize, -1);
5981 int Size = Mask.size();
5982 for (int i = 0; i < Size; ++i) {
5985 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
5986 // This entry crosses lanes, so there is no way to model this shuffle.
5989 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
5990 if (RepeatedMask[i % LaneSize] == -1)
5991 // This is the first non-undef entry in this slot of a 128-bit lane.
5992 RepeatedMask[i % LaneSize] =
5993 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
5994 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
5995 // Found a mismatch with the repeated mask.
6001 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6004 /// This is a fast way to test a shuffle mask against a fixed pattern:
6006 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6008 /// It returns true if the mask is exactly as wide as the argument list, and
6009 /// each element of the mask is either -1 (signifying undef) or the value given
6010 /// in the argument.
6011 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6012 ArrayRef<int> ExpectedMask) {
6013 if (Mask.size() != ExpectedMask.size())
6016 int Size = Mask.size();
6018 // If the values are build vectors, we can look through them to find
6019 // equivalent inputs that make the shuffles equivalent.
6020 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6021 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6023 for (int i = 0; i < Size; ++i)
6024 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6025 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6026 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6027 if (!MaskBV || !ExpectedBV ||
6028 MaskBV->getOperand(Mask[i] % Size) !=
6029 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6036 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6038 /// This helper function produces an 8-bit shuffle immediate corresponding to
6039 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6040 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6043 /// NB: We rely heavily on "undef" masks preserving the input lane.
6044 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6045 SelectionDAG &DAG) {
6046 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6047 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6048 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6049 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6050 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6053 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6054 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6055 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6056 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6057 return DAG.getConstant(Imm, MVT::i8);
6060 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6062 /// This is used as a fallback approach when first class blend instructions are
6063 /// unavailable. Currently it is only suitable for integer vectors, but could
6064 /// be generalized for floating point vectors if desirable.
6065 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6066 SDValue V2, ArrayRef<int> Mask,
6067 SelectionDAG &DAG) {
6068 assert(VT.isInteger() && "Only supports integer vector types!");
6069 MVT EltVT = VT.getScalarType();
6070 int NumEltBits = EltVT.getSizeInBits();
6071 SDValue Zero = DAG.getConstant(0, EltVT);
6072 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6073 SmallVector<SDValue, 16> MaskOps;
6074 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6075 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6076 return SDValue(); // Shuffled input!
6077 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6080 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6081 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6082 // We have to cast V2 around.
6083 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6084 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6085 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6086 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6087 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6088 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6091 /// \brief Try to emit a blend instruction for a shuffle.
6093 /// This doesn't do any checks for the availability of instructions for blending
6094 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6095 /// be matched in the backend with the type given. What it does check for is
6096 /// that the shuffle mask is in fact a blend.
6097 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6098 SDValue V2, ArrayRef<int> Mask,
6099 const X86Subtarget *Subtarget,
6100 SelectionDAG &DAG) {
6101 unsigned BlendMask = 0;
6102 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6103 if (Mask[i] >= Size) {
6104 if (Mask[i] != i + Size)
6105 return SDValue(); // Shuffled V2 input!
6106 BlendMask |= 1u << i;
6109 if (Mask[i] >= 0 && Mask[i] != i)
6110 return SDValue(); // Shuffled V1 input!
6112 switch (VT.SimpleTy) {
6117 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6118 DAG.getConstant(BlendMask, MVT::i8));
6122 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6126 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6127 // that instruction.
6128 if (Subtarget->hasAVX2()) {
6129 // Scale the blend by the number of 32-bit dwords per element.
6130 int Scale = VT.getScalarSizeInBits() / 32;
6132 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6133 if (Mask[i] >= Size)
6134 for (int j = 0; j < Scale; ++j)
6135 BlendMask |= 1u << (i * Scale + j);
6137 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6138 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6139 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6140 return DAG.getNode(ISD::BITCAST, DL, VT,
6141 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6142 DAG.getConstant(BlendMask, MVT::i8)));
6146 // For integer shuffles we need to expand the mask and cast the inputs to
6147 // v8i16s prior to blending.
6148 int Scale = 8 / VT.getVectorNumElements();
6150 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6151 if (Mask[i] >= Size)
6152 for (int j = 0; j < Scale; ++j)
6153 BlendMask |= 1u << (i * Scale + j);
6155 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6156 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6157 return DAG.getNode(ISD::BITCAST, DL, VT,
6158 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6159 DAG.getConstant(BlendMask, MVT::i8)));
6163 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6164 SmallVector<int, 8> RepeatedMask;
6165 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6166 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6167 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6169 for (int i = 0; i < 8; ++i)
6170 if (RepeatedMask[i] >= 16)
6171 BlendMask |= 1u << i;
6172 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6173 DAG.getConstant(BlendMask, MVT::i8));
6179 // Scale the blend by the number of bytes per element.
6180 int Scale = VT.getScalarSizeInBits() / 8;
6182 // This form of blend is always done on bytes. Compute the byte vector
6184 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6186 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6187 // mix of LLVM's code generator and the x86 backend. We tell the code
6188 // generator that boolean values in the elements of an x86 vector register
6189 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6190 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6191 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6192 // of the element (the remaining are ignored) and 0 in that high bit would
6193 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6194 // the LLVM model for boolean values in vector elements gets the relevant
6195 // bit set, it is set backwards and over constrained relative to x86's
6197 SmallVector<SDValue, 32> VSELECTMask;
6198 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6199 for (int j = 0; j < Scale; ++j)
6200 VSELECTMask.push_back(
6201 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6202 : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6204 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6205 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6207 ISD::BITCAST, DL, VT,
6208 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6209 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6214 llvm_unreachable("Not a supported integer vector type!");
6218 /// \brief Try to lower as a blend of elements from two inputs followed by
6219 /// a single-input permutation.
6221 /// This matches the pattern where we can blend elements from two inputs and
6222 /// then reduce the shuffle to a single-input permutation.
6223 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6226 SelectionDAG &DAG) {
6227 // We build up the blend mask while checking whether a blend is a viable way
6228 // to reduce the shuffle.
6229 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6230 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6232 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6236 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6238 if (BlendMask[Mask[i] % Size] == -1)
6239 BlendMask[Mask[i] % Size] = Mask[i];
6240 else if (BlendMask[Mask[i] % Size] != Mask[i])
6241 return SDValue(); // Can't blend in the needed input!
6243 PermuteMask[i] = Mask[i] % Size;
6246 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6247 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6250 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6251 /// blends and permutes.
6253 /// This matches the extremely common pattern for handling combined
6254 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6255 /// operations. It will try to pick the best arrangement of shuffles and
6257 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6261 SelectionDAG &DAG) {
6262 // Shuffle the input elements into the desired positions in V1 and V2 and
6263 // blend them together.
6264 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6265 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6266 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6267 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6268 if (Mask[i] >= 0 && Mask[i] < Size) {
6269 V1Mask[i] = Mask[i];
6271 } else if (Mask[i] >= Size) {
6272 V2Mask[i] = Mask[i] - Size;
6273 BlendMask[i] = i + Size;
6276 // Try to lower with the simpler initial blend strategy unless one of the
6277 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6278 // shuffle may be able to fold with a load or other benefit. However, when
6279 // we'll have to do 2x as many shuffles in order to achieve this, blending
6280 // first is a better strategy.
6281 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6282 if (SDValue BlendPerm =
6283 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6286 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6287 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6288 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6291 /// \brief Try to lower a vector shuffle as a byte rotation.
6293 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6294 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6295 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6296 /// try to generically lower a vector shuffle through such an pattern. It
6297 /// does not check for the profitability of lowering either as PALIGNR or
6298 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6299 /// This matches shuffle vectors that look like:
6301 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6303 /// Essentially it concatenates V1 and V2, shifts right by some number of
6304 /// elements, and takes the low elements as the result. Note that while this is
6305 /// specified as a *right shift* because x86 is little-endian, it is a *left
6306 /// rotate* of the vector lanes.
6307 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6310 const X86Subtarget *Subtarget,
6311 SelectionDAG &DAG) {
6312 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6314 int NumElts = Mask.size();
6315 int NumLanes = VT.getSizeInBits() / 128;
6316 int NumLaneElts = NumElts / NumLanes;
6318 // We need to detect various ways of spelling a rotation:
6319 // [11, 12, 13, 14, 15, 0, 1, 2]
6320 // [-1, 12, 13, 14, -1, -1, 1, -1]
6321 // [-1, -1, -1, -1, -1, -1, 1, 2]
6322 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6323 // [-1, 4, 5, 6, -1, -1, 9, -1]
6324 // [-1, 4, 5, 6, -1, -1, -1, -1]
6327 for (int l = 0; l < NumElts; l += NumLaneElts) {
6328 for (int i = 0; i < NumLaneElts; ++i) {
6329 if (Mask[l + i] == -1)
6331 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6333 // Get the mod-Size index and lane correct it.
6334 int LaneIdx = (Mask[l + i] % NumElts) - l;
6335 // Make sure it was in this lane.
6336 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6339 // Determine where a rotated vector would have started.
6340 int StartIdx = i - LaneIdx;
6342 // The identity rotation isn't interesting, stop.
6345 // If we found the tail of a vector the rotation must be the missing
6346 // front. If we found the head of a vector, it must be how much of the
6348 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6351 Rotation = CandidateRotation;
6352 else if (Rotation != CandidateRotation)
6353 // The rotations don't match, so we can't match this mask.
6356 // Compute which value this mask is pointing at.
6357 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6359 // Compute which of the two target values this index should be assigned
6360 // to. This reflects whether the high elements are remaining or the low
6361 // elements are remaining.
6362 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6364 // Either set up this value if we've not encountered it before, or check
6365 // that it remains consistent.
6368 else if (TargetV != MaskV)
6369 // This may be a rotation, but it pulls from the inputs in some
6370 // unsupported interleaving.
6375 // Check that we successfully analyzed the mask, and normalize the results.
6376 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6377 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6383 // The actual rotate instruction rotates bytes, so we need to scale the
6384 // rotation based on how many bytes are in the vector lane.
6385 int Scale = 16 / NumLaneElts;
6387 // SSSE3 targets can use the palignr instruction.
6388 if (Subtarget->hasSSSE3()) {
6389 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6390 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6391 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6392 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6394 return DAG.getNode(ISD::BITCAST, DL, VT,
6395 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6396 DAG.getConstant(Rotation * Scale, MVT::i8)));
6399 assert(VT.getSizeInBits() == 128 &&
6400 "Rotate-based lowering only supports 128-bit lowering!");
6401 assert(Mask.size() <= 16 &&
6402 "Can shuffle at most 16 bytes in a 128-bit vector!");
6404 // Default SSE2 implementation
6405 int LoByteShift = 16 - Rotation * Scale;
6406 int HiByteShift = Rotation * Scale;
6408 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6409 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6410 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6412 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6413 DAG.getConstant(LoByteShift, MVT::i8));
6414 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6415 DAG.getConstant(HiByteShift, MVT::i8));
6416 return DAG.getNode(ISD::BITCAST, DL, VT,
6417 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6420 /// \brief Compute whether each element of a shuffle is zeroable.
6422 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6423 /// Either it is an undef element in the shuffle mask, the element of the input
6424 /// referenced is undef, or the element of the input referenced is known to be
6425 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6426 /// as many lanes with this technique as possible to simplify the remaining
6428 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6429 SDValue V1, SDValue V2) {
6430 SmallBitVector Zeroable(Mask.size(), false);
6432 while (V1.getOpcode() == ISD::BITCAST)
6433 V1 = V1->getOperand(0);
6434 while (V2.getOpcode() == ISD::BITCAST)
6435 V2 = V2->getOperand(0);
6437 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6438 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6440 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6442 // Handle the easy cases.
6443 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6448 // If this is an index into a build_vector node (which has the same number
6449 // of elements), dig out the input value and use it.
6450 SDValue V = M < Size ? V1 : V2;
6451 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6454 SDValue Input = V.getOperand(M % Size);
6455 // The UNDEF opcode check really should be dead code here, but not quite
6456 // worth asserting on (it isn't invalid, just unexpected).
6457 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6464 /// \brief Try to emit a bitmask instruction for a shuffle.
6466 /// This handles cases where we can model a blend exactly as a bitmask due to
6467 /// one of the inputs being zeroable.
6468 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6469 SDValue V2, ArrayRef<int> Mask,
6470 SelectionDAG &DAG) {
6471 MVT EltVT = VT.getScalarType();
6472 int NumEltBits = EltVT.getSizeInBits();
6473 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6474 SDValue Zero = DAG.getConstant(0, IntEltVT);
6475 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6476 if (EltVT.isFloatingPoint()) {
6477 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6478 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6480 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6481 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6483 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6486 if (Mask[i] % Size != i)
6487 return SDValue(); // Not a blend.
6489 V = Mask[i] < Size ? V1 : V2;
6490 else if (V != (Mask[i] < Size ? V1 : V2))
6491 return SDValue(); // Can only let one input through the mask.
6493 VMaskOps[i] = AllOnes;
6496 return SDValue(); // No non-zeroable elements!
6498 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6499 V = DAG.getNode(VT.isFloatingPoint()
6500 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6505 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6507 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6508 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6509 /// matches elements from one of the input vectors shuffled to the left or
6510 /// right with zeroable elements 'shifted in'. It handles both the strictly
6511 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6514 /// PSHL : (little-endian) left bit shift.
6515 /// [ zz, 0, zz, 2 ]
6516 /// [ -1, 4, zz, -1 ]
6517 /// PSRL : (little-endian) right bit shift.
6519 /// [ -1, -1, 7, zz]
6520 /// PSLLDQ : (little-endian) left byte shift
6521 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6522 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6523 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6524 /// PSRLDQ : (little-endian) right byte shift
6525 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6526 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6527 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6528 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6529 SDValue V2, ArrayRef<int> Mask,
6530 SelectionDAG &DAG) {
6531 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6533 int Size = Mask.size();
6534 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6536 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6537 for (int i = 0; i < Size; i += Scale)
6538 for (int j = 0; j < Shift; ++j)
6539 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6545 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6546 for (int i = 0; i != Size; i += Scale) {
6547 unsigned Pos = Left ? i + Shift : i;
6548 unsigned Low = Left ? i : i + Shift;
6549 unsigned Len = Scale - Shift;
6550 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6551 Low + (V == V1 ? 0 : Size)))
6555 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6556 bool ByteShift = ShiftEltBits > 64;
6557 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6558 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6559 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6561 // Normalize the scale for byte shifts to still produce an i64 element
6563 Scale = ByteShift ? Scale / 2 : Scale;
6565 // We need to round trip through the appropriate type for the shift.
6566 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6567 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6568 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6569 "Illegal integer vector type");
6570 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6572 V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6573 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6576 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6577 // keep doubling the size of the integer elements up to that. We can
6578 // then shift the elements of the integer vector by whole multiples of
6579 // their width within the elements of the larger integer vector. Test each
6580 // multiple to see if we can find a match with the moved element indices
6581 // and that the shifted in elements are all zeroable.
6582 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6583 for (int Shift = 1; Shift != Scale; ++Shift)
6584 for (bool Left : {true, false})
6585 if (CheckZeros(Shift, Scale, Left))
6586 for (SDValue V : {V1, V2})
6587 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6594 /// \brief Lower a vector shuffle as a zero or any extension.
6596 /// Given a specific number of elements, element bit width, and extension
6597 /// stride, produce either a zero or any extension based on the available
6598 /// features of the subtarget.
6599 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6600 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6601 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6602 assert(Scale > 1 && "Need a scale to extend.");
6603 int NumElements = VT.getVectorNumElements();
6604 int EltBits = VT.getScalarSizeInBits();
6605 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6606 "Only 8, 16, and 32 bit elements can be extended.");
6607 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6609 // Found a valid zext mask! Try various lowering strategies based on the
6610 // input type and available ISA extensions.
6611 if (Subtarget->hasSSE41()) {
6612 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6613 NumElements / Scale);
6614 return DAG.getNode(ISD::BITCAST, DL, VT,
6615 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6618 // For any extends we can cheat for larger element sizes and use shuffle
6619 // instructions that can fold with a load and/or copy.
6620 if (AnyExt && EltBits == 32) {
6621 int PSHUFDMask[4] = {0, -1, 1, -1};
6623 ISD::BITCAST, DL, VT,
6624 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6625 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6626 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6628 if (AnyExt && EltBits == 16 && Scale > 2) {
6629 int PSHUFDMask[4] = {0, -1, 0, -1};
6630 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6631 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6632 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6633 int PSHUFHWMask[4] = {1, -1, -1, -1};
6635 ISD::BITCAST, DL, VT,
6636 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6637 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6638 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6641 // If this would require more than 2 unpack instructions to expand, use
6642 // pshufb when available. We can only use more than 2 unpack instructions
6643 // when zero extending i8 elements which also makes it easier to use pshufb.
6644 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6645 assert(NumElements == 16 && "Unexpected byte vector width!");
6646 SDValue PSHUFBMask[16];
6647 for (int i = 0; i < 16; ++i)
6649 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6650 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6651 return DAG.getNode(ISD::BITCAST, DL, VT,
6652 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6653 DAG.getNode(ISD::BUILD_VECTOR, DL,
6654 MVT::v16i8, PSHUFBMask)));
6657 // Otherwise emit a sequence of unpacks.
6659 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6660 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6661 : getZeroVector(InputVT, Subtarget, DAG, DL);
6662 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6663 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6667 } while (Scale > 1);
6668 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6671 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6673 /// This routine will try to do everything in its power to cleverly lower
6674 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6675 /// check for the profitability of this lowering, it tries to aggressively
6676 /// match this pattern. It will use all of the micro-architectural details it
6677 /// can to emit an efficient lowering. It handles both blends with all-zero
6678 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6679 /// masking out later).
6681 /// The reason we have dedicated lowering for zext-style shuffles is that they
6682 /// are both incredibly common and often quite performance sensitive.
6683 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6684 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6685 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6686 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6688 int Bits = VT.getSizeInBits();
6689 int NumElements = VT.getVectorNumElements();
6690 assert(VT.getScalarSizeInBits() <= 32 &&
6691 "Exceeds 32-bit integer zero extension limit");
6692 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6694 // Define a helper function to check a particular ext-scale and lower to it if
6696 auto Lower = [&](int Scale) -> SDValue {
6699 for (int i = 0; i < NumElements; ++i) {
6701 continue; // Valid anywhere but doesn't tell us anything.
6702 if (i % Scale != 0) {
6703 // Each of the extended elements need to be zeroable.
6707 // We no longer are in the anyext case.
6712 // Each of the base elements needs to be consecutive indices into the
6713 // same input vector.
6714 SDValue V = Mask[i] < NumElements ? V1 : V2;
6717 else if (InputV != V)
6718 return SDValue(); // Flip-flopping inputs.
6720 if (Mask[i] % NumElements != i / Scale)
6721 return SDValue(); // Non-consecutive strided elements.
6724 // If we fail to find an input, we have a zero-shuffle which should always
6725 // have already been handled.
6726 // FIXME: Maybe handle this here in case during blending we end up with one?
6730 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6731 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6734 // The widest scale possible for extending is to a 64-bit integer.
6735 assert(Bits % 64 == 0 &&
6736 "The number of bits in a vector must be divisible by 64 on x86!");
6737 int NumExtElements = Bits / 64;
6739 // Each iteration, try extending the elements half as much, but into twice as
6741 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6742 assert(NumElements % NumExtElements == 0 &&
6743 "The input vector size must be divisible by the extended size.");
6744 if (SDValue V = Lower(NumElements / NumExtElements))
6748 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6752 // Returns one of the source operands if the shuffle can be reduced to a
6753 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6754 auto CanZExtLowHalf = [&]() {
6755 for (int i = NumElements / 2; i != NumElements; ++i)
6758 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6760 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6765 if (SDValue V = CanZExtLowHalf()) {
6766 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6767 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6768 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6771 // No viable ext lowering found.
6775 /// \brief Try to get a scalar value for a specific element of a vector.
6777 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6778 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6779 SelectionDAG &DAG) {
6780 MVT VT = V.getSimpleValueType();
6781 MVT EltVT = VT.getVectorElementType();
6782 while (V.getOpcode() == ISD::BITCAST)
6783 V = V.getOperand(0);
6784 // If the bitcasts shift the element size, we can't extract an equivalent
6786 MVT NewVT = V.getSimpleValueType();
6787 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6790 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6791 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6792 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6797 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6799 /// This is particularly important because the set of instructions varies
6800 /// significantly based on whether the operand is a load or not.
6801 static bool isShuffleFoldableLoad(SDValue V) {
6802 while (V.getOpcode() == ISD::BITCAST)
6803 V = V.getOperand(0);
6805 return ISD::isNON_EXTLoad(V.getNode());
6808 /// \brief Try to lower insertion of a single element into a zero vector.
6810 /// This is a common pattern that we have especially efficient patterns to lower
6811 /// across all subtarget feature sets.
6812 static SDValue lowerVectorShuffleAsElementInsertion(
6813 MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6814 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6815 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6817 MVT EltVT = VT.getVectorElementType();
6819 int V2Index = std::find_if(Mask.begin(), Mask.end(),
6820 [&Mask](int M) { return M >= (int)Mask.size(); }) -
6822 bool IsV1Zeroable = true;
6823 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6824 if (i != V2Index && !Zeroable[i]) {
6825 IsV1Zeroable = false;
6829 // Check for a single input from a SCALAR_TO_VECTOR node.
6830 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6831 // all the smarts here sunk into that routine. However, the current
6832 // lowering of BUILD_VECTOR makes that nearly impossible until the old
6833 // vector shuffle lowering is dead.
6834 if (SDValue V2S = getScalarValueForVectorElement(
6835 V2, Mask[V2Index] - Mask.size(), DAG)) {
6836 // We need to zext the scalar if it is smaller than an i32.
6837 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6838 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6839 // Using zext to expand a narrow element won't work for non-zero
6844 // Zero-extend directly to i32.
6846 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6848 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6849 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6850 EltVT == MVT::i16) {
6851 // Either not inserting from the low element of the input or the input
6852 // element size is too small to use VZEXT_MOVL to clear the high bits.
6856 if (!IsV1Zeroable) {
6857 // If V1 can't be treated as a zero vector we have fewer options to lower
6858 // this. We can't support integer vectors or non-zero targets cheaply, and
6859 // the V1 elements can't be permuted in any way.
6860 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6861 if (!VT.isFloatingPoint() || V2Index != 0)
6863 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6864 V1Mask[V2Index] = -1;
6865 if (!isNoopShuffleMask(V1Mask))
6867 // This is essentially a special case blend operation, but if we have
6868 // general purpose blend operations, they are always faster. Bail and let
6869 // the rest of the lowering handle these as blends.
6870 if (Subtarget->hasSSE41())
6873 // Otherwise, use MOVSD or MOVSS.
6874 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6875 "Only two types of floating point element types to handle!");
6876 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6880 // This lowering only works for the low element with floating point vectors.
6881 if (VT.isFloatingPoint() && V2Index != 0)
6884 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6886 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6889 // If we have 4 or fewer lanes we can cheaply shuffle the element into
6890 // the desired position. Otherwise it is more efficient to do a vector
6891 // shift left. We know that we can do a vector shift left because all
6892 // the inputs are zero.
6893 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6894 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6895 V2Shuffle[V2Index] = 0;
6896 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6898 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6900 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6902 V2Index * EltVT.getSizeInBits()/8,
6903 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6904 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6910 /// \brief Try to lower broadcast of a single element.
6912 /// For convenience, this code also bundles all of the subtarget feature set
6913 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6914 /// a convenient way to factor it out.
6915 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
6917 const X86Subtarget *Subtarget,
6918 SelectionDAG &DAG) {
6919 if (!Subtarget->hasAVX())
6921 if (VT.isInteger() && !Subtarget->hasAVX2())
6924 // Check that the mask is a broadcast.
6925 int BroadcastIdx = -1;
6927 if (M >= 0 && BroadcastIdx == -1)
6929 else if (M >= 0 && M != BroadcastIdx)
6932 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6933 "a sorted mask where the broadcast "
6936 // Go up the chain of (vector) values to try and find a scalar load that
6937 // we can combine with the broadcast.
6939 switch (V.getOpcode()) {
6940 case ISD::CONCAT_VECTORS: {
6941 int OperandSize = Mask.size() / V.getNumOperands();
6942 V = V.getOperand(BroadcastIdx / OperandSize);
6943 BroadcastIdx %= OperandSize;
6947 case ISD::INSERT_SUBVECTOR: {
6948 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6949 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6953 int BeginIdx = (int)ConstantIdx->getZExtValue();
6955 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6956 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6957 BroadcastIdx -= BeginIdx;
6968 // Check if this is a broadcast of a scalar. We special case lowering
6969 // for scalars so that we can more effectively fold with loads.
6970 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6971 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6972 V = V.getOperand(BroadcastIdx);
6974 // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6976 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6978 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6979 // We can't broadcast from a vector register w/o AVX2, and we can only
6980 // broadcast from the zero-element of a vector register.
6984 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
6987 // Check for whether we can use INSERTPS to perform the shuffle. We only use
6988 // INSERTPS when the V1 elements are already in the correct locations
6989 // because otherwise we can just always use two SHUFPS instructions which
6990 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
6991 // perform INSERTPS if a single V1 element is out of place and all V2
6992 // elements are zeroable.
6993 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
6995 SelectionDAG &DAG) {
6996 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
6997 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6998 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
6999 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7001 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7004 int V1DstIndex = -1;
7005 int V2DstIndex = -1;
7006 bool V1UsedInPlace = false;
7008 for (int i = 0; i < 4; ++i) {
7009 // Synthesize a zero mask from the zeroable elements (includes undefs).
7015 // Flag if we use any V1 inputs in place.
7017 V1UsedInPlace = true;
7021 // We can only insert a single non-zeroable element.
7022 if (V1DstIndex != -1 || V2DstIndex != -1)
7026 // V1 input out of place for insertion.
7029 // V2 input for insertion.
7034 // Don't bother if we have no (non-zeroable) element for insertion.
7035 if (V1DstIndex == -1 && V2DstIndex == -1)
7038 // Determine element insertion src/dst indices. The src index is from the
7039 // start of the inserted vector, not the start of the concatenated vector.
7040 unsigned V2SrcIndex = 0;
7041 if (V1DstIndex != -1) {
7042 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7043 // and don't use the original V2 at all.
7044 V2SrcIndex = Mask[V1DstIndex];
7045 V2DstIndex = V1DstIndex;
7048 V2SrcIndex = Mask[V2DstIndex] - 4;
7051 // If no V1 inputs are used in place, then the result is created only from
7052 // the zero mask and the V2 insertion - so remove V1 dependency.
7054 V1 = DAG.getUNDEF(MVT::v4f32);
7056 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7057 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7059 // Insert the V2 element into the desired position.
7061 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7062 DAG.getConstant(InsertPSMask, MVT::i8));
7065 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7066 /// UNPCK instruction.
7068 /// This specifically targets cases where we end up with alternating between
7069 /// the two inputs, and so can permute them into something that feeds a single
7070 /// UNPCK instruction. Note that this routine only targets integer vectors
7071 /// because for floating point vectors we have a generalized SHUFPS lowering
7072 /// strategy that handles everything that doesn't *exactly* match an unpack,
7073 /// making this clever lowering unnecessary.
7074 static SDValue lowerVectorShuffleAsUnpack(MVT VT, SDLoc DL, SDValue V1,
7075 SDValue V2, ArrayRef<int> Mask,
7076 SelectionDAG &DAG) {
7077 assert(!VT.isFloatingPoint() &&
7078 "This routine only supports integer vectors.");
7079 assert(!isSingleInputShuffleMask(Mask) &&
7080 "This routine should only be used when blending two inputs.");
7081 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7083 int Size = Mask.size();
7085 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7086 return M >= 0 && M % Size < Size / 2;
7088 int NumHiInputs = std::count_if(
7089 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7091 bool UnpackLo = NumLoInputs >= NumHiInputs;
7093 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7094 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7095 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7097 for (int i = 0; i < Size; ++i) {
7101 // Each element of the unpack contains Scale elements from this mask.
7102 int UnpackIdx = i / Scale;
7104 // We only handle the case where V1 feeds the first slots of the unpack.
7105 // We rely on canonicalization to ensure this is the case.
7106 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7109 // Setup the mask for this input. The indexing is tricky as we have to
7110 // handle the unpack stride.
7111 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7112 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7116 // If we will have to shuffle both inputs to use the unpack, check whether
7117 // we can just unpack first and shuffle the result. If so, skip this unpack.
7118 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7119 !isNoopShuffleMask(V2Mask))
7122 // Shuffle the inputs into place.
7123 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7124 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7126 // Cast the inputs to the type we will use to unpack them.
7127 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7128 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7130 // Unpack the inputs and cast the result back to the desired type.
7131 return DAG.getNode(ISD::BITCAST, DL, VT,
7132 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7133 DL, UnpackVT, V1, V2));
7136 // We try each unpack from the largest to the smallest to try and find one
7137 // that fits this mask.
7138 int OrigNumElements = VT.getVectorNumElements();
7139 int OrigScalarSize = VT.getScalarSizeInBits();
7140 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7141 int Scale = ScalarSize / OrigScalarSize;
7142 int NumElements = OrigNumElements / Scale;
7143 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7144 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7148 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7150 if (NumLoInputs == 0 || NumHiInputs == 0) {
7151 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7152 "We have to have *some* inputs!");
7153 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7155 // FIXME: We could consider the total complexity of the permute of each
7156 // possible unpacking. Or at the least we should consider how many
7157 // half-crossings are created.
7158 // FIXME: We could consider commuting the unpacks.
7160 SmallVector<int, 32> PermMask;
7161 PermMask.assign(Size, -1);
7162 for (int i = 0; i < Size; ++i) {
7166 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7169 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7171 return DAG.getVectorShuffle(
7172 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7174 DAG.getUNDEF(VT), PermMask);
7180 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7182 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7183 /// support for floating point shuffles but not integer shuffles. These
7184 /// instructions will incur a domain crossing penalty on some chips though so
7185 /// it is better to avoid lowering through this for integer vectors where
7187 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7188 const X86Subtarget *Subtarget,
7189 SelectionDAG &DAG) {
7191 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7192 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7193 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7194 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7195 ArrayRef<int> Mask = SVOp->getMask();
7196 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7198 if (isSingleInputShuffleMask(Mask)) {
7199 // Use low duplicate instructions for masks that match their pattern.
7200 if (Subtarget->hasSSE3())
7201 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7202 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7204 // Straight shuffle of a single input vector. Simulate this by using the
7205 // single input as both of the "inputs" to this instruction..
7206 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7208 if (Subtarget->hasAVX()) {
7209 // If we have AVX, we can use VPERMILPS which will allow folding a load
7210 // into the shuffle.
7211 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7212 DAG.getConstant(SHUFPDMask, MVT::i8));
7215 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7216 DAG.getConstant(SHUFPDMask, MVT::i8));
7218 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7219 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7221 // If we have a single input, insert that into V1 if we can do so cheaply.
7222 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7223 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7224 MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
7226 // Try inverting the insertion since for v2 masks it is easy to do and we
7227 // can't reliably sort the mask one way or the other.
7228 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7229 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7230 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7231 MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
7235 // Try to use one of the special instruction patterns to handle two common
7236 // blend patterns if a zero-blend above didn't work.
7237 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7238 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7239 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7240 // We can either use a special instruction to load over the low double or
7241 // to move just the low double.
7243 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7245 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7247 if (Subtarget->hasSSE41())
7248 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7252 // Use dedicated unpack instructions for masks that match their pattern.
7253 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7254 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7255 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7256 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7258 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7259 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7260 DAG.getConstant(SHUFPDMask, MVT::i8));
7263 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7265 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7266 /// the integer unit to minimize domain crossing penalties. However, for blends
7267 /// it falls back to the floating point shuffle operation with appropriate bit
7269 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7270 const X86Subtarget *Subtarget,
7271 SelectionDAG &DAG) {
7273 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7274 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7275 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7276 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7277 ArrayRef<int> Mask = SVOp->getMask();
7278 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7280 if (isSingleInputShuffleMask(Mask)) {
7281 // Check for being able to broadcast a single element.
7282 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
7283 Mask, Subtarget, DAG))
7286 // Straight shuffle of a single input vector. For everything from SSE2
7287 // onward this has a single fast instruction with no scary immediates.
7288 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7289 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7290 int WidenedMask[4] = {
7291 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7292 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7294 ISD::BITCAST, DL, MVT::v2i64,
7295 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7296 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7298 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7299 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7300 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7301 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7303 // If we have a blend of two PACKUS operations an the blend aligns with the
7304 // low and half halves, we can just merge the PACKUS operations. This is
7305 // particularly important as it lets us merge shuffles that this routine itself
7307 auto GetPackNode = [](SDValue V) {
7308 while (V.getOpcode() == ISD::BITCAST)
7309 V = V.getOperand(0);
7311 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7313 if (SDValue V1Pack = GetPackNode(V1))
7314 if (SDValue V2Pack = GetPackNode(V2))
7315 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7316 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7317 Mask[0] == 0 ? V1Pack.getOperand(0)
7318 : V1Pack.getOperand(1),
7319 Mask[1] == 2 ? V2Pack.getOperand(0)
7320 : V2Pack.getOperand(1)));
7322 // Try to use shift instructions.
7324 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7327 // When loading a scalar and then shuffling it into a vector we can often do
7328 // the insertion cheaply.
7329 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7330 MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
7332 // Try inverting the insertion since for v2 masks it is easy to do and we
7333 // can't reliably sort the mask one way or the other.
7334 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7335 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7336 MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
7339 // We have different paths for blend lowering, but they all must use the
7340 // *exact* same predicate.
7341 bool IsBlendSupported = Subtarget->hasSSE41();
7342 if (IsBlendSupported)
7343 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7347 // Use dedicated unpack instructions for masks that match their pattern.
7348 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7349 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7350 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7351 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7353 // Try to use byte rotation instructions.
7354 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7355 if (Subtarget->hasSSSE3())
7356 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7357 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7360 // If we have direct support for blends, we should lower by decomposing into
7361 // a permute. That will be faster than the domain cross.
7362 if (IsBlendSupported)
7363 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7366 // We implement this with SHUFPD which is pretty lame because it will likely
7367 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7368 // However, all the alternatives are still more cycles and newer chips don't
7369 // have this problem. It would be really nice if x86 had better shuffles here.
7370 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7371 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7372 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7373 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7376 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7378 /// This is used to disable more specialized lowerings when the shufps lowering
7379 /// will happen to be efficient.
7380 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7381 // This routine only handles 128-bit shufps.
7382 assert(Mask.size() == 4 && "Unsupported mask size!");
7384 // To lower with a single SHUFPS we need to have the low half and high half
7385 // each requiring a single input.
7386 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7388 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7394 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7396 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7397 /// It makes no assumptions about whether this is the *best* lowering, it simply
7399 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7400 ArrayRef<int> Mask, SDValue V1,
7401 SDValue V2, SelectionDAG &DAG) {
7402 SDValue LowV = V1, HighV = V2;
7403 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7406 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7408 if (NumV2Elements == 1) {
7410 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7413 // Compute the index adjacent to V2Index and in the same half by toggling
7415 int V2AdjIndex = V2Index ^ 1;
7417 if (Mask[V2AdjIndex] == -1) {
7418 // Handles all the cases where we have a single V2 element and an undef.
7419 // This will only ever happen in the high lanes because we commute the
7420 // vector otherwise.
7422 std::swap(LowV, HighV);
7423 NewMask[V2Index] -= 4;
7425 // Handle the case where the V2 element ends up adjacent to a V1 element.
7426 // To make this work, blend them together as the first step.
7427 int V1Index = V2AdjIndex;
7428 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7429 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7430 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7432 // Now proceed to reconstruct the final blend as we have the necessary
7433 // high or low half formed.
7440 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7441 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7443 } else if (NumV2Elements == 2) {
7444 if (Mask[0] < 4 && Mask[1] < 4) {
7445 // Handle the easy case where we have V1 in the low lanes and V2 in the
7449 } else if (Mask[2] < 4 && Mask[3] < 4) {
7450 // We also handle the reversed case because this utility may get called
7451 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7452 // arrange things in the right direction.
7458 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7459 // trying to place elements directly, just blend them and set up the final
7460 // shuffle to place them.
7462 // The first two blend mask elements are for V1, the second two are for
7464 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7465 Mask[2] < 4 ? Mask[2] : Mask[3],
7466 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7467 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7468 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7469 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7471 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7474 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7475 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7476 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7477 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7480 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7481 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7484 /// \brief Lower 4-lane 32-bit floating point shuffles.
7486 /// Uses instructions exclusively from the floating point unit to minimize
7487 /// domain crossing penalties, as these are sufficient to implement all v4f32
7489 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7490 const X86Subtarget *Subtarget,
7491 SelectionDAG &DAG) {
7493 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7494 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7495 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7496 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7497 ArrayRef<int> Mask = SVOp->getMask();
7498 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7501 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7503 if (NumV2Elements == 0) {
7504 // Check for being able to broadcast a single element.
7505 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
7506 Mask, Subtarget, DAG))
7509 // Use even/odd duplicate instructions for masks that match their pattern.
7510 if (Subtarget->hasSSE3()) {
7511 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7512 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7513 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7514 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7517 if (Subtarget->hasAVX()) {
7518 // If we have AVX, we can use VPERMILPS which will allow folding a load
7519 // into the shuffle.
7520 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7521 getV4X86ShuffleImm8ForMask(Mask, DAG));
7524 // Otherwise, use a straight shuffle of a single input vector. We pass the
7525 // input vector to both operands to simulate this with a SHUFPS.
7526 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7527 getV4X86ShuffleImm8ForMask(Mask, DAG));
7530 // There are special ways we can lower some single-element blends. However, we
7531 // have custom ways we can lower more complex single-element blends below that
7532 // we defer to if both this and BLENDPS fail to match, so restrict this to
7533 // when the V2 input is targeting element 0 of the mask -- that is the fast
7535 if (NumV2Elements == 1 && Mask[0] >= 4)
7536 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
7537 Mask, Subtarget, DAG))
7540 if (Subtarget->hasSSE41()) {
7541 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7545 // Use INSERTPS if we can complete the shuffle efficiently.
7546 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7549 if (!isSingleSHUFPSMask(Mask))
7550 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7551 DL, MVT::v4f32, V1, V2, Mask, DAG))
7555 // Use dedicated unpack instructions for masks that match their pattern.
7556 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7557 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7558 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7559 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7560 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7561 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7562 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7563 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7565 // Otherwise fall back to a SHUFPS lowering strategy.
7566 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7569 /// \brief Lower 4-lane i32 vector shuffles.
7571 /// We try to handle these with integer-domain shuffles where we can, but for
7572 /// blends we use the floating point domain blend instructions.
7573 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7574 const X86Subtarget *Subtarget,
7575 SelectionDAG &DAG) {
7577 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7578 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7579 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7580 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7581 ArrayRef<int> Mask = SVOp->getMask();
7582 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7584 // Whenever we can lower this as a zext, that instruction is strictly faster
7585 // than any alternative. It also allows us to fold memory operands into the
7586 // shuffle in many cases.
7587 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7588 Mask, Subtarget, DAG))
7592 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7594 if (NumV2Elements == 0) {
7595 // Check for being able to broadcast a single element.
7596 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
7597 Mask, Subtarget, DAG))
7600 // Straight shuffle of a single input vector. For everything from SSE2
7601 // onward this has a single fast instruction with no scary immediates.
7602 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7603 // but we aren't actually going to use the UNPCK instruction because doing
7604 // so prevents folding a load into this instruction or making a copy.
7605 const int UnpackLoMask[] = {0, 0, 1, 1};
7606 const int UnpackHiMask[] = {2, 2, 3, 3};
7607 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7608 Mask = UnpackLoMask;
7609 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7610 Mask = UnpackHiMask;
7612 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7613 getV4X86ShuffleImm8ForMask(Mask, DAG));
7616 // Try to use shift instructions.
7618 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7621 // There are special ways we can lower some single-element blends.
7622 if (NumV2Elements == 1)
7623 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
7624 Mask, Subtarget, DAG))
7627 // We have different paths for blend lowering, but they all must use the
7628 // *exact* same predicate.
7629 bool IsBlendSupported = Subtarget->hasSSE41();
7630 if (IsBlendSupported)
7631 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7635 if (SDValue Masked =
7636 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7639 // Use dedicated unpack instructions for masks that match their pattern.
7640 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7641 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7642 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7643 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7644 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7645 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7646 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7647 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7649 // Try to use byte rotation instructions.
7650 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7651 if (Subtarget->hasSSSE3())
7652 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7653 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7656 // If we have direct support for blends, we should lower by decomposing into
7657 // a permute. That will be faster than the domain cross.
7658 if (IsBlendSupported)
7659 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7662 // Try to lower by permuting the inputs into an unpack instruction.
7663 if (SDValue Unpack =
7664 lowerVectorShuffleAsUnpack(MVT::v4i32, DL, V1, V2, Mask, DAG))
7667 // We implement this with SHUFPS because it can blend from two vectors.
7668 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7669 // up the inputs, bypassing domain shift penalties that we would encur if we
7670 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7672 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7673 DAG.getVectorShuffle(
7675 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7676 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7679 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7680 /// shuffle lowering, and the most complex part.
7682 /// The lowering strategy is to try to form pairs of input lanes which are
7683 /// targeted at the same half of the final vector, and then use a dword shuffle
7684 /// to place them onto the right half, and finally unpack the paired lanes into
7685 /// their final position.
7687 /// The exact breakdown of how to form these dword pairs and align them on the
7688 /// correct sides is really tricky. See the comments within the function for
7689 /// more of the details.
7690 static SDValue lowerV8I16SingleInputVectorShuffle(
7691 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7692 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7693 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7694 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7695 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7697 SmallVector<int, 4> LoInputs;
7698 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7699 [](int M) { return M >= 0; });
7700 std::sort(LoInputs.begin(), LoInputs.end());
7701 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7702 SmallVector<int, 4> HiInputs;
7703 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7704 [](int M) { return M >= 0; });
7705 std::sort(HiInputs.begin(), HiInputs.end());
7706 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7708 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7709 int NumHToL = LoInputs.size() - NumLToL;
7711 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7712 int NumHToH = HiInputs.size() - NumLToH;
7713 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7714 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7715 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7716 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7718 // Check for being able to broadcast a single element.
7719 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
7720 Mask, Subtarget, DAG))
7723 // Try to use shift instructions.
7725 lowerVectorShuffleAsShift(DL, MVT::v8i16, V, V, Mask, DAG))
7728 // Use dedicated unpack instructions for masks that match their pattern.
7729 if (isShuffleEquivalent(V, V, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
7730 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
7731 if (isShuffleEquivalent(V, V, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
7732 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
7734 // Try to use byte rotation instructions.
7735 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7736 DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
7739 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7740 // such inputs we can swap two of the dwords across the half mark and end up
7741 // with <=2 inputs to each half in each half. Once there, we can fall through
7742 // to the generic code below. For example:
7744 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7745 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7747 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7748 // and an existing 2-into-2 on the other half. In this case we may have to
7749 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7750 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7751 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7752 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7753 // half than the one we target for fixing) will be fixed when we re-enter this
7754 // path. We will also combine away any sequence of PSHUFD instructions that
7755 // result into a single instruction. Here is an example of the tricky case:
7757 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7758 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7760 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7762 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7763 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7765 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7766 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7768 // The result is fine to be handled by the generic logic.
7769 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7770 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7771 int AOffset, int BOffset) {
7772 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7773 "Must call this with A having 3 or 1 inputs from the A half.");
7774 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7775 "Must call this with B having 1 or 3 inputs from the B half.");
7776 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7777 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7779 // Compute the index of dword with only one word among the three inputs in
7780 // a half by taking the sum of the half with three inputs and subtracting
7781 // the sum of the actual three inputs. The difference is the remaining
7784 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7785 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7786 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7787 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7788 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7789 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7790 int TripleNonInputIdx =
7791 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7792 TripleDWord = TripleNonInputIdx / 2;
7794 // We use xor with one to compute the adjacent DWord to whichever one the
7796 OneInputDWord = (OneInput / 2) ^ 1;
7798 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7799 // and BToA inputs. If there is also such a problem with the BToB and AToB
7800 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7801 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7802 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7803 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7804 // Compute how many inputs will be flipped by swapping these DWords. We
7806 // to balance this to ensure we don't form a 3-1 shuffle in the other
7808 int NumFlippedAToBInputs =
7809 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7810 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7811 int NumFlippedBToBInputs =
7812 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7813 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7814 if ((NumFlippedAToBInputs == 1 &&
7815 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7816 (NumFlippedBToBInputs == 1 &&
7817 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7818 // We choose whether to fix the A half or B half based on whether that
7819 // half has zero flipped inputs. At zero, we may not be able to fix it
7820 // with that half. We also bias towards fixing the B half because that
7821 // will more commonly be the high half, and we have to bias one way.
7822 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7823 ArrayRef<int> Inputs) {
7824 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7825 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7826 PinnedIdx ^ 1) != Inputs.end();
7827 // Determine whether the free index is in the flipped dword or the
7828 // unflipped dword based on where the pinned index is. We use this bit
7829 // in an xor to conditionally select the adjacent dword.
7830 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7831 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7832 FixFreeIdx) != Inputs.end();
7833 if (IsFixIdxInput == IsFixFreeIdxInput)
7835 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7836 FixFreeIdx) != Inputs.end();
7837 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7838 "We need to be changing the number of flipped inputs!");
7839 int PSHUFHalfMask[] = {0, 1, 2, 3};
7840 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7841 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7843 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7846 if (M != -1 && M == FixIdx)
7848 else if (M != -1 && M == FixFreeIdx)
7851 if (NumFlippedBToBInputs != 0) {
7853 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7854 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7856 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7858 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7859 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7864 int PSHUFDMask[] = {0, 1, 2, 3};
7865 PSHUFDMask[ADWord] = BDWord;
7866 PSHUFDMask[BDWord] = ADWord;
7867 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7868 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7869 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7870 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7872 // Adjust the mask to match the new locations of A and B.
7874 if (M != -1 && M/2 == ADWord)
7875 M = 2 * BDWord + M % 2;
7876 else if (M != -1 && M/2 == BDWord)
7877 M = 2 * ADWord + M % 2;
7879 // Recurse back into this routine to re-compute state now that this isn't
7880 // a 3 and 1 problem.
7881 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7884 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7885 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7886 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7887 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7889 // At this point there are at most two inputs to the low and high halves from
7890 // each half. That means the inputs can always be grouped into dwords and
7891 // those dwords can then be moved to the correct half with a dword shuffle.
7892 // We use at most one low and one high word shuffle to collect these paired
7893 // inputs into dwords, and finally a dword shuffle to place them.
7894 int PSHUFLMask[4] = {-1, -1, -1, -1};
7895 int PSHUFHMask[4] = {-1, -1, -1, -1};
7896 int PSHUFDMask[4] = {-1, -1, -1, -1};
7898 // First fix the masks for all the inputs that are staying in their
7899 // original halves. This will then dictate the targets of the cross-half
7901 auto fixInPlaceInputs =
7902 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7903 MutableArrayRef<int> SourceHalfMask,
7904 MutableArrayRef<int> HalfMask, int HalfOffset) {
7905 if (InPlaceInputs.empty())
7907 if (InPlaceInputs.size() == 1) {
7908 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7909 InPlaceInputs[0] - HalfOffset;
7910 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7913 if (IncomingInputs.empty()) {
7914 // Just fix all of the in place inputs.
7915 for (int Input : InPlaceInputs) {
7916 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7917 PSHUFDMask[Input / 2] = Input / 2;
7922 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7923 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7924 InPlaceInputs[0] - HalfOffset;
7925 // Put the second input next to the first so that they are packed into
7926 // a dword. We find the adjacent index by toggling the low bit.
7927 int AdjIndex = InPlaceInputs[0] ^ 1;
7928 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7929 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7930 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7932 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7933 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7935 // Now gather the cross-half inputs and place them into a free dword of
7936 // their target half.
7937 // FIXME: This operation could almost certainly be simplified dramatically to
7938 // look more like the 3-1 fixing operation.
7939 auto moveInputsToRightHalf = [&PSHUFDMask](
7940 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7941 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7942 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7944 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7945 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7947 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7949 int LowWord = Word & ~1;
7950 int HighWord = Word | 1;
7951 return isWordClobbered(SourceHalfMask, LowWord) ||
7952 isWordClobbered(SourceHalfMask, HighWord);
7955 if (IncomingInputs.empty())
7958 if (ExistingInputs.empty()) {
7959 // Map any dwords with inputs from them into the right half.
7960 for (int Input : IncomingInputs) {
7961 // If the source half mask maps over the inputs, turn those into
7962 // swaps and use the swapped lane.
7963 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7964 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7965 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7966 Input - SourceOffset;
7967 // We have to swap the uses in our half mask in one sweep.
7968 for (int &M : HalfMask)
7969 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7971 else if (M == Input)
7972 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7974 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7975 Input - SourceOffset &&
7976 "Previous placement doesn't match!");
7978 // Note that this correctly re-maps both when we do a swap and when
7979 // we observe the other side of the swap above. We rely on that to
7980 // avoid swapping the members of the input list directly.
7981 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7984 // Map the input's dword into the correct half.
7985 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7986 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7988 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7990 "Previous placement doesn't match!");
7993 // And just directly shift any other-half mask elements to be same-half
7994 // as we will have mirrored the dword containing the element into the
7995 // same position within that half.
7996 for (int &M : HalfMask)
7997 if (M >= SourceOffset && M < SourceOffset + 4) {
7998 M = M - SourceOffset + DestOffset;
7999 assert(M >= 0 && "This should never wrap below zero!");
8004 // Ensure we have the input in a viable dword of its current half. This
8005 // is particularly tricky because the original position may be clobbered
8006 // by inputs being moved and *staying* in that half.
8007 if (IncomingInputs.size() == 1) {
8008 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8009 int InputFixed = std::find(std::begin(SourceHalfMask),
8010 std::end(SourceHalfMask), -1) -
8011 std::begin(SourceHalfMask) + SourceOffset;
8012 SourceHalfMask[InputFixed - SourceOffset] =
8013 IncomingInputs[0] - SourceOffset;
8014 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8016 IncomingInputs[0] = InputFixed;
8018 } else if (IncomingInputs.size() == 2) {
8019 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8020 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8021 // We have two non-adjacent or clobbered inputs we need to extract from
8022 // the source half. To do this, we need to map them into some adjacent
8023 // dword slot in the source mask.
8024 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8025 IncomingInputs[1] - SourceOffset};
8027 // If there is a free slot in the source half mask adjacent to one of
8028 // the inputs, place the other input in it. We use (Index XOR 1) to
8029 // compute an adjacent index.
8030 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8031 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8032 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8033 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8034 InputsFixed[1] = InputsFixed[0] ^ 1;
8035 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8036 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8037 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8038 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8039 InputsFixed[0] = InputsFixed[1] ^ 1;
8040 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8041 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8042 // The two inputs are in the same DWord but it is clobbered and the
8043 // adjacent DWord isn't used at all. Move both inputs to the free
8045 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8046 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8047 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8048 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8050 // The only way we hit this point is if there is no clobbering
8051 // (because there are no off-half inputs to this half) and there is no
8052 // free slot adjacent to one of the inputs. In this case, we have to
8053 // swap an input with a non-input.
8054 for (int i = 0; i < 4; ++i)
8055 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8056 "We can't handle any clobbers here!");
8057 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8058 "Cannot have adjacent inputs here!");
8060 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8061 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8063 // We also have to update the final source mask in this case because
8064 // it may need to undo the above swap.
8065 for (int &M : FinalSourceHalfMask)
8066 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8067 M = InputsFixed[1] + SourceOffset;
8068 else if (M == InputsFixed[1] + SourceOffset)
8069 M = (InputsFixed[0] ^ 1) + SourceOffset;
8071 InputsFixed[1] = InputsFixed[0] ^ 1;
8074 // Point everything at the fixed inputs.
8075 for (int &M : HalfMask)
8076 if (M == IncomingInputs[0])
8077 M = InputsFixed[0] + SourceOffset;
8078 else if (M == IncomingInputs[1])
8079 M = InputsFixed[1] + SourceOffset;
8081 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8082 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8085 llvm_unreachable("Unhandled input size!");
8088 // Now hoist the DWord down to the right half.
8089 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8090 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8091 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8092 for (int &M : HalfMask)
8093 for (int Input : IncomingInputs)
8095 M = FreeDWord * 2 + Input % 2;
8097 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8098 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8099 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8100 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8102 // Now enact all the shuffles we've computed to move the inputs into their
8104 if (!isNoopShuffleMask(PSHUFLMask))
8105 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8106 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8107 if (!isNoopShuffleMask(PSHUFHMask))
8108 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8109 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8110 if (!isNoopShuffleMask(PSHUFDMask))
8111 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8112 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8113 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8114 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8116 // At this point, each half should contain all its inputs, and we can then
8117 // just shuffle them into their final position.
8118 assert(std::count_if(LoMask.begin(), LoMask.end(),
8119 [](int M) { return M >= 4; }) == 0 &&
8120 "Failed to lift all the high half inputs to the low mask!");
8121 assert(std::count_if(HiMask.begin(), HiMask.end(),
8122 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8123 "Failed to lift all the low half inputs to the high mask!");
8125 // Do a half shuffle for the low mask.
8126 if (!isNoopShuffleMask(LoMask))
8127 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8128 getV4X86ShuffleImm8ForMask(LoMask, DAG));
8130 // Do a half shuffle with the high mask after shifting its values down.
8131 for (int &M : HiMask)
8134 if (!isNoopShuffleMask(HiMask))
8135 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8136 getV4X86ShuffleImm8ForMask(HiMask, DAG));
8141 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8142 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8143 SDValue V2, ArrayRef<int> Mask,
8144 SelectionDAG &DAG, bool &V1InUse,
8146 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8152 int Size = Mask.size();
8153 int Scale = 16 / Size;
8154 for (int i = 0; i < 16; ++i) {
8155 if (Mask[i / Scale] == -1) {
8156 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8158 const int ZeroMask = 0x80;
8159 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8161 int V2Idx = Mask[i / Scale] < Size
8163 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8164 if (Zeroable[i / Scale])
8165 V1Idx = V2Idx = ZeroMask;
8166 V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8167 V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8168 V1InUse |= (ZeroMask != V1Idx);
8169 V2InUse |= (ZeroMask != V2Idx);
8174 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8175 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8176 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8178 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8179 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8180 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8182 // If we need shuffled inputs from both, blend the two.
8184 if (V1InUse && V2InUse)
8185 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8187 V = V1InUse ? V1 : V2;
8189 // Cast the result back to the correct type.
8190 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8193 /// \brief Generic lowering of 8-lane i16 shuffles.
8195 /// This handles both single-input shuffles and combined shuffle/blends with
8196 /// two inputs. The single input shuffles are immediately delegated to
8197 /// a dedicated lowering routine.
8199 /// The blends are lowered in one of three fundamental ways. If there are few
8200 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8201 /// of the input is significantly cheaper when lowered as an interleaving of
8202 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8203 /// halves of the inputs separately (making them have relatively few inputs)
8204 /// and then concatenate them.
8205 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8206 const X86Subtarget *Subtarget,
8207 SelectionDAG &DAG) {
8209 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8210 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8211 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8212 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8213 ArrayRef<int> OrigMask = SVOp->getMask();
8214 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8215 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8216 MutableArrayRef<int> Mask(MaskStorage);
8218 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8220 // Whenever we can lower this as a zext, that instruction is strictly faster
8221 // than any alternative.
8222 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8223 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8226 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8228 auto isV2 = [](int M) { return M >= 8; };
8230 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8232 if (NumV2Inputs == 0)
8233 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8235 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8236 "All single-input shuffles should be canonicalized to be V1-input "
8239 // Try to use shift instructions.
8241 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8244 // There are special ways we can lower some single-element blends.
8245 if (NumV2Inputs == 1)
8246 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
8247 Mask, Subtarget, DAG))
8250 // We have different paths for blend lowering, but they all must use the
8251 // *exact* same predicate.
8252 bool IsBlendSupported = Subtarget->hasSSE41();
8253 if (IsBlendSupported)
8254 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8258 if (SDValue Masked =
8259 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8262 // Use dedicated unpack instructions for masks that match their pattern.
8263 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8264 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8265 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8266 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8268 // Try to use byte rotation instructions.
8269 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8270 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8273 if (SDValue BitBlend =
8274 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8277 if (SDValue Unpack =
8278 lowerVectorShuffleAsUnpack(MVT::v8i16, DL, V1, V2, Mask, DAG))
8281 // If we can't directly blend but can use PSHUFB, that will be better as it
8282 // can both shuffle and set up the inefficient blend.
8283 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8284 bool V1InUse, V2InUse;
8285 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8289 // We can always bit-blend if we have to so the fallback strategy is to
8290 // decompose into single-input permutes and blends.
8291 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8295 /// \brief Check whether a compaction lowering can be done by dropping even
8296 /// elements and compute how many times even elements must be dropped.
8298 /// This handles shuffles which take every Nth element where N is a power of
8299 /// two. Example shuffle masks:
8301 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8302 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8303 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8304 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8305 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8306 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8308 /// Any of these lanes can of course be undef.
8310 /// This routine only supports N <= 3.
8311 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8314 /// \returns N above, or the number of times even elements must be dropped if
8315 /// there is such a number. Otherwise returns zero.
8316 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8317 // Figure out whether we're looping over two inputs or just one.
8318 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8320 // The modulus for the shuffle vector entries is based on whether this is
8321 // a single input or not.
8322 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8323 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8324 "We should only be called with masks with a power-of-2 size!");
8326 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8328 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8329 // and 2^3 simultaneously. This is because we may have ambiguity with
8330 // partially undef inputs.
8331 bool ViableForN[3] = {true, true, true};
8333 for (int i = 0, e = Mask.size(); i < e; ++i) {
8334 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8339 bool IsAnyViable = false;
8340 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8341 if (ViableForN[j]) {
8344 // The shuffle mask must be equal to (i * 2^N) % M.
8345 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8348 ViableForN[j] = false;
8350 // Early exit if we exhaust the possible powers of two.
8355 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8359 // Return 0 as there is no viable power of two.
8363 /// \brief Generic lowering of v16i8 shuffles.
8365 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8366 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8367 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8368 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8370 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8371 const X86Subtarget *Subtarget,
8372 SelectionDAG &DAG) {
8374 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8375 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8376 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8377 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8378 ArrayRef<int> Mask = SVOp->getMask();
8379 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8381 // Try to use shift instructions.
8383 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8386 // Try to use byte rotation instructions.
8387 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8388 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8391 // Try to use a zext lowering.
8392 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8393 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8397 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8399 // For single-input shuffles, there are some nicer lowering tricks we can use.
8400 if (NumV2Elements == 0) {
8401 // Check for being able to broadcast a single element.
8402 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
8403 Mask, Subtarget, DAG))
8406 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8407 // Notably, this handles splat and partial-splat shuffles more efficiently.
8408 // However, it only makes sense if the pre-duplication shuffle simplifies
8409 // things significantly. Currently, this means we need to be able to
8410 // express the pre-duplication shuffle as an i16 shuffle.
8412 // FIXME: We should check for other patterns which can be widened into an
8413 // i16 shuffle as well.
8414 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8415 for (int i = 0; i < 16; i += 2)
8416 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8421 auto tryToWidenViaDuplication = [&]() -> SDValue {
8422 if (!canWidenViaDuplication(Mask))
8424 SmallVector<int, 4> LoInputs;
8425 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8426 [](int M) { return M >= 0 && M < 8; });
8427 std::sort(LoInputs.begin(), LoInputs.end());
8428 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8430 SmallVector<int, 4> HiInputs;
8431 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8432 [](int M) { return M >= 8; });
8433 std::sort(HiInputs.begin(), HiInputs.end());
8434 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8437 bool TargetLo = LoInputs.size() >= HiInputs.size();
8438 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8439 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8441 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8442 SmallDenseMap<int, int, 8> LaneMap;
8443 for (int I : InPlaceInputs) {
8444 PreDupI16Shuffle[I/2] = I/2;
8447 int j = TargetLo ? 0 : 4, je = j + 4;
8448 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8449 // Check if j is already a shuffle of this input. This happens when
8450 // there are two adjacent bytes after we move the low one.
8451 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8452 // If we haven't yet mapped the input, search for a slot into which
8454 while (j < je && PreDupI16Shuffle[j] != -1)
8458 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8461 // Map this input with the i16 shuffle.
8462 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8465 // Update the lane map based on the mapping we ended up with.
8466 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8469 ISD::BITCAST, DL, MVT::v16i8,
8470 DAG.getVectorShuffle(MVT::v8i16, DL,
8471 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8472 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8474 // Unpack the bytes to form the i16s that will be shuffled into place.
8475 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8476 MVT::v16i8, V1, V1);
8478 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8479 for (int i = 0; i < 16; ++i)
8480 if (Mask[i] != -1) {
8481 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8482 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8483 if (PostDupI16Shuffle[i / 2] == -1)
8484 PostDupI16Shuffle[i / 2] = MappedMask;
8486 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8487 "Conflicting entrties in the original shuffle!");
8490 ISD::BITCAST, DL, MVT::v16i8,
8491 DAG.getVectorShuffle(MVT::v8i16, DL,
8492 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8493 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8495 if (SDValue V = tryToWidenViaDuplication())
8499 // Use dedicated unpack instructions for masks that match their pattern.
8500 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8501 0, 16, 1, 17, 2, 18, 3, 19,
8503 4, 20, 5, 21, 6, 22, 7, 23}))
8504 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8505 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8506 8, 24, 9, 25, 10, 26, 11, 27,
8508 12, 28, 13, 29, 14, 30, 15, 31}))
8509 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8511 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8512 // with PSHUFB. It is important to do this before we attempt to generate any
8513 // blends but after all of the single-input lowerings. If the single input
8514 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8515 // want to preserve that and we can DAG combine any longer sequences into
8516 // a PSHUFB in the end. But once we start blending from multiple inputs,
8517 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8518 // and there are *very* few patterns that would actually be faster than the
8519 // PSHUFB approach because of its ability to zero lanes.
8521 // FIXME: The only exceptions to the above are blends which are exact
8522 // interleavings with direct instructions supporting them. We currently don't
8523 // handle those well here.
8524 if (Subtarget->hasSSSE3()) {
8525 bool V1InUse = false;
8526 bool V2InUse = false;
8528 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8529 DAG, V1InUse, V2InUse);
8531 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8532 // do so. This avoids using them to handle blends-with-zero which is
8533 // important as a single pshufb is significantly faster for that.
8534 if (V1InUse && V2InUse) {
8535 if (Subtarget->hasSSE41())
8536 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8537 Mask, Subtarget, DAG))
8540 // We can use an unpack to do the blending rather than an or in some
8541 // cases. Even though the or may be (very minorly) more efficient, we
8542 // preference this lowering because there are common cases where part of
8543 // the complexity of the shuffles goes away when we do the final blend as
8545 // FIXME: It might be worth trying to detect if the unpack-feeding
8546 // shuffles will both be pshufb, in which case we shouldn't bother with
8548 if (SDValue Unpack =
8549 lowerVectorShuffleAsUnpack(MVT::v16i8, DL, V1, V2, Mask, DAG))
8556 // There are special ways we can lower some single-element blends.
8557 if (NumV2Elements == 1)
8558 if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
8559 Mask, Subtarget, DAG))
8562 if (SDValue BitBlend =
8563 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8566 // Check whether a compaction lowering can be done. This handles shuffles
8567 // which take every Nth element for some even N. See the helper function for
8570 // We special case these as they can be particularly efficiently handled with
8571 // the PACKUSB instruction on x86 and they show up in common patterns of
8572 // rearranging bytes to truncate wide elements.
8573 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8574 // NumEvenDrops is the power of two stride of the elements. Another way of
8575 // thinking about it is that we need to drop the even elements this many
8576 // times to get the original input.
8577 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8579 // First we need to zero all the dropped bytes.
8580 assert(NumEvenDrops <= 3 &&
8581 "No support for dropping even elements more than 3 times.");
8582 // We use the mask type to pick which bytes are preserved based on how many
8583 // elements are dropped.
8584 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8585 SDValue ByteClearMask =
8586 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8587 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8588 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8590 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8592 // Now pack things back together.
8593 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8594 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8595 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8596 for (int i = 1; i < NumEvenDrops; ++i) {
8597 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8598 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8604 // Handle multi-input cases by blending single-input shuffles.
8605 if (NumV2Elements > 0)
8606 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8609 // The fallback path for single-input shuffles widens this into two v8i16
8610 // vectors with unpacks, shuffles those, and then pulls them back together
8614 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8615 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8616 for (int i = 0; i < 16; ++i)
8618 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8620 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8622 SDValue VLoHalf, VHiHalf;
8623 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8624 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8626 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8627 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8628 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8629 [](int M) { return M >= 0 && M % 2 == 1; })) {
8630 // Use a mask to drop the high bytes.
8631 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8632 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8633 DAG.getConstant(0x00FF, MVT::v8i16));
8635 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8636 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8638 // Squash the masks to point directly into VLoHalf.
8639 for (int &M : LoBlendMask)
8642 for (int &M : HiBlendMask)
8646 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8647 // VHiHalf so that we can blend them as i16s.
8648 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8649 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8650 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8651 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8654 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8655 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8657 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8660 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8662 /// This routine breaks down the specific type of 128-bit shuffle and
8663 /// dispatches to the lowering routines accordingly.
8664 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8665 MVT VT, const X86Subtarget *Subtarget,
8666 SelectionDAG &DAG) {
8667 switch (VT.SimpleTy) {
8669 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8671 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8673 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8675 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8677 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8679 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8682 llvm_unreachable("Unimplemented!");
8686 /// \brief Helper function to test whether a shuffle mask could be
8687 /// simplified by widening the elements being shuffled.
8689 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8690 /// leaves it in an unspecified state.
8692 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8693 /// shuffle masks. The latter have the special property of a '-2' representing
8694 /// a zero-ed lane of a vector.
8695 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8696 SmallVectorImpl<int> &WidenedMask) {
8697 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8698 // If both elements are undef, its trivial.
8699 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8700 WidenedMask.push_back(SM_SentinelUndef);
8704 // Check for an undef mask and a mask value properly aligned to fit with
8705 // a pair of values. If we find such a case, use the non-undef mask's value.
8706 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8707 WidenedMask.push_back(Mask[i + 1] / 2);
8710 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8711 WidenedMask.push_back(Mask[i] / 2);
8715 // When zeroing, we need to spread the zeroing across both lanes to widen.
8716 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8717 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8718 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8719 WidenedMask.push_back(SM_SentinelZero);
8725 // Finally check if the two mask values are adjacent and aligned with
8727 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8728 WidenedMask.push_back(Mask[i] / 2);
8732 // Otherwise we can't safely widen the elements used in this shuffle.
8735 assert(WidenedMask.size() == Mask.size() / 2 &&
8736 "Incorrect size of mask after widening the elements!");
8741 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8743 /// This routine just extracts two subvectors, shuffles them independently, and
8744 /// then concatenates them back together. This should work effectively with all
8745 /// AVX vector shuffle types.
8746 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8747 SDValue V2, ArrayRef<int> Mask,
8748 SelectionDAG &DAG) {
8749 assert(VT.getSizeInBits() >= 256 &&
8750 "Only for 256-bit or wider vector shuffles!");
8751 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8752 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8754 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8755 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8757 int NumElements = VT.getVectorNumElements();
8758 int SplitNumElements = NumElements / 2;
8759 MVT ScalarVT = VT.getScalarType();
8760 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8762 // Rather than splitting build-vectors, just build two narrower build
8763 // vectors. This helps shuffling with splats and zeros.
8764 auto SplitVector = [&](SDValue V) {
8765 while (V.getOpcode() == ISD::BITCAST)
8766 V = V->getOperand(0);
8768 MVT OrigVT = V.getSimpleValueType();
8769 int OrigNumElements = OrigVT.getVectorNumElements();
8770 int OrigSplitNumElements = OrigNumElements / 2;
8771 MVT OrigScalarVT = OrigVT.getScalarType();
8772 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8776 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8778 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8779 DAG.getIntPtrConstant(0));
8780 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8781 DAG.getIntPtrConstant(OrigSplitNumElements));
8784 SmallVector<SDValue, 16> LoOps, HiOps;
8785 for (int i = 0; i < OrigSplitNumElements; ++i) {
8786 LoOps.push_back(BV->getOperand(i));
8787 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8789 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8790 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8792 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8793 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8796 SDValue LoV1, HiV1, LoV2, HiV2;
8797 std::tie(LoV1, HiV1) = SplitVector(V1);
8798 std::tie(LoV2, HiV2) = SplitVector(V2);
8800 // Now create two 4-way blends of these half-width vectors.
8801 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8802 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8803 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8804 for (int i = 0; i < SplitNumElements; ++i) {
8805 int M = HalfMask[i];
8806 if (M >= NumElements) {
8807 if (M >= NumElements + SplitNumElements)
8811 V2BlendMask.push_back(M - NumElements);
8812 V1BlendMask.push_back(-1);
8813 BlendMask.push_back(SplitNumElements + i);
8814 } else if (M >= 0) {
8815 if (M >= SplitNumElements)
8819 V2BlendMask.push_back(-1);
8820 V1BlendMask.push_back(M);
8821 BlendMask.push_back(i);
8823 V2BlendMask.push_back(-1);
8824 V1BlendMask.push_back(-1);
8825 BlendMask.push_back(-1);
8829 // Because the lowering happens after all combining takes place, we need to
8830 // manually combine these blend masks as much as possible so that we create
8831 // a minimal number of high-level vector shuffle nodes.
8833 // First try just blending the halves of V1 or V2.
8834 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8835 return DAG.getUNDEF(SplitVT);
8836 if (!UseLoV2 && !UseHiV2)
8837 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8838 if (!UseLoV1 && !UseHiV1)
8839 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8841 SDValue V1Blend, V2Blend;
8842 if (UseLoV1 && UseHiV1) {
8844 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8846 // We only use half of V1 so map the usage down into the final blend mask.
8847 V1Blend = UseLoV1 ? LoV1 : HiV1;
8848 for (int i = 0; i < SplitNumElements; ++i)
8849 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8850 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8852 if (UseLoV2 && UseHiV2) {
8854 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8856 // We only use half of V2 so map the usage down into the final blend mask.
8857 V2Blend = UseLoV2 ? LoV2 : HiV2;
8858 for (int i = 0; i < SplitNumElements; ++i)
8859 if (BlendMask[i] >= SplitNumElements)
8860 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8862 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8864 SDValue Lo = HalfBlend(LoMask);
8865 SDValue Hi = HalfBlend(HiMask);
8866 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8869 /// \brief Either split a vector in halves or decompose the shuffles and the
8872 /// This is provided as a good fallback for many lowerings of non-single-input
8873 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8874 /// between splitting the shuffle into 128-bit components and stitching those
8875 /// back together vs. extracting the single-input shuffles and blending those
8877 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8878 SDValue V2, ArrayRef<int> Mask,
8879 SelectionDAG &DAG) {
8880 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8881 "lower single-input shuffles as it "
8882 "could then recurse on itself.");
8883 int Size = Mask.size();
8885 // If this can be modeled as a broadcast of two elements followed by a blend,
8886 // prefer that lowering. This is especially important because broadcasts can
8887 // often fold with memory operands.
8888 auto DoBothBroadcast = [&] {
8889 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8892 if (V2BroadcastIdx == -1)
8893 V2BroadcastIdx = M - Size;
8894 else if (M - Size != V2BroadcastIdx)
8896 } else if (M >= 0) {
8897 if (V1BroadcastIdx == -1)
8899 else if (M != V1BroadcastIdx)
8904 if (DoBothBroadcast())
8905 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8908 // If the inputs all stem from a single 128-bit lane of each input, then we
8909 // split them rather than blending because the split will decompose to
8910 // unusually few instructions.
8911 int LaneCount = VT.getSizeInBits() / 128;
8912 int LaneSize = Size / LaneCount;
8913 SmallBitVector LaneInputs[2];
8914 LaneInputs[0].resize(LaneCount, false);
8915 LaneInputs[1].resize(LaneCount, false);
8916 for (int i = 0; i < Size; ++i)
8918 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8919 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8920 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8922 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8923 // that the decomposed single-input shuffles don't end up here.
8924 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8927 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8928 /// a permutation and blend of those lanes.
8930 /// This essentially blends the out-of-lane inputs to each lane into the lane
8931 /// from a permuted copy of the vector. This lowering strategy results in four
8932 /// instructions in the worst case for a single-input cross lane shuffle which
8933 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8934 /// of. Special cases for each particular shuffle pattern should be handled
8935 /// prior to trying this lowering.
8936 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8937 SDValue V1, SDValue V2,
8939 SelectionDAG &DAG) {
8940 // FIXME: This should probably be generalized for 512-bit vectors as well.
8941 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8942 int LaneSize = Mask.size() / 2;
8944 // If there are only inputs from one 128-bit lane, splitting will in fact be
8945 // less expensive. The flags track wether the given lane contains an element
8946 // that crosses to another lane.
8947 bool LaneCrossing[2] = {false, false};
8948 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8949 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8950 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8951 if (!LaneCrossing[0] || !LaneCrossing[1])
8952 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8954 if (isSingleInputShuffleMask(Mask)) {
8955 SmallVector<int, 32> FlippedBlendMask;
8956 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8957 FlippedBlendMask.push_back(
8958 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8960 : Mask[i] % LaneSize +
8961 (i / LaneSize) * LaneSize + Size));
8963 // Flip the vector, and blend the results which should now be in-lane. The
8964 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8965 // 5 for the high source. The value 3 selects the high half of source 2 and
8966 // the value 2 selects the low half of source 2. We only use source 2 to
8967 // allow folding it into a memory operand.
8968 unsigned PERMMask = 3 | 2 << 4;
8969 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
8970 V1, DAG.getConstant(PERMMask, MVT::i8));
8971 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
8974 // This now reduces to two single-input shuffles of V1 and V2 which at worst
8975 // will be handled by the above logic and a blend of the results, much like
8976 // other patterns in AVX.
8977 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8980 /// \brief Handle lowering 2-lane 128-bit shuffles.
8981 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8982 SDValue V2, ArrayRef<int> Mask,
8983 const X86Subtarget *Subtarget,
8984 SelectionDAG &DAG) {
8985 // Blends are faster and handle all the non-lane-crossing cases.
8986 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
8990 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
8991 VT.getVectorNumElements() / 2);
8992 // Check for patterns which can be matched with a single insert of a 128-bit
8994 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}) ||
8995 isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
8996 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
8997 DAG.getIntPtrConstant(0));
8998 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
8999 Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9000 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9002 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9003 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9004 DAG.getIntPtrConstant(0));
9005 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9006 DAG.getIntPtrConstant(2));
9007 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9010 // Otherwise form a 128-bit permutation.
9011 // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9012 unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9013 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9014 DAG.getConstant(PermMask, MVT::i8));
9017 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9018 /// shuffling each lane.
9020 /// This will only succeed when the result of fixing the 128-bit lanes results
9021 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9022 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9023 /// the lane crosses early and then use simpler shuffles within each lane.
9025 /// FIXME: It might be worthwhile at some point to support this without
9026 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9027 /// in x86 only floating point has interesting non-repeating shuffles, and even
9028 /// those are still *marginally* more expensive.
9029 static SDValue lowerVectorShuffleByMerging128BitLanes(
9030 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9031 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9032 assert(!isSingleInputShuffleMask(Mask) &&
9033 "This is only useful with multiple inputs.");
9035 int Size = Mask.size();
9036 int LaneSize = 128 / VT.getScalarSizeInBits();
9037 int NumLanes = Size / LaneSize;
9038 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9040 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9041 // check whether the in-128-bit lane shuffles share a repeating pattern.
9042 SmallVector<int, 4> Lanes;
9043 Lanes.resize(NumLanes, -1);
9044 SmallVector<int, 4> InLaneMask;
9045 InLaneMask.resize(LaneSize, -1);
9046 for (int i = 0; i < Size; ++i) {
9050 int j = i / LaneSize;
9053 // First entry we've seen for this lane.
9054 Lanes[j] = Mask[i] / LaneSize;
9055 } else if (Lanes[j] != Mask[i] / LaneSize) {
9056 // This doesn't match the lane selected previously!
9060 // Check that within each lane we have a consistent shuffle mask.
9061 int k = i % LaneSize;
9062 if (InLaneMask[k] < 0) {
9063 InLaneMask[k] = Mask[i] % LaneSize;
9064 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9065 // This doesn't fit a repeating in-lane mask.
9070 // First shuffle the lanes into place.
9071 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9072 VT.getSizeInBits() / 64);
9073 SmallVector<int, 8> LaneMask;
9074 LaneMask.resize(NumLanes * 2, -1);
9075 for (int i = 0; i < NumLanes; ++i)
9076 if (Lanes[i] >= 0) {
9077 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9078 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9081 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9082 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9083 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9085 // Cast it back to the type we actually want.
9086 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9088 // Now do a simple shuffle that isn't lane crossing.
9089 SmallVector<int, 8> NewMask;
9090 NewMask.resize(Size, -1);
9091 for (int i = 0; i < Size; ++i)
9093 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9094 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9095 "Must not introduce lane crosses at this point!");
9097 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9100 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9103 /// This returns true if the elements from a particular input are already in the
9104 /// slot required by the given mask and require no permutation.
9105 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9106 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9107 int Size = Mask.size();
9108 for (int i = 0; i < Size; ++i)
9109 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9115 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9117 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9118 /// isn't available.
9119 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9120 const X86Subtarget *Subtarget,
9121 SelectionDAG &DAG) {
9123 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9124 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9125 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9126 ArrayRef<int> Mask = SVOp->getMask();
9127 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9129 SmallVector<int, 4> WidenedMask;
9130 if (canWidenShuffleElements(Mask, WidenedMask))
9131 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9134 if (isSingleInputShuffleMask(Mask)) {
9135 // Check for being able to broadcast a single element.
9136 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
9137 Mask, Subtarget, DAG))
9140 // Use low duplicate instructions for masks that match their pattern.
9141 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9142 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9144 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9145 // Non-half-crossing single input shuffles can be lowerid with an
9146 // interleaved permutation.
9147 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9148 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9149 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9150 DAG.getConstant(VPERMILPMask, MVT::i8));
9153 // With AVX2 we have direct support for this permutation.
9154 if (Subtarget->hasAVX2())
9155 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9156 getV4X86ShuffleImm8ForMask(Mask, DAG));
9158 // Otherwise, fall back.
9159 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9163 // X86 has dedicated unpack instructions that can handle specific blend
9164 // operations: UNPCKH and UNPCKL.
9165 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9166 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9167 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9168 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9169 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9170 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9171 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9172 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9174 // If we have a single input to the zero element, insert that into V1 if we
9175 // can do so cheaply.
9177 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9178 if (NumV2Elements == 1 && Mask[0] >= 4)
9179 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9180 MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
9183 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9187 // Check if the blend happens to exactly fit that of SHUFPD.
9188 if ((Mask[0] == -1 || Mask[0] < 2) &&
9189 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9190 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9191 (Mask[3] == -1 || Mask[3] >= 6)) {
9192 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9193 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9194 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9195 DAG.getConstant(SHUFPDMask, MVT::i8));
9197 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9198 (Mask[1] == -1 || Mask[1] < 2) &&
9199 (Mask[2] == -1 || Mask[2] >= 6) &&
9200 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9201 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9202 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9203 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9204 DAG.getConstant(SHUFPDMask, MVT::i8));
9207 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9208 // shuffle. However, if we have AVX2 and either inputs are already in place,
9209 // we will be able to shuffle even across lanes the other input in a single
9210 // instruction so skip this pattern.
9211 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9212 isShuffleMaskInputInPlace(1, Mask))))
9213 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9214 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9217 // If we have AVX2 then we always want to lower with a blend because an v4 we
9218 // can fully permute the elements.
9219 if (Subtarget->hasAVX2())
9220 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9223 // Otherwise fall back on generic lowering.
9224 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9227 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9229 /// This routine is only called when we have AVX2 and thus a reasonable
9230 /// instruction set for v4i64 shuffling..
9231 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9232 const X86Subtarget *Subtarget,
9233 SelectionDAG &DAG) {
9235 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9236 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9237 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9238 ArrayRef<int> Mask = SVOp->getMask();
9239 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9240 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9242 SmallVector<int, 4> WidenedMask;
9243 if (canWidenShuffleElements(Mask, WidenedMask))
9244 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9247 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9251 // Check for being able to broadcast a single element.
9252 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
9253 Mask, Subtarget, DAG))
9256 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9257 // use lower latency instructions that will operate on both 128-bit lanes.
9258 SmallVector<int, 2> RepeatedMask;
9259 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9260 if (isSingleInputShuffleMask(Mask)) {
9261 int PSHUFDMask[] = {-1, -1, -1, -1};
9262 for (int i = 0; i < 2; ++i)
9263 if (RepeatedMask[i] >= 0) {
9264 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9265 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9268 ISD::BITCAST, DL, MVT::v4i64,
9269 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9270 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9271 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9275 // AVX2 provides a direct instruction for permuting a single input across
9277 if (isSingleInputShuffleMask(Mask))
9278 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9279 getV4X86ShuffleImm8ForMask(Mask, DAG));
9281 // Try to use shift instructions.
9283 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9286 // Use dedicated unpack instructions for masks that match their pattern.
9287 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9288 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9289 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9290 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9291 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9292 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9293 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9294 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9296 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9297 // shuffle. However, if we have AVX2 and either inputs are already in place,
9298 // we will be able to shuffle even across lanes the other input in a single
9299 // instruction so skip this pattern.
9300 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9301 isShuffleMaskInputInPlace(1, Mask))))
9302 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9303 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9306 // Otherwise fall back on generic blend lowering.
9307 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9311 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9313 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9314 /// isn't available.
9315 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9316 const X86Subtarget *Subtarget,
9317 SelectionDAG &DAG) {
9319 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9320 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9321 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9322 ArrayRef<int> Mask = SVOp->getMask();
9323 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9325 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9329 // Check for being able to broadcast a single element.
9330 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
9331 Mask, Subtarget, DAG))
9334 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9335 // options to efficiently lower the shuffle.
9336 SmallVector<int, 4> RepeatedMask;
9337 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9338 assert(RepeatedMask.size() == 4 &&
9339 "Repeated masks must be half the mask width!");
9341 // Use even/odd duplicate instructions for masks that match their pattern.
9342 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9343 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9344 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9345 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9347 if (isSingleInputShuffleMask(Mask))
9348 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9349 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9351 // Use dedicated unpack instructions for masks that match their pattern.
9352 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9353 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9354 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9355 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9356 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9357 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9358 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9359 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9361 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9362 // have already handled any direct blends. We also need to squash the
9363 // repeated mask into a simulated v4f32 mask.
9364 for (int i = 0; i < 4; ++i)
9365 if (RepeatedMask[i] >= 8)
9366 RepeatedMask[i] -= 4;
9367 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9370 // If we have a single input shuffle with different shuffle patterns in the
9371 // two 128-bit lanes use the variable mask to VPERMILPS.
9372 if (isSingleInputShuffleMask(Mask)) {
9373 SDValue VPermMask[8];
9374 for (int i = 0; i < 8; ++i)
9375 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9376 : DAG.getConstant(Mask[i], MVT::i32);
9377 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9379 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9380 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9382 if (Subtarget->hasAVX2())
9383 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9384 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9385 DAG.getNode(ISD::BUILD_VECTOR, DL,
9386 MVT::v8i32, VPermMask)),
9389 // Otherwise, fall back.
9390 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9394 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9396 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9397 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9400 // If we have AVX2 then we always want to lower with a blend because at v8 we
9401 // can fully permute the elements.
9402 if (Subtarget->hasAVX2())
9403 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9406 // Otherwise fall back on generic lowering.
9407 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9410 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9412 /// This routine is only called when we have AVX2 and thus a reasonable
9413 /// instruction set for v8i32 shuffling..
9414 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9415 const X86Subtarget *Subtarget,
9416 SelectionDAG &DAG) {
9418 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9419 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9420 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9421 ArrayRef<int> Mask = SVOp->getMask();
9422 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9423 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9425 // Whenever we can lower this as a zext, that instruction is strictly faster
9426 // than any alternative. It also allows us to fold memory operands into the
9427 // shuffle in many cases.
9428 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9429 Mask, Subtarget, DAG))
9432 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9436 // Check for being able to broadcast a single element.
9437 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
9438 Mask, Subtarget, DAG))
9441 // If the shuffle mask is repeated in each 128-bit lane we can use more
9442 // efficient instructions that mirror the shuffles across the two 128-bit
9444 SmallVector<int, 4> RepeatedMask;
9445 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9446 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9447 if (isSingleInputShuffleMask(Mask))
9448 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9449 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9451 // Use dedicated unpack instructions for masks that match their pattern.
9452 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9453 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9454 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9455 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9456 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9457 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9458 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9459 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9462 // Try to use shift instructions.
9464 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9467 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9468 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9471 // If the shuffle patterns aren't repeated but it is a single input, directly
9472 // generate a cross-lane VPERMD instruction.
9473 if (isSingleInputShuffleMask(Mask)) {
9474 SDValue VPermMask[8];
9475 for (int i = 0; i < 8; ++i)
9476 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9477 : DAG.getConstant(Mask[i], MVT::i32);
9479 X86ISD::VPERMV, DL, MVT::v8i32,
9480 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9483 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9485 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9486 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9489 // Otherwise fall back on generic blend lowering.
9490 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9494 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9496 /// This routine is only called when we have AVX2 and thus a reasonable
9497 /// instruction set for v16i16 shuffling..
9498 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9499 const X86Subtarget *Subtarget,
9500 SelectionDAG &DAG) {
9502 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9503 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9504 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9505 ArrayRef<int> Mask = SVOp->getMask();
9506 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9507 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9509 // Whenever we can lower this as a zext, that instruction is strictly faster
9510 // than any alternative. It also allows us to fold memory operands into the
9511 // shuffle in many cases.
9512 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9513 Mask, Subtarget, DAG))
9516 // Check for being able to broadcast a single element.
9517 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
9518 Mask, Subtarget, DAG))
9521 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9525 // Use dedicated unpack instructions for masks that match their pattern.
9526 if (isShuffleEquivalent(V1, V2, Mask,
9527 {// First 128-bit lane:
9528 0, 16, 1, 17, 2, 18, 3, 19,
9529 // Second 128-bit lane:
9530 8, 24, 9, 25, 10, 26, 11, 27}))
9531 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9532 if (isShuffleEquivalent(V1, V2, Mask,
9533 {// First 128-bit lane:
9534 4, 20, 5, 21, 6, 22, 7, 23,
9535 // Second 128-bit lane:
9536 12, 28, 13, 29, 14, 30, 15, 31}))
9537 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9539 // Try to use shift instructions.
9541 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9544 // Try to use byte rotation instructions.
9545 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9546 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9549 if (isSingleInputShuffleMask(Mask)) {
9550 // There are no generalized cross-lane shuffle operations available on i16
9552 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9553 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9556 SDValue PSHUFBMask[32];
9557 for (int i = 0; i < 16; ++i) {
9558 if (Mask[i] == -1) {
9559 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9563 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9564 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9565 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9566 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9569 ISD::BITCAST, DL, MVT::v16i16,
9571 X86ISD::PSHUFB, DL, MVT::v32i8,
9572 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9573 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9576 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9578 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9579 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9582 // Otherwise fall back on generic lowering.
9583 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9586 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9588 /// This routine is only called when we have AVX2 and thus a reasonable
9589 /// instruction set for v32i8 shuffling..
9590 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9591 const X86Subtarget *Subtarget,
9592 SelectionDAG &DAG) {
9594 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9595 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9596 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9597 ArrayRef<int> Mask = SVOp->getMask();
9598 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9599 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9601 // Whenever we can lower this as a zext, that instruction is strictly faster
9602 // than any alternative. It also allows us to fold memory operands into the
9603 // shuffle in many cases.
9604 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9605 Mask, Subtarget, DAG))
9608 // Check for being able to broadcast a single element.
9609 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
9610 Mask, Subtarget, DAG))
9613 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9617 // Use dedicated unpack instructions for masks that match their pattern.
9618 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9620 if (isShuffleEquivalent(
9622 {// First 128-bit lane:
9623 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9624 // Second 128-bit lane:
9625 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9626 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9627 if (isShuffleEquivalent(
9629 {// First 128-bit lane:
9630 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9631 // Second 128-bit lane:
9632 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9633 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9635 // Try to use shift instructions.
9637 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9640 // Try to use byte rotation instructions.
9641 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9642 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9645 if (isSingleInputShuffleMask(Mask)) {
9646 // There are no generalized cross-lane shuffle operations available on i8
9648 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9649 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9652 SDValue PSHUFBMask[32];
9653 for (int i = 0; i < 32; ++i)
9656 ? DAG.getUNDEF(MVT::i8)
9657 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9660 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9661 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9664 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9666 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9667 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9670 // Otherwise fall back on generic lowering.
9671 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9674 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9676 /// This routine either breaks down the specific type of a 256-bit x86 vector
9677 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9678 /// together based on the available instructions.
9679 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9680 MVT VT, const X86Subtarget *Subtarget,
9681 SelectionDAG &DAG) {
9683 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9684 ArrayRef<int> Mask = SVOp->getMask();
9686 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9687 // check for those subtargets here and avoid much of the subtarget querying in
9688 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9689 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9690 // floating point types there eventually, just immediately cast everything to
9691 // a float and operate entirely in that domain.
9692 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9693 int ElementBits = VT.getScalarSizeInBits();
9694 if (ElementBits < 32)
9695 // No floating point type available, decompose into 128-bit vectors.
9696 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9698 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9699 VT.getVectorNumElements());
9700 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9701 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9702 return DAG.getNode(ISD::BITCAST, DL, VT,
9703 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9706 switch (VT.SimpleTy) {
9708 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9710 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9712 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9714 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9716 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9718 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9721 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9725 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9726 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9727 const X86Subtarget *Subtarget,
9728 SelectionDAG &DAG) {
9730 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9731 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9732 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9733 ArrayRef<int> Mask = SVOp->getMask();
9734 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9736 // X86 has dedicated unpack instructions that can handle specific blend
9737 // operations: UNPCKH and UNPCKL.
9738 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9739 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9740 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9741 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9743 // FIXME: Implement direct support for this type!
9744 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9747 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9748 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9749 const X86Subtarget *Subtarget,
9750 SelectionDAG &DAG) {
9752 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9753 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9754 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9755 ArrayRef<int> Mask = SVOp->getMask();
9756 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9758 // Use dedicated unpack instructions for masks that match their pattern.
9759 if (isShuffleEquivalent(V1, V2, Mask,
9760 {// First 128-bit lane.
9761 0, 16, 1, 17, 4, 20, 5, 21,
9762 // Second 128-bit lane.
9763 8, 24, 9, 25, 12, 28, 13, 29}))
9764 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9765 if (isShuffleEquivalent(V1, V2, Mask,
9766 {// First 128-bit lane.
9767 2, 18, 3, 19, 6, 22, 7, 23,
9768 // Second 128-bit lane.
9769 10, 26, 11, 27, 14, 30, 15, 31}))
9770 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9772 // FIXME: Implement direct support for this type!
9773 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9776 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9777 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9778 const X86Subtarget *Subtarget,
9779 SelectionDAG &DAG) {
9781 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9782 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9783 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9784 ArrayRef<int> Mask = SVOp->getMask();
9785 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9787 // X86 has dedicated unpack instructions that can handle specific blend
9788 // operations: UNPCKH and UNPCKL.
9789 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9790 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9791 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9792 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9794 // FIXME: Implement direct support for this type!
9795 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9798 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9799 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9800 const X86Subtarget *Subtarget,
9801 SelectionDAG &DAG) {
9803 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9804 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9805 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9806 ArrayRef<int> Mask = SVOp->getMask();
9807 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9809 // Use dedicated unpack instructions for masks that match their pattern.
9810 if (isShuffleEquivalent(V1, V2, Mask,
9811 {// First 128-bit lane.
9812 0, 16, 1, 17, 4, 20, 5, 21,
9813 // Second 128-bit lane.
9814 8, 24, 9, 25, 12, 28, 13, 29}))
9815 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9816 if (isShuffleEquivalent(V1, V2, Mask,
9817 {// First 128-bit lane.
9818 2, 18, 3, 19, 6, 22, 7, 23,
9819 // Second 128-bit lane.
9820 10, 26, 11, 27, 14, 30, 15, 31}))
9821 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9823 // FIXME: Implement direct support for this type!
9824 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9827 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9828 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9829 const X86Subtarget *Subtarget,
9830 SelectionDAG &DAG) {
9832 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9833 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9834 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9835 ArrayRef<int> Mask = SVOp->getMask();
9836 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9837 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9839 // FIXME: Implement direct support for this type!
9840 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9843 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9844 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9845 const X86Subtarget *Subtarget,
9846 SelectionDAG &DAG) {
9848 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9849 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9850 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9851 ArrayRef<int> Mask = SVOp->getMask();
9852 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9853 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9855 // FIXME: Implement direct support for this type!
9856 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9859 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9861 /// This routine either breaks down the specific type of a 512-bit x86 vector
9862 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9863 /// together based on the available instructions.
9864 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9865 MVT VT, const X86Subtarget *Subtarget,
9866 SelectionDAG &DAG) {
9868 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9869 ArrayRef<int> Mask = SVOp->getMask();
9870 assert(Subtarget->hasAVX512() &&
9871 "Cannot lower 512-bit vectors w/ basic ISA!");
9873 // Check for being able to broadcast a single element.
9874 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
9875 Mask, Subtarget, DAG))
9878 // Dispatch to each element type for lowering. If we don't have supprot for
9879 // specific element type shuffles at 512 bits, immediately split them and
9880 // lower them. Each lowering routine of a given type is allowed to assume that
9881 // the requisite ISA extensions for that element type are available.
9882 switch (VT.SimpleTy) {
9884 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9886 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9888 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9890 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9892 if (Subtarget->hasBWI())
9893 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9896 if (Subtarget->hasBWI())
9897 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9901 llvm_unreachable("Not a valid 512-bit x86 vector type!");
9904 // Otherwise fall back on splitting.
9905 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9908 /// \brief Top-level lowering for x86 vector shuffles.
9910 /// This handles decomposition, canonicalization, and lowering of all x86
9911 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9912 /// above in helper routines. The canonicalization attempts to widen shuffles
9913 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9914 /// s.t. only one of the two inputs needs to be tested, etc.
9915 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9916 SelectionDAG &DAG) {
9917 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9918 ArrayRef<int> Mask = SVOp->getMask();
9919 SDValue V1 = Op.getOperand(0);
9920 SDValue V2 = Op.getOperand(1);
9921 MVT VT = Op.getSimpleValueType();
9922 int NumElements = VT.getVectorNumElements();
9925 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9927 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9928 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9929 if (V1IsUndef && V2IsUndef)
9930 return DAG.getUNDEF(VT);
9932 // When we create a shuffle node we put the UNDEF node to second operand,
9933 // but in some cases the first operand may be transformed to UNDEF.
9934 // In this case we should just commute the node.
9936 return DAG.getCommutedVectorShuffle(*SVOp);
9938 // Check for non-undef masks pointing at an undef vector and make the masks
9939 // undef as well. This makes it easier to match the shuffle based solely on
9943 if (M >= NumElements) {
9944 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
9945 for (int &M : NewMask)
9946 if (M >= NumElements)
9948 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
9951 // We actually see shuffles that are entirely re-arrangements of a set of
9952 // zero inputs. This mostly happens while decomposing complex shuffles into
9953 // simple ones. Directly lower these as a buildvector of zeros.
9954 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9956 return getZeroVector(VT, Subtarget, DAG, dl);
9958 // Try to collapse shuffles into using a vector type with fewer elements but
9959 // wider element types. We cap this to not form integers or floating point
9960 // elements wider than 64 bits, but it might be interesting to form i128
9961 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
9962 SmallVector<int, 16> WidenedMask;
9963 if (VT.getScalarSizeInBits() < 64 &&
9964 canWidenShuffleElements(Mask, WidenedMask)) {
9965 MVT NewEltVT = VT.isFloatingPoint()
9966 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
9967 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
9968 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9969 // Make sure that the new vector type is legal. For example, v2f64 isn't
9971 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9972 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9973 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9974 return DAG.getNode(ISD::BITCAST, dl, VT,
9975 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
9979 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
9980 for (int M : SVOp->getMask())
9983 else if (M < NumElements)
9988 // Commute the shuffle as needed such that more elements come from V1 than
9989 // V2. This allows us to match the shuffle pattern strictly on how many
9990 // elements come from V1 without handling the symmetric cases.
9991 if (NumV2Elements > NumV1Elements)
9992 return DAG.getCommutedVectorShuffle(*SVOp);
9994 // When the number of V1 and V2 elements are the same, try to minimize the
9995 // number of uses of V2 in the low half of the vector. When that is tied,
9996 // ensure that the sum of indices for V1 is equal to or lower than the sum
9997 // indices for V2. When those are equal, try to ensure that the number of odd
9998 // indices for V1 is lower than the number of odd indices for V2.
9999 if (NumV1Elements == NumV2Elements) {
10000 int LowV1Elements = 0, LowV2Elements = 0;
10001 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10002 if (M >= NumElements)
10006 if (LowV2Elements > LowV1Elements) {
10007 return DAG.getCommutedVectorShuffle(*SVOp);
10008 } else if (LowV2Elements == LowV1Elements) {
10009 int SumV1Indices = 0, SumV2Indices = 0;
10010 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10011 if (SVOp->getMask()[i] >= NumElements)
10013 else if (SVOp->getMask()[i] >= 0)
10015 if (SumV2Indices < SumV1Indices) {
10016 return DAG.getCommutedVectorShuffle(*SVOp);
10017 } else if (SumV2Indices == SumV1Indices) {
10018 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10019 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10020 if (SVOp->getMask()[i] >= NumElements)
10021 NumV2OddIndices += i % 2;
10022 else if (SVOp->getMask()[i] >= 0)
10023 NumV1OddIndices += i % 2;
10024 if (NumV2OddIndices < NumV1OddIndices)
10025 return DAG.getCommutedVectorShuffle(*SVOp);
10030 // For each vector width, delegate to a specialized lowering routine.
10031 if (VT.getSizeInBits() == 128)
10032 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10034 if (VT.getSizeInBits() == 256)
10035 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10037 // Force AVX-512 vectors to be scalarized for now.
10038 // FIXME: Implement AVX-512 support!
10039 if (VT.getSizeInBits() == 512)
10040 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10042 llvm_unreachable("Unimplemented!");
10045 // This function assumes its argument is a BUILD_VECTOR of constants or
10046 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10048 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10049 unsigned &MaskValue) {
10051 unsigned NumElems = BuildVector->getNumOperands();
10052 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10053 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10054 unsigned NumElemsInLane = NumElems / NumLanes;
10056 // Blend for v16i16 should be symetric for the both lanes.
10057 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10058 SDValue EltCond = BuildVector->getOperand(i);
10059 SDValue SndLaneEltCond =
10060 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10062 int Lane1Cond = -1, Lane2Cond = -1;
10063 if (isa<ConstantSDNode>(EltCond))
10064 Lane1Cond = !isZero(EltCond);
10065 if (isa<ConstantSDNode>(SndLaneEltCond))
10066 Lane2Cond = !isZero(SndLaneEltCond);
10068 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10069 // Lane1Cond != 0, means we want the first argument.
10070 // Lane1Cond == 0, means we want the second argument.
10071 // The encoding of this argument is 0 for the first argument, 1
10072 // for the second. Therefore, invert the condition.
10073 MaskValue |= !Lane1Cond << i;
10074 else if (Lane1Cond < 0)
10075 MaskValue |= !Lane2Cond << i;
10082 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10083 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10084 const X86Subtarget *Subtarget,
10085 SelectionDAG &DAG) {
10086 SDValue Cond = Op.getOperand(0);
10087 SDValue LHS = Op.getOperand(1);
10088 SDValue RHS = Op.getOperand(2);
10090 MVT VT = Op.getSimpleValueType();
10092 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10094 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10096 // Only non-legal VSELECTs reach this lowering, convert those into generic
10097 // shuffles and re-use the shuffle lowering path for blends.
10098 SmallVector<int, 32> Mask;
10099 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10100 SDValue CondElt = CondBV->getOperand(i);
10102 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10104 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10107 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10108 // A vselect where all conditions and data are constants can be optimized into
10109 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10110 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10111 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10112 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10115 // Try to lower this to a blend-style vector shuffle. This can handle all
10116 // constant condition cases.
10117 SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG);
10118 if (BlendOp.getNode())
10121 // Variable blends are only legal from SSE4.1 onward.
10122 if (!Subtarget->hasSSE41())
10125 // Some types for vselect were previously set to Expand, not Legal or
10126 // Custom. Return an empty SDValue so we fall-through to Expand, after
10127 // the Custom lowering phase.
10128 MVT VT = Op.getSimpleValueType();
10129 switch (VT.SimpleTy) {
10134 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10139 // We couldn't create a "Blend with immediate" node.
10140 // This node should still be legal, but we'll have to emit a blendv*
10145 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10146 MVT VT = Op.getSimpleValueType();
10149 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10152 if (VT.getSizeInBits() == 8) {
10153 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10154 Op.getOperand(0), Op.getOperand(1));
10155 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10156 DAG.getValueType(VT));
10157 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10160 if (VT.getSizeInBits() == 16) {
10161 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10162 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10164 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10165 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10166 DAG.getNode(ISD::BITCAST, dl,
10169 Op.getOperand(1)));
10170 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10171 Op.getOperand(0), Op.getOperand(1));
10172 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10173 DAG.getValueType(VT));
10174 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10177 if (VT == MVT::f32) {
10178 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10179 // the result back to FR32 register. It's only worth matching if the
10180 // result has a single use which is a store or a bitcast to i32. And in
10181 // the case of a store, it's not worth it if the index is a constant 0,
10182 // because a MOVSSmr can be used instead, which is smaller and faster.
10183 if (!Op.hasOneUse())
10185 SDNode *User = *Op.getNode()->use_begin();
10186 if ((User->getOpcode() != ISD::STORE ||
10187 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10188 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10189 (User->getOpcode() != ISD::BITCAST ||
10190 User->getValueType(0) != MVT::i32))
10192 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10193 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10196 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10199 if (VT == MVT::i32 || VT == MVT::i64) {
10200 // ExtractPS/pextrq works with constant index.
10201 if (isa<ConstantSDNode>(Op.getOperand(1)))
10207 /// Extract one bit from mask vector, like v16i1 or v8i1.
10208 /// AVX-512 feature.
10210 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10211 SDValue Vec = Op.getOperand(0);
10213 MVT VecVT = Vec.getSimpleValueType();
10214 SDValue Idx = Op.getOperand(1);
10215 MVT EltVT = Op.getSimpleValueType();
10217 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10218 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10219 "Unexpected vector type in ExtractBitFromMaskVector");
10221 // variable index can't be handled in mask registers,
10222 // extend vector to VR512
10223 if (!isa<ConstantSDNode>(Idx)) {
10224 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10225 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10226 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10227 ExtVT.getVectorElementType(), Ext, Idx);
10228 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10231 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10232 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10233 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10234 rc = getRegClassFor(MVT::v16i1);
10235 unsigned MaxSift = rc->getSize()*8 - 1;
10236 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10237 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10238 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10239 DAG.getConstant(MaxSift, MVT::i8));
10240 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10241 DAG.getIntPtrConstant(0));
10245 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10246 SelectionDAG &DAG) const {
10248 SDValue Vec = Op.getOperand(0);
10249 MVT VecVT = Vec.getSimpleValueType();
10250 SDValue Idx = Op.getOperand(1);
10252 if (Op.getSimpleValueType() == MVT::i1)
10253 return ExtractBitFromMaskVector(Op, DAG);
10255 if (!isa<ConstantSDNode>(Idx)) {
10256 if (VecVT.is512BitVector() ||
10257 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10258 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10261 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10262 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10263 MaskEltVT.getSizeInBits());
10265 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10266 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10267 getZeroVector(MaskVT, Subtarget, DAG, dl),
10268 Idx, DAG.getConstant(0, getPointerTy()));
10269 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10270 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10271 Perm, DAG.getConstant(0, getPointerTy()));
10276 // If this is a 256-bit vector result, first extract the 128-bit vector and
10277 // then extract the element from the 128-bit vector.
10278 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10280 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10281 // Get the 128-bit vector.
10282 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10283 MVT EltVT = VecVT.getVectorElementType();
10285 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10287 //if (IdxVal >= NumElems/2)
10288 // IdxVal -= NumElems/2;
10289 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10290 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10291 DAG.getConstant(IdxVal, MVT::i32));
10294 assert(VecVT.is128BitVector() && "Unexpected vector length");
10296 if (Subtarget->hasSSE41()) {
10297 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10302 MVT VT = Op.getSimpleValueType();
10303 // TODO: handle v16i8.
10304 if (VT.getSizeInBits() == 16) {
10305 SDValue Vec = Op.getOperand(0);
10306 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10308 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10309 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10310 DAG.getNode(ISD::BITCAST, dl,
10312 Op.getOperand(1)));
10313 // Transform it so it match pextrw which produces a 32-bit result.
10314 MVT EltVT = MVT::i32;
10315 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10316 Op.getOperand(0), Op.getOperand(1));
10317 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10318 DAG.getValueType(VT));
10319 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10322 if (VT.getSizeInBits() == 32) {
10323 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10327 // SHUFPS the element to the lowest double word, then movss.
10328 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10329 MVT VVT = Op.getOperand(0).getSimpleValueType();
10330 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10331 DAG.getUNDEF(VVT), Mask);
10332 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10333 DAG.getIntPtrConstant(0));
10336 if (VT.getSizeInBits() == 64) {
10337 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10338 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10339 // to match extract_elt for f64.
10340 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10344 // UNPCKHPD the element to the lowest double word, then movsd.
10345 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10346 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10347 int Mask[2] = { 1, -1 };
10348 MVT VVT = Op.getOperand(0).getSimpleValueType();
10349 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10350 DAG.getUNDEF(VVT), Mask);
10351 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10352 DAG.getIntPtrConstant(0));
10358 /// Insert one bit to mask vector, like v16i1 or v8i1.
10359 /// AVX-512 feature.
10361 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10363 SDValue Vec = Op.getOperand(0);
10364 SDValue Elt = Op.getOperand(1);
10365 SDValue Idx = Op.getOperand(2);
10366 MVT VecVT = Vec.getSimpleValueType();
10368 if (!isa<ConstantSDNode>(Idx)) {
10369 // Non constant index. Extend source and destination,
10370 // insert element and then truncate the result.
10371 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10372 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10373 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10374 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10375 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10376 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10379 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10380 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10381 if (Vec.getOpcode() == ISD::UNDEF)
10382 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10383 DAG.getConstant(IdxVal, MVT::i8));
10384 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10385 unsigned MaxSift = rc->getSize()*8 - 1;
10386 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10387 DAG.getConstant(MaxSift, MVT::i8));
10388 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10389 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10390 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10393 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10394 SelectionDAG &DAG) const {
10395 MVT VT = Op.getSimpleValueType();
10396 MVT EltVT = VT.getVectorElementType();
10398 if (EltVT == MVT::i1)
10399 return InsertBitToMaskVector(Op, DAG);
10402 SDValue N0 = Op.getOperand(0);
10403 SDValue N1 = Op.getOperand(1);
10404 SDValue N2 = Op.getOperand(2);
10405 if (!isa<ConstantSDNode>(N2))
10407 auto *N2C = cast<ConstantSDNode>(N2);
10408 unsigned IdxVal = N2C->getZExtValue();
10410 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10411 // into that, and then insert the subvector back into the result.
10412 if (VT.is256BitVector() || VT.is512BitVector()) {
10413 // Get the desired 128-bit vector half.
10414 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10416 // Insert the element into the desired half.
10417 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10418 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10420 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10421 DAG.getConstant(IdxIn128, MVT::i32));
10423 // Insert the changed part back to the 256-bit vector
10424 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10426 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10428 if (Subtarget->hasSSE41()) {
10429 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10431 if (VT == MVT::v8i16) {
10432 Opc = X86ISD::PINSRW;
10434 assert(VT == MVT::v16i8);
10435 Opc = X86ISD::PINSRB;
10438 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10440 if (N1.getValueType() != MVT::i32)
10441 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10442 if (N2.getValueType() != MVT::i32)
10443 N2 = DAG.getIntPtrConstant(IdxVal);
10444 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10447 if (EltVT == MVT::f32) {
10448 // Bits [7:6] of the constant are the source select. This will always be
10449 // zero here. The DAG Combiner may combine an extract_elt index into
10451 // bits. For example (insert (extract, 3), 2) could be matched by
10453 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10454 // Bits [5:4] of the constant are the destination select. This is the
10455 // value of the incoming immediate.
10456 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10457 // combine either bitwise AND or insert of float 0.0 to set these bits.
10458 N2 = DAG.getIntPtrConstant(IdxVal << 4);
10459 // Create this as a scalar to vector..
10460 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10461 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10464 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10465 // PINSR* works with constant index.
10470 if (EltVT == MVT::i8)
10473 if (EltVT.getSizeInBits() == 16) {
10474 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10475 // as its second argument.
10476 if (N1.getValueType() != MVT::i32)
10477 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10478 if (N2.getValueType() != MVT::i32)
10479 N2 = DAG.getIntPtrConstant(IdxVal);
10480 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10485 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10487 MVT OpVT = Op.getSimpleValueType();
10489 // If this is a 256-bit vector result, first insert into a 128-bit
10490 // vector and then insert into the 256-bit vector.
10491 if (!OpVT.is128BitVector()) {
10492 // Insert into a 128-bit vector.
10493 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10494 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10495 OpVT.getVectorNumElements() / SizeFactor);
10497 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10499 // Insert the 128-bit vector.
10500 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10503 if (OpVT == MVT::v1i64 &&
10504 Op.getOperand(0).getValueType() == MVT::i64)
10505 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10507 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10508 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10509 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10510 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10513 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10514 // a simple subregister reference or explicit instructions to grab
10515 // upper bits of a vector.
10516 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10517 SelectionDAG &DAG) {
10519 SDValue In = Op.getOperand(0);
10520 SDValue Idx = Op.getOperand(1);
10521 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10522 MVT ResVT = Op.getSimpleValueType();
10523 MVT InVT = In.getSimpleValueType();
10525 if (Subtarget->hasFp256()) {
10526 if (ResVT.is128BitVector() &&
10527 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10528 isa<ConstantSDNode>(Idx)) {
10529 return Extract128BitVector(In, IdxVal, DAG, dl);
10531 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10532 isa<ConstantSDNode>(Idx)) {
10533 return Extract256BitVector(In, IdxVal, DAG, dl);
10539 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10540 // simple superregister reference or explicit instructions to insert
10541 // the upper bits of a vector.
10542 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10543 SelectionDAG &DAG) {
10544 if (!Subtarget->hasAVX())
10548 SDValue Vec = Op.getOperand(0);
10549 SDValue SubVec = Op.getOperand(1);
10550 SDValue Idx = Op.getOperand(2);
10552 if (!isa<ConstantSDNode>(Idx))
10555 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10556 MVT OpVT = Op.getSimpleValueType();
10557 MVT SubVecVT = SubVec.getSimpleValueType();
10559 // Fold two 16-byte subvector loads into one 32-byte load:
10560 // (insert_subvector (insert_subvector undef, (load addr), 0),
10561 // (load addr + 16), Elts/2)
10563 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10564 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10565 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10566 !Subtarget->isUnalignedMem32Slow()) {
10567 SDValue SubVec2 = Vec.getOperand(1);
10568 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10569 if (Idx2->getZExtValue() == 0) {
10570 SDValue Ops[] = { SubVec2, SubVec };
10571 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10578 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10579 SubVecVT.is128BitVector())
10580 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10582 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10583 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10588 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10589 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10590 // one of the above mentioned nodes. It has to be wrapped because otherwise
10591 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10592 // be used to form addressing mode. These wrapped nodes will be selected
10595 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10596 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10598 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10599 // global base reg.
10600 unsigned char OpFlag = 0;
10601 unsigned WrapperKind = X86ISD::Wrapper;
10602 CodeModel::Model M = DAG.getTarget().getCodeModel();
10604 if (Subtarget->isPICStyleRIPRel() &&
10605 (M == CodeModel::Small || M == CodeModel::Kernel))
10606 WrapperKind = X86ISD::WrapperRIP;
10607 else if (Subtarget->isPICStyleGOT())
10608 OpFlag = X86II::MO_GOTOFF;
10609 else if (Subtarget->isPICStyleStubPIC())
10610 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10612 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10613 CP->getAlignment(),
10614 CP->getOffset(), OpFlag);
10616 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10617 // With PIC, the address is actually $g + Offset.
10619 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10620 DAG.getNode(X86ISD::GlobalBaseReg,
10621 SDLoc(), getPointerTy()),
10628 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10629 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10631 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10632 // global base reg.
10633 unsigned char OpFlag = 0;
10634 unsigned WrapperKind = X86ISD::Wrapper;
10635 CodeModel::Model M = DAG.getTarget().getCodeModel();
10637 if (Subtarget->isPICStyleRIPRel() &&
10638 (M == CodeModel::Small || M == CodeModel::Kernel))
10639 WrapperKind = X86ISD::WrapperRIP;
10640 else if (Subtarget->isPICStyleGOT())
10641 OpFlag = X86II::MO_GOTOFF;
10642 else if (Subtarget->isPICStyleStubPIC())
10643 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10645 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10648 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10650 // With PIC, the address is actually $g + Offset.
10652 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10653 DAG.getNode(X86ISD::GlobalBaseReg,
10654 SDLoc(), getPointerTy()),
10661 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10662 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10664 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10665 // global base reg.
10666 unsigned char OpFlag = 0;
10667 unsigned WrapperKind = X86ISD::Wrapper;
10668 CodeModel::Model M = DAG.getTarget().getCodeModel();
10670 if (Subtarget->isPICStyleRIPRel() &&
10671 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10672 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10673 OpFlag = X86II::MO_GOTPCREL;
10674 WrapperKind = X86ISD::WrapperRIP;
10675 } else if (Subtarget->isPICStyleGOT()) {
10676 OpFlag = X86II::MO_GOT;
10677 } else if (Subtarget->isPICStyleStubPIC()) {
10678 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10679 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10680 OpFlag = X86II::MO_DARWIN_NONLAZY;
10683 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10686 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10688 // With PIC, the address is actually $g + Offset.
10689 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10690 !Subtarget->is64Bit()) {
10691 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10692 DAG.getNode(X86ISD::GlobalBaseReg,
10693 SDLoc(), getPointerTy()),
10697 // For symbols that require a load from a stub to get the address, emit the
10699 if (isGlobalStubReference(OpFlag))
10700 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10701 MachinePointerInfo::getGOT(), false, false, false, 0);
10707 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10708 // Create the TargetBlockAddressAddress node.
10709 unsigned char OpFlags =
10710 Subtarget->ClassifyBlockAddressReference();
10711 CodeModel::Model M = DAG.getTarget().getCodeModel();
10712 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10713 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10715 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10718 if (Subtarget->isPICStyleRIPRel() &&
10719 (M == CodeModel::Small || M == CodeModel::Kernel))
10720 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10722 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10724 // With PIC, the address is actually $g + Offset.
10725 if (isGlobalRelativeToPICBase(OpFlags)) {
10726 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10727 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10735 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10736 int64_t Offset, SelectionDAG &DAG) const {
10737 // Create the TargetGlobalAddress node, folding in the constant
10738 // offset if it is legal.
10739 unsigned char OpFlags =
10740 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10741 CodeModel::Model M = DAG.getTarget().getCodeModel();
10743 if (OpFlags == X86II::MO_NO_FLAG &&
10744 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10745 // A direct static reference to a global.
10746 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10749 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10752 if (Subtarget->isPICStyleRIPRel() &&
10753 (M == CodeModel::Small || M == CodeModel::Kernel))
10754 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10756 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10758 // With PIC, the address is actually $g + Offset.
10759 if (isGlobalRelativeToPICBase(OpFlags)) {
10760 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10761 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10765 // For globals that require a load from a stub to get the address, emit the
10767 if (isGlobalStubReference(OpFlags))
10768 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10769 MachinePointerInfo::getGOT(), false, false, false, 0);
10771 // If there was a non-zero offset that we didn't fold, create an explicit
10772 // addition for it.
10774 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10775 DAG.getConstant(Offset, getPointerTy()));
10781 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10782 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10783 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10784 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10788 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10789 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10790 unsigned char OperandFlags, bool LocalDynamic = false) {
10791 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10792 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10794 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10795 GA->getValueType(0),
10799 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10803 SDValue Ops[] = { Chain, TGA, *InFlag };
10804 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10806 SDValue Ops[] = { Chain, TGA };
10807 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10810 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10811 MFI->setAdjustsStack(true);
10812 MFI->setHasCalls(true);
10814 SDValue Flag = Chain.getValue(1);
10815 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10818 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10820 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10823 SDLoc dl(GA); // ? function entry point might be better
10824 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10825 DAG.getNode(X86ISD::GlobalBaseReg,
10826 SDLoc(), PtrVT), InFlag);
10827 InFlag = Chain.getValue(1);
10829 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10832 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10834 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10836 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10837 X86::RAX, X86II::MO_TLSGD);
10840 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10846 // Get the start address of the TLS block for this module.
10847 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10848 .getInfo<X86MachineFunctionInfo>();
10849 MFI->incNumLocalDynamicTLSAccesses();
10853 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10854 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10857 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10858 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10859 InFlag = Chain.getValue(1);
10860 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10861 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10864 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10868 unsigned char OperandFlags = X86II::MO_DTPOFF;
10869 unsigned WrapperKind = X86ISD::Wrapper;
10870 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10871 GA->getValueType(0),
10872 GA->getOffset(), OperandFlags);
10873 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10875 // Add x@dtpoff with the base.
10876 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10879 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10880 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10881 const EVT PtrVT, TLSModel::Model model,
10882 bool is64Bit, bool isPIC) {
10885 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10886 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10887 is64Bit ? 257 : 256));
10889 SDValue ThreadPointer =
10890 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10891 MachinePointerInfo(Ptr), false, false, false, 0);
10893 unsigned char OperandFlags = 0;
10894 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10896 unsigned WrapperKind = X86ISD::Wrapper;
10897 if (model == TLSModel::LocalExec) {
10898 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10899 } else if (model == TLSModel::InitialExec) {
10901 OperandFlags = X86II::MO_GOTTPOFF;
10902 WrapperKind = X86ISD::WrapperRIP;
10904 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10907 llvm_unreachable("Unexpected model");
10910 // emit "addl x@ntpoff,%eax" (local exec)
10911 // or "addl x@indntpoff,%eax" (initial exec)
10912 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10914 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10915 GA->getOffset(), OperandFlags);
10916 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10918 if (model == TLSModel::InitialExec) {
10919 if (isPIC && !is64Bit) {
10920 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10921 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10925 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10926 MachinePointerInfo::getGOT(), false, false, false, 0);
10929 // The address of the thread local variable is the add of the thread
10930 // pointer with the offset of the variable.
10931 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10935 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10937 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10938 const GlobalValue *GV = GA->getGlobal();
10940 if (Subtarget->isTargetELF()) {
10941 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10944 case TLSModel::GeneralDynamic:
10945 if (Subtarget->is64Bit())
10946 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10947 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10948 case TLSModel::LocalDynamic:
10949 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10950 Subtarget->is64Bit());
10951 case TLSModel::InitialExec:
10952 case TLSModel::LocalExec:
10953 return LowerToTLSExecModel(
10954 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10955 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10957 llvm_unreachable("Unknown TLS model.");
10960 if (Subtarget->isTargetDarwin()) {
10961 // Darwin only has one model of TLS. Lower to that.
10962 unsigned char OpFlag = 0;
10963 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10964 X86ISD::WrapperRIP : X86ISD::Wrapper;
10966 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10967 // global base reg.
10968 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10969 !Subtarget->is64Bit();
10971 OpFlag = X86II::MO_TLVP_PIC_BASE;
10973 OpFlag = X86II::MO_TLVP;
10975 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10976 GA->getValueType(0),
10977 GA->getOffset(), OpFlag);
10978 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10980 // With PIC32, the address is actually $g + Offset.
10982 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10983 DAG.getNode(X86ISD::GlobalBaseReg,
10984 SDLoc(), getPointerTy()),
10987 // Lowering the machine isd will make sure everything is in the right
10989 SDValue Chain = DAG.getEntryNode();
10990 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10991 SDValue Args[] = { Chain, Offset };
10992 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10994 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10995 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10996 MFI->setAdjustsStack(true);
10998 // And our return value (tls address) is in the standard call return value
11000 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11001 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11002 Chain.getValue(1));
11005 if (Subtarget->isTargetKnownWindowsMSVC() ||
11006 Subtarget->isTargetWindowsGNU()) {
11007 // Just use the implicit TLS architecture
11008 // Need to generate someting similar to:
11009 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11011 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11012 // mov rcx, qword [rdx+rcx*8]
11013 // mov eax, .tls$:tlsvar
11014 // [rax+rcx] contains the address
11015 // Windows 64bit: gs:0x58
11016 // Windows 32bit: fs:__tls_array
11019 SDValue Chain = DAG.getEntryNode();
11021 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11022 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11023 // use its literal value of 0x2C.
11024 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11025 ? Type::getInt8PtrTy(*DAG.getContext(),
11027 : Type::getInt32PtrTy(*DAG.getContext(),
11031 Subtarget->is64Bit()
11032 ? DAG.getIntPtrConstant(0x58)
11033 : (Subtarget->isTargetWindowsGNU()
11034 ? DAG.getIntPtrConstant(0x2C)
11035 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11037 SDValue ThreadPointer =
11038 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11039 MachinePointerInfo(Ptr), false, false, false, 0);
11041 // Load the _tls_index variable
11042 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11043 if (Subtarget->is64Bit())
11044 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11045 IDX, MachinePointerInfo(), MVT::i32,
11046 false, false, false, 0);
11048 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11049 false, false, false, 0);
11051 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11053 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11055 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11056 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11057 false, false, false, 0);
11059 // Get the offset of start of .tls section
11060 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11061 GA->getValueType(0),
11062 GA->getOffset(), X86II::MO_SECREL);
11063 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
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, getPointerTy(), res, Offset);
11070 llvm_unreachable("TLS not implemented for this target.");
11073 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11074 /// and take a 2 x i32 value to shift plus a shift amount.
11075 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11076 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11077 MVT VT = Op.getSimpleValueType();
11078 unsigned VTBits = VT.getSizeInBits();
11080 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11081 SDValue ShOpLo = Op.getOperand(0);
11082 SDValue ShOpHi = Op.getOperand(1);
11083 SDValue ShAmt = Op.getOperand(2);
11084 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11085 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11087 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11088 DAG.getConstant(VTBits - 1, MVT::i8));
11089 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11090 DAG.getConstant(VTBits - 1, MVT::i8))
11091 : DAG.getConstant(0, VT);
11093 SDValue Tmp2, Tmp3;
11094 if (Op.getOpcode() == ISD::SHL_PARTS) {
11095 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11096 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11098 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11099 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11102 // If the shift amount is larger or equal than the width of a part we can't
11103 // rely on the results of shld/shrd. Insert a test and select the appropriate
11104 // values for large shift amounts.
11105 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11106 DAG.getConstant(VTBits, MVT::i8));
11107 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11108 AndNode, DAG.getConstant(0, MVT::i8));
11111 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11112 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11113 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11115 if (Op.getOpcode() == ISD::SHL_PARTS) {
11116 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11117 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11119 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11120 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11123 SDValue Ops[2] = { Lo, Hi };
11124 return DAG.getMergeValues(Ops, dl);
11127 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11128 SelectionDAG &DAG) const {
11129 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11132 if (SrcVT.isVector()) {
11133 if (SrcVT.getVectorElementType() == MVT::i1) {
11134 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11135 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11136 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11137 Op.getOperand(0)));
11142 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11143 "Unknown SINT_TO_FP to lower!");
11145 // These are really Legal; return the operand so the caller accepts it as
11147 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11149 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11150 Subtarget->is64Bit()) {
11154 unsigned Size = SrcVT.getSizeInBits()/8;
11155 MachineFunction &MF = DAG.getMachineFunction();
11156 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11157 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11158 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11160 MachinePointerInfo::getFixedStack(SSFI),
11162 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11165 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11167 SelectionDAG &DAG) const {
11171 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11173 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11175 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11177 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11179 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11180 MachineMemOperand *MMO;
11182 int SSFI = FI->getIndex();
11184 DAG.getMachineFunction()
11185 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11186 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11188 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11189 StackSlot = StackSlot.getOperand(1);
11191 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11192 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11194 Tys, Ops, SrcVT, MMO);
11197 Chain = Result.getValue(1);
11198 SDValue InFlag = Result.getValue(2);
11200 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11201 // shouldn't be necessary except that RFP cannot be live across
11202 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11203 MachineFunction &MF = DAG.getMachineFunction();
11204 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11205 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11206 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11207 Tys = DAG.getVTList(MVT::Other);
11209 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11211 MachineMemOperand *MMO =
11212 DAG.getMachineFunction()
11213 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11214 MachineMemOperand::MOStore, SSFISize, SSFISize);
11216 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11217 Ops, Op.getValueType(), MMO);
11218 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11219 MachinePointerInfo::getFixedStack(SSFI),
11220 false, false, false, 0);
11226 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11227 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11228 SelectionDAG &DAG) const {
11229 // This algorithm is not obvious. Here it is what we're trying to output:
11232 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11233 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11235 haddpd %xmm0, %xmm0
11237 pshufd $0x4e, %xmm0, %xmm1
11243 LLVMContext *Context = DAG.getContext();
11245 // Build some magic constants.
11246 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11247 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11248 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11250 SmallVector<Constant*,2> CV1;
11252 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11253 APInt(64, 0x4330000000000000ULL))));
11255 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11256 APInt(64, 0x4530000000000000ULL))));
11257 Constant *C1 = ConstantVector::get(CV1);
11258 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11260 // Load the 64-bit value into an XMM register.
11261 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11263 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11264 MachinePointerInfo::getConstantPool(),
11265 false, false, false, 16);
11266 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11267 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11270 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11271 MachinePointerInfo::getConstantPool(),
11272 false, false, false, 16);
11273 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11274 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11277 if (Subtarget->hasSSE3()) {
11278 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11279 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11281 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11282 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11284 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11285 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11289 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11290 DAG.getIntPtrConstant(0));
11293 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11294 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11295 SelectionDAG &DAG) const {
11297 // FP constant to bias correct the final result.
11298 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11301 // Load the 32-bit value into an XMM register.
11302 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11305 // Zero out the upper parts of the register.
11306 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11308 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11309 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11310 DAG.getIntPtrConstant(0));
11312 // Or the load with the bias.
11313 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11314 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11315 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11316 MVT::v2f64, Load)),
11317 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11318 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11319 MVT::v2f64, Bias)));
11320 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11321 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11322 DAG.getIntPtrConstant(0));
11324 // Subtract the bias.
11325 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11327 // Handle final rounding.
11328 EVT DestVT = Op.getValueType();
11330 if (DestVT.bitsLT(MVT::f64))
11331 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11332 DAG.getIntPtrConstant(0));
11333 if (DestVT.bitsGT(MVT::f64))
11334 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11336 // Handle final rounding.
11340 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11341 const X86Subtarget &Subtarget) {
11342 // The algorithm is the following:
11343 // #ifdef __SSE4_1__
11344 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11345 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11346 // (uint4) 0x53000000, 0xaa);
11348 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11349 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11351 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11352 // return (float4) lo + fhi;
11355 SDValue V = Op->getOperand(0);
11356 EVT VecIntVT = V.getValueType();
11357 bool Is128 = VecIntVT == MVT::v4i32;
11358 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11359 // If we convert to something else than the supported type, e.g., to v4f64,
11361 if (VecFloatVT != Op->getValueType(0))
11364 unsigned NumElts = VecIntVT.getVectorNumElements();
11365 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11366 "Unsupported custom type");
11367 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11369 // In the #idef/#else code, we have in common:
11370 // - The vector of constants:
11376 // Create the splat vector for 0x4b000000.
11377 SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11378 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11379 CstLow, CstLow, CstLow, CstLow};
11380 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11381 makeArrayRef(&CstLowArray[0], NumElts));
11382 // Create the splat vector for 0x53000000.
11383 SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11384 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11385 CstHigh, CstHigh, CstHigh, CstHigh};
11386 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11387 makeArrayRef(&CstHighArray[0], NumElts));
11389 // Create the right shift.
11390 SDValue CstShift = DAG.getConstant(16, MVT::i32);
11391 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11392 CstShift, CstShift, CstShift, CstShift};
11393 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11394 makeArrayRef(&CstShiftArray[0], NumElts));
11395 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11398 if (Subtarget.hasSSE41()) {
11399 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11400 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11401 SDValue VecCstLowBitcast =
11402 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11403 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11404 // Low will be bitcasted right away, so do not bother bitcasting back to its
11406 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11407 VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11408 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11409 // (uint4) 0x53000000, 0xaa);
11410 SDValue VecCstHighBitcast =
11411 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11412 SDValue VecShiftBitcast =
11413 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11414 // High will be bitcasted right away, so do not bother bitcasting back to
11415 // its original type.
11416 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11417 VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11419 SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11420 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11421 CstMask, CstMask, CstMask);
11422 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11423 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11424 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11426 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11427 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11430 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11431 SDValue CstFAdd = DAG.getConstantFP(
11432 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11433 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11434 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11435 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11436 makeArrayRef(&CstFAddArray[0], NumElts));
11438 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11439 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11441 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11442 // return (float4) lo + fhi;
11443 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11444 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11447 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11448 SelectionDAG &DAG) const {
11449 SDValue N0 = Op.getOperand(0);
11450 MVT SVT = N0.getSimpleValueType();
11453 switch (SVT.SimpleTy) {
11455 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11460 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11461 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11462 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11466 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11468 llvm_unreachable(nullptr);
11471 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11472 SelectionDAG &DAG) const {
11473 SDValue N0 = Op.getOperand(0);
11476 if (Op.getValueType().isVector())
11477 return lowerUINT_TO_FP_vec(Op, DAG);
11479 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11480 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11481 // the optimization here.
11482 if (DAG.SignBitIsZero(N0))
11483 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11485 MVT SrcVT = N0.getSimpleValueType();
11486 MVT DstVT = Op.getSimpleValueType();
11487 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11488 return LowerUINT_TO_FP_i64(Op, DAG);
11489 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11490 return LowerUINT_TO_FP_i32(Op, DAG);
11491 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11494 // Make a 64-bit buffer, and use it to build an FILD.
11495 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11496 if (SrcVT == MVT::i32) {
11497 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11498 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11499 getPointerTy(), StackSlot, WordOff);
11500 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11501 StackSlot, MachinePointerInfo(),
11503 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11504 OffsetSlot, MachinePointerInfo(),
11506 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11510 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11511 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11512 StackSlot, MachinePointerInfo(),
11514 // For i64 source, we need to add the appropriate power of 2 if the input
11515 // was negative. This is the same as the optimization in
11516 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11517 // we must be careful to do the computation in x87 extended precision, not
11518 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11519 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11520 MachineMemOperand *MMO =
11521 DAG.getMachineFunction()
11522 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11523 MachineMemOperand::MOLoad, 8, 8);
11525 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11526 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11527 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11530 APInt FF(32, 0x5F800000ULL);
11532 // Check whether the sign bit is set.
11533 SDValue SignSet = DAG.getSetCC(dl,
11534 getSetCCResultType(*DAG.getContext(), MVT::i64),
11535 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11538 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11539 SDValue FudgePtr = DAG.getConstantPool(
11540 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11543 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11544 SDValue Zero = DAG.getIntPtrConstant(0);
11545 SDValue Four = DAG.getIntPtrConstant(4);
11546 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11548 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11550 // Load the value out, extending it from f32 to f80.
11551 // FIXME: Avoid the extend by constructing the right constant pool?
11552 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11553 FudgePtr, MachinePointerInfo::getConstantPool(),
11554 MVT::f32, false, false, false, 4);
11555 // Extend everything to 80 bits to force it to be done on x87.
11556 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11557 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11560 std::pair<SDValue,SDValue>
11561 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11562 bool IsSigned, bool IsReplace) const {
11565 EVT DstTy = Op.getValueType();
11567 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11568 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11572 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11573 DstTy.getSimpleVT() >= MVT::i16 &&
11574 "Unknown FP_TO_INT to lower!");
11576 // These are really Legal.
11577 if (DstTy == MVT::i32 &&
11578 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11579 return std::make_pair(SDValue(), SDValue());
11580 if (Subtarget->is64Bit() &&
11581 DstTy == MVT::i64 &&
11582 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11583 return std::make_pair(SDValue(), SDValue());
11585 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11586 // stack slot, or into the FTOL runtime function.
11587 MachineFunction &MF = DAG.getMachineFunction();
11588 unsigned MemSize = DstTy.getSizeInBits()/8;
11589 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11590 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11593 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11594 Opc = X86ISD::WIN_FTOL;
11596 switch (DstTy.getSimpleVT().SimpleTy) {
11597 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11598 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11599 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11600 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11603 SDValue Chain = DAG.getEntryNode();
11604 SDValue Value = Op.getOperand(0);
11605 EVT TheVT = Op.getOperand(0).getValueType();
11606 // FIXME This causes a redundant load/store if the SSE-class value is already
11607 // in memory, such as if it is on the callstack.
11608 if (isScalarFPTypeInSSEReg(TheVT)) {
11609 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11610 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11611 MachinePointerInfo::getFixedStack(SSFI),
11613 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11615 Chain, StackSlot, DAG.getValueType(TheVT)
11618 MachineMemOperand *MMO =
11619 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11620 MachineMemOperand::MOLoad, MemSize, MemSize);
11621 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11622 Chain = Value.getValue(1);
11623 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11624 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11627 MachineMemOperand *MMO =
11628 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11629 MachineMemOperand::MOStore, MemSize, MemSize);
11631 if (Opc != X86ISD::WIN_FTOL) {
11632 // Build the FP_TO_INT*_IN_MEM
11633 SDValue Ops[] = { Chain, Value, StackSlot };
11634 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11636 return std::make_pair(FIST, StackSlot);
11638 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11639 DAG.getVTList(MVT::Other, MVT::Glue),
11641 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11642 MVT::i32, ftol.getValue(1));
11643 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11644 MVT::i32, eax.getValue(2));
11645 SDValue Ops[] = { eax, edx };
11646 SDValue pair = IsReplace
11647 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11648 : DAG.getMergeValues(Ops, DL);
11649 return std::make_pair(pair, SDValue());
11653 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11654 const X86Subtarget *Subtarget) {
11655 MVT VT = Op->getSimpleValueType(0);
11656 SDValue In = Op->getOperand(0);
11657 MVT InVT = In.getSimpleValueType();
11660 // Optimize vectors in AVX mode:
11663 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11664 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11665 // Concat upper and lower parts.
11668 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11669 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11670 // Concat upper and lower parts.
11673 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11674 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11675 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11678 if (Subtarget->hasInt256())
11679 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11681 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11682 SDValue Undef = DAG.getUNDEF(InVT);
11683 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11684 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11685 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11687 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11688 VT.getVectorNumElements()/2);
11690 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11691 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11693 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11696 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11697 SelectionDAG &DAG) {
11698 MVT VT = Op->getSimpleValueType(0);
11699 SDValue In = Op->getOperand(0);
11700 MVT InVT = In.getSimpleValueType();
11702 unsigned int NumElts = VT.getVectorNumElements();
11703 if (NumElts != 8 && NumElts != 16)
11706 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11707 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11709 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11710 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11711 // Now we have only mask extension
11712 assert(InVT.getVectorElementType() == MVT::i1);
11713 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11714 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11715 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11716 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11717 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11718 MachinePointerInfo::getConstantPool(),
11719 false, false, false, Alignment);
11721 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11722 if (VT.is512BitVector())
11724 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11727 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11728 SelectionDAG &DAG) {
11729 if (Subtarget->hasFp256()) {
11730 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11738 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11739 SelectionDAG &DAG) {
11741 MVT VT = Op.getSimpleValueType();
11742 SDValue In = Op.getOperand(0);
11743 MVT SVT = In.getSimpleValueType();
11745 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11746 return LowerZERO_EXTEND_AVX512(Op, DAG);
11748 if (Subtarget->hasFp256()) {
11749 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11754 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11755 VT.getVectorNumElements() != SVT.getVectorNumElements());
11759 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11761 MVT VT = Op.getSimpleValueType();
11762 SDValue In = Op.getOperand(0);
11763 MVT InVT = In.getSimpleValueType();
11765 if (VT == MVT::i1) {
11766 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11767 "Invalid scalar TRUNCATE operation");
11768 if (InVT.getSizeInBits() >= 32)
11770 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11771 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11773 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11774 "Invalid TRUNCATE operation");
11776 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11777 if (VT.getVectorElementType().getSizeInBits() >=8)
11778 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11780 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11781 unsigned NumElts = InVT.getVectorNumElements();
11782 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11783 if (InVT.getSizeInBits() < 512) {
11784 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11785 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11789 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11790 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11791 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11792 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11793 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11794 MachinePointerInfo::getConstantPool(),
11795 false, false, false, Alignment);
11796 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11797 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11798 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11801 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11802 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11803 if (Subtarget->hasInt256()) {
11804 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11805 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11806 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11808 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11809 DAG.getIntPtrConstant(0));
11812 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11813 DAG.getIntPtrConstant(0));
11814 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11815 DAG.getIntPtrConstant(2));
11816 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11817 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11818 static const int ShufMask[] = {0, 2, 4, 6};
11819 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11822 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11823 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11824 if (Subtarget->hasInt256()) {
11825 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11827 SmallVector<SDValue,32> pshufbMask;
11828 for (unsigned i = 0; i < 2; ++i) {
11829 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11830 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11831 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11832 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11833 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11834 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11835 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11836 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11837 for (unsigned j = 0; j < 8; ++j)
11838 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11840 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11841 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11842 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11844 static const int ShufMask[] = {0, 2, -1, -1};
11845 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11847 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11848 DAG.getIntPtrConstant(0));
11849 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11852 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11853 DAG.getIntPtrConstant(0));
11855 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11856 DAG.getIntPtrConstant(4));
11858 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11859 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11861 // The PSHUFB mask:
11862 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11863 -1, -1, -1, -1, -1, -1, -1, -1};
11865 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11866 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11867 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11869 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11870 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11872 // The MOVLHPS Mask:
11873 static const int ShufMask2[] = {0, 1, 4, 5};
11874 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11875 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11878 // Handle truncation of V256 to V128 using shuffles.
11879 if (!VT.is128BitVector() || !InVT.is256BitVector())
11882 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11884 unsigned NumElems = VT.getVectorNumElements();
11885 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11887 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11888 // Prepare truncation shuffle mask
11889 for (unsigned i = 0; i != NumElems; ++i)
11890 MaskVec[i] = i * 2;
11891 SDValue V = DAG.getVectorShuffle(NVT, DL,
11892 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11893 DAG.getUNDEF(NVT), &MaskVec[0]);
11894 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11895 DAG.getIntPtrConstant(0));
11898 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11899 SelectionDAG &DAG) const {
11900 assert(!Op.getSimpleValueType().isVector());
11902 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11903 /*IsSigned=*/ true, /*IsReplace=*/ false);
11904 SDValue FIST = Vals.first, StackSlot = Vals.second;
11905 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11906 if (!FIST.getNode()) return Op;
11908 if (StackSlot.getNode())
11909 // Load the result.
11910 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11911 FIST, StackSlot, MachinePointerInfo(),
11912 false, false, false, 0);
11914 // The node is the result.
11918 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11919 SelectionDAG &DAG) const {
11920 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11921 /*IsSigned=*/ false, /*IsReplace=*/ false);
11922 SDValue FIST = Vals.first, StackSlot = Vals.second;
11923 assert(FIST.getNode() && "Unexpected failure");
11925 if (StackSlot.getNode())
11926 // Load the result.
11927 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11928 FIST, StackSlot, MachinePointerInfo(),
11929 false, false, false, 0);
11931 // The node is the result.
11935 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11937 MVT VT = Op.getSimpleValueType();
11938 SDValue In = Op.getOperand(0);
11939 MVT SVT = In.getSimpleValueType();
11941 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11943 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11944 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11945 In, DAG.getUNDEF(SVT)));
11948 /// The only differences between FABS and FNEG are the mask and the logic op.
11949 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
11950 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
11951 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
11952 "Wrong opcode for lowering FABS or FNEG.");
11954 bool IsFABS = (Op.getOpcode() == ISD::FABS);
11956 // If this is a FABS and it has an FNEG user, bail out to fold the combination
11957 // into an FNABS. We'll lower the FABS after that if it is still in use.
11959 for (SDNode *User : Op->uses())
11960 if (User->getOpcode() == ISD::FNEG)
11963 SDValue Op0 = Op.getOperand(0);
11964 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
11967 MVT VT = Op.getSimpleValueType();
11968 // Assume scalar op for initialization; update for vector if needed.
11969 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
11970 // generate a 16-byte vector constant and logic op even for the scalar case.
11971 // Using a 16-byte mask allows folding the load of the mask with
11972 // the logic op, so it can save (~4 bytes) on code size.
11974 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11975 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
11976 // decide if we should generate a 16-byte constant mask when we only need 4 or
11977 // 8 bytes for the scalar case.
11978 if (VT.isVector()) {
11979 EltVT = VT.getVectorElementType();
11980 NumElts = VT.getVectorNumElements();
11983 unsigned EltBits = EltVT.getSizeInBits();
11984 LLVMContext *Context = DAG.getContext();
11985 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
11987 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
11988 Constant *C = ConstantInt::get(*Context, MaskElt);
11989 C = ConstantVector::getSplat(NumElts, C);
11990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11991 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11992 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11993 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11994 MachinePointerInfo::getConstantPool(),
11995 false, false, false, Alignment);
11997 if (VT.isVector()) {
11998 // For a vector, cast operands to a vector type, perform the logic op,
11999 // and cast the result back to the original value type.
12000 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12001 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12002 SDValue Operand = IsFNABS ?
12003 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12004 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12005 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12006 return DAG.getNode(ISD::BITCAST, dl, VT,
12007 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12010 // If not vector, then scalar.
12011 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12012 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12013 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12016 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12017 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12018 LLVMContext *Context = DAG.getContext();
12019 SDValue Op0 = Op.getOperand(0);
12020 SDValue Op1 = Op.getOperand(1);
12022 MVT VT = Op.getSimpleValueType();
12023 MVT SrcVT = Op1.getSimpleValueType();
12025 // If second operand is smaller, extend it first.
12026 if (SrcVT.bitsLT(VT)) {
12027 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12030 // And if it is bigger, shrink it first.
12031 if (SrcVT.bitsGT(VT)) {
12032 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12036 // At this point the operands and the result should have the same
12037 // type, and that won't be f80 since that is not custom lowered.
12039 const fltSemantics &Sem =
12040 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12041 const unsigned SizeInBits = VT.getSizeInBits();
12043 SmallVector<Constant *, 4> CV(
12044 VT == MVT::f64 ? 2 : 4,
12045 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12047 // First, clear all bits but the sign bit from the second operand (sign).
12048 CV[0] = ConstantFP::get(*Context,
12049 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12050 Constant *C = ConstantVector::get(CV);
12051 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12052 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12053 MachinePointerInfo::getConstantPool(),
12054 false, false, false, 16);
12055 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12057 // Next, clear the sign bit from the first operand (magnitude).
12058 // If it's a constant, we can clear it here.
12059 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12060 APFloat APF = Op0CN->getValueAPF();
12061 // If the magnitude is a positive zero, the sign bit alone is enough.
12062 if (APF.isPosZero())
12065 CV[0] = ConstantFP::get(*Context, APF);
12067 CV[0] = ConstantFP::get(
12069 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12071 C = ConstantVector::get(CV);
12072 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12073 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12074 MachinePointerInfo::getConstantPool(),
12075 false, false, false, 16);
12076 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12077 if (!isa<ConstantFPSDNode>(Op0))
12078 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12080 // OR the magnitude value with the sign bit.
12081 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12084 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12085 SDValue N0 = Op.getOperand(0);
12087 MVT VT = Op.getSimpleValueType();
12089 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12090 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12091 DAG.getConstant(1, VT));
12092 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12095 // Check whether an OR'd tree is PTEST-able.
12096 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12097 SelectionDAG &DAG) {
12098 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12100 if (!Subtarget->hasSSE41())
12103 if (!Op->hasOneUse())
12106 SDNode *N = Op.getNode();
12109 SmallVector<SDValue, 8> Opnds;
12110 DenseMap<SDValue, unsigned> VecInMap;
12111 SmallVector<SDValue, 8> VecIns;
12112 EVT VT = MVT::Other;
12114 // Recognize a special case where a vector is casted into wide integer to
12116 Opnds.push_back(N->getOperand(0));
12117 Opnds.push_back(N->getOperand(1));
12119 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12120 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12121 // BFS traverse all OR'd operands.
12122 if (I->getOpcode() == ISD::OR) {
12123 Opnds.push_back(I->getOperand(0));
12124 Opnds.push_back(I->getOperand(1));
12125 // Re-evaluate the number of nodes to be traversed.
12126 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12130 // Quit if a non-EXTRACT_VECTOR_ELT
12131 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12134 // Quit if without a constant index.
12135 SDValue Idx = I->getOperand(1);
12136 if (!isa<ConstantSDNode>(Idx))
12139 SDValue ExtractedFromVec = I->getOperand(0);
12140 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12141 if (M == VecInMap.end()) {
12142 VT = ExtractedFromVec.getValueType();
12143 // Quit if not 128/256-bit vector.
12144 if (!VT.is128BitVector() && !VT.is256BitVector())
12146 // Quit if not the same type.
12147 if (VecInMap.begin() != VecInMap.end() &&
12148 VT != VecInMap.begin()->first.getValueType())
12150 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12151 VecIns.push_back(ExtractedFromVec);
12153 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12156 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12157 "Not extracted from 128-/256-bit vector.");
12159 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12161 for (DenseMap<SDValue, unsigned>::const_iterator
12162 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12163 // Quit if not all elements are used.
12164 if (I->second != FullMask)
12168 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12170 // Cast all vectors into TestVT for PTEST.
12171 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12172 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12174 // If more than one full vectors are evaluated, OR them first before PTEST.
12175 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12176 // Each iteration will OR 2 nodes and append the result until there is only
12177 // 1 node left, i.e. the final OR'd value of all vectors.
12178 SDValue LHS = VecIns[Slot];
12179 SDValue RHS = VecIns[Slot + 1];
12180 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12183 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12184 VecIns.back(), VecIns.back());
12187 /// \brief return true if \c Op has a use that doesn't just read flags.
12188 static bool hasNonFlagsUse(SDValue Op) {
12189 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12191 SDNode *User = *UI;
12192 unsigned UOpNo = UI.getOperandNo();
12193 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12194 // Look pass truncate.
12195 UOpNo = User->use_begin().getOperandNo();
12196 User = *User->use_begin();
12199 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12200 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12206 /// Emit nodes that will be selected as "test Op0,Op0", or something
12208 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12209 SelectionDAG &DAG) const {
12210 if (Op.getValueType() == MVT::i1) {
12211 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12212 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12213 DAG.getConstant(0, MVT::i8));
12215 // CF and OF aren't always set the way we want. Determine which
12216 // of these we need.
12217 bool NeedCF = false;
12218 bool NeedOF = false;
12221 case X86::COND_A: case X86::COND_AE:
12222 case X86::COND_B: case X86::COND_BE:
12225 case X86::COND_G: case X86::COND_GE:
12226 case X86::COND_L: case X86::COND_LE:
12227 case X86::COND_O: case X86::COND_NO: {
12228 // Check if we really need to set the
12229 // Overflow flag. If NoSignedWrap is present
12230 // that is not actually needed.
12231 switch (Op->getOpcode()) {
12236 const BinaryWithFlagsSDNode *BinNode =
12237 cast<BinaryWithFlagsSDNode>(Op.getNode());
12238 if (BinNode->hasNoSignedWrap())
12248 // See if we can use the EFLAGS value from the operand instead of
12249 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12250 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12251 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12252 // Emit a CMP with 0, which is the TEST pattern.
12253 //if (Op.getValueType() == MVT::i1)
12254 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12255 // DAG.getConstant(0, MVT::i1));
12256 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12257 DAG.getConstant(0, Op.getValueType()));
12259 unsigned Opcode = 0;
12260 unsigned NumOperands = 0;
12262 // Truncate operations may prevent the merge of the SETCC instruction
12263 // and the arithmetic instruction before it. Attempt to truncate the operands
12264 // of the arithmetic instruction and use a reduced bit-width instruction.
12265 bool NeedTruncation = false;
12266 SDValue ArithOp = Op;
12267 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12268 SDValue Arith = Op->getOperand(0);
12269 // Both the trunc and the arithmetic op need to have one user each.
12270 if (Arith->hasOneUse())
12271 switch (Arith.getOpcode()) {
12278 NeedTruncation = true;
12284 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12285 // which may be the result of a CAST. We use the variable 'Op', which is the
12286 // non-casted variable when we check for possible users.
12287 switch (ArithOp.getOpcode()) {
12289 // Due to an isel shortcoming, be conservative if this add is likely to be
12290 // selected as part of a load-modify-store instruction. When the root node
12291 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12292 // uses of other nodes in the match, such as the ADD in this case. This
12293 // leads to the ADD being left around and reselected, with the result being
12294 // two adds in the output. Alas, even if none our users are stores, that
12295 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12296 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12297 // climbing the DAG back to the root, and it doesn't seem to be worth the
12299 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12300 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12301 if (UI->getOpcode() != ISD::CopyToReg &&
12302 UI->getOpcode() != ISD::SETCC &&
12303 UI->getOpcode() != ISD::STORE)
12306 if (ConstantSDNode *C =
12307 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12308 // An add of one will be selected as an INC.
12309 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12310 Opcode = X86ISD::INC;
12315 // An add of negative one (subtract of one) will be selected as a DEC.
12316 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12317 Opcode = X86ISD::DEC;
12323 // Otherwise use a regular EFLAGS-setting add.
12324 Opcode = X86ISD::ADD;
12329 // If we have a constant logical shift that's only used in a comparison
12330 // against zero turn it into an equivalent AND. This allows turning it into
12331 // a TEST instruction later.
12332 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12333 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12334 EVT VT = Op.getValueType();
12335 unsigned BitWidth = VT.getSizeInBits();
12336 unsigned ShAmt = Op->getConstantOperandVal(1);
12337 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12339 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12340 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12341 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12342 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12344 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12345 DAG.getConstant(Mask, VT));
12346 DAG.ReplaceAllUsesWith(Op, New);
12352 // If the primary and result isn't used, don't bother using X86ISD::AND,
12353 // because a TEST instruction will be better.
12354 if (!hasNonFlagsUse(Op))
12360 // Due to the ISEL shortcoming noted above, be conservative if this op is
12361 // likely to be selected as part of a load-modify-store instruction.
12362 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12363 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12364 if (UI->getOpcode() == ISD::STORE)
12367 // Otherwise use a regular EFLAGS-setting instruction.
12368 switch (ArithOp.getOpcode()) {
12369 default: llvm_unreachable("unexpected operator!");
12370 case ISD::SUB: Opcode = X86ISD::SUB; break;
12371 case ISD::XOR: Opcode = X86ISD::XOR; break;
12372 case ISD::AND: Opcode = X86ISD::AND; break;
12374 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12375 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12376 if (EFLAGS.getNode())
12379 Opcode = X86ISD::OR;
12393 return SDValue(Op.getNode(), 1);
12399 // If we found that truncation is beneficial, perform the truncation and
12401 if (NeedTruncation) {
12402 EVT VT = Op.getValueType();
12403 SDValue WideVal = Op->getOperand(0);
12404 EVT WideVT = WideVal.getValueType();
12405 unsigned ConvertedOp = 0;
12406 // Use a target machine opcode to prevent further DAGCombine
12407 // optimizations that may separate the arithmetic operations
12408 // from the setcc node.
12409 switch (WideVal.getOpcode()) {
12411 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12412 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12413 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12414 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12415 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12420 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12421 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12422 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12423 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12429 // Emit a CMP with 0, which is the TEST pattern.
12430 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12431 DAG.getConstant(0, Op.getValueType()));
12433 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12434 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12436 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12437 DAG.ReplaceAllUsesWith(Op, New);
12438 return SDValue(New.getNode(), 1);
12441 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12443 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12444 SDLoc dl, SelectionDAG &DAG) const {
12445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12446 if (C->getAPIntValue() == 0)
12447 return EmitTest(Op0, X86CC, dl, DAG);
12449 if (Op0.getValueType() == MVT::i1)
12450 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12453 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12454 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12455 // Do the comparison at i32 if it's smaller, besides the Atom case.
12456 // This avoids subregister aliasing issues. Keep the smaller reference
12457 // if we're optimizing for size, however, as that'll allow better folding
12458 // of memory operations.
12459 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12460 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12461 Attribute::MinSize) &&
12462 !Subtarget->isAtom()) {
12463 unsigned ExtendOp =
12464 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12465 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12466 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12468 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12469 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12470 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12472 return SDValue(Sub.getNode(), 1);
12474 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12477 /// Convert a comparison if required by the subtarget.
12478 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12479 SelectionDAG &DAG) const {
12480 // If the subtarget does not support the FUCOMI instruction, floating-point
12481 // comparisons have to be converted.
12482 if (Subtarget->hasCMov() ||
12483 Cmp.getOpcode() != X86ISD::CMP ||
12484 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12485 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12488 // The instruction selector will select an FUCOM instruction instead of
12489 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12490 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12491 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12493 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12494 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12495 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12496 DAG.getConstant(8, MVT::i8));
12497 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12498 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12501 /// The minimum architected relative accuracy is 2^-12. We need one
12502 /// Newton-Raphson step to have a good float result (24 bits of precision).
12503 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12504 DAGCombinerInfo &DCI,
12505 unsigned &RefinementSteps,
12506 bool &UseOneConstNR) const {
12507 // FIXME: We should use instruction latency models to calculate the cost of
12508 // each potential sequence, but this is very hard to do reliably because
12509 // at least Intel's Core* chips have variable timing based on the number of
12510 // significant digits in the divisor and/or sqrt operand.
12511 if (!Subtarget->useSqrtEst())
12514 EVT VT = Op.getValueType();
12516 // SSE1 has rsqrtss and rsqrtps.
12517 // TODO: Add support for AVX512 (v16f32).
12518 // It is likely not profitable to do this for f64 because a double-precision
12519 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12520 // instructions: convert to single, rsqrtss, convert back to double, refine
12521 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12522 // along with FMA, this could be a throughput win.
12523 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12524 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12525 RefinementSteps = 1;
12526 UseOneConstNR = false;
12527 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12532 /// The minimum architected relative accuracy is 2^-12. We need one
12533 /// Newton-Raphson step to have a good float result (24 bits of precision).
12534 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12535 DAGCombinerInfo &DCI,
12536 unsigned &RefinementSteps) const {
12537 // FIXME: We should use instruction latency models to calculate the cost of
12538 // each potential sequence, but this is very hard to do reliably because
12539 // at least Intel's Core* chips have variable timing based on the number of
12540 // significant digits in the divisor.
12541 if (!Subtarget->useReciprocalEst())
12544 EVT VT = Op.getValueType();
12546 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12547 // TODO: Add support for AVX512 (v16f32).
12548 // It is likely not profitable to do this for f64 because a double-precision
12549 // reciprocal estimate with refinement on x86 prior to FMA requires
12550 // 15 instructions: convert to single, rcpss, convert back to double, refine
12551 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12552 // along with FMA, this could be a throughput win.
12553 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12554 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12555 RefinementSteps = ReciprocalEstimateRefinementSteps;
12556 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12561 static bool isAllOnes(SDValue V) {
12562 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12563 return C && C->isAllOnesValue();
12566 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12567 /// if it's possible.
12568 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12569 SDLoc dl, SelectionDAG &DAG) const {
12570 SDValue Op0 = And.getOperand(0);
12571 SDValue Op1 = And.getOperand(1);
12572 if (Op0.getOpcode() == ISD::TRUNCATE)
12573 Op0 = Op0.getOperand(0);
12574 if (Op1.getOpcode() == ISD::TRUNCATE)
12575 Op1 = Op1.getOperand(0);
12578 if (Op1.getOpcode() == ISD::SHL)
12579 std::swap(Op0, Op1);
12580 if (Op0.getOpcode() == ISD::SHL) {
12581 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12582 if (And00C->getZExtValue() == 1) {
12583 // If we looked past a truncate, check that it's only truncating away
12585 unsigned BitWidth = Op0.getValueSizeInBits();
12586 unsigned AndBitWidth = And.getValueSizeInBits();
12587 if (BitWidth > AndBitWidth) {
12589 DAG.computeKnownBits(Op0, Zeros, Ones);
12590 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12594 RHS = Op0.getOperand(1);
12596 } else if (Op1.getOpcode() == ISD::Constant) {
12597 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12598 uint64_t AndRHSVal = AndRHS->getZExtValue();
12599 SDValue AndLHS = Op0;
12601 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12602 LHS = AndLHS.getOperand(0);
12603 RHS = AndLHS.getOperand(1);
12606 // Use BT if the immediate can't be encoded in a TEST instruction.
12607 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12609 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12613 if (LHS.getNode()) {
12614 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12615 // instruction. Since the shift amount is in-range-or-undefined, we know
12616 // that doing a bittest on the i32 value is ok. We extend to i32 because
12617 // the encoding for the i16 version is larger than the i32 version.
12618 // Also promote i16 to i32 for performance / code size reason.
12619 if (LHS.getValueType() == MVT::i8 ||
12620 LHS.getValueType() == MVT::i16)
12621 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12623 // If the operand types disagree, extend the shift amount to match. Since
12624 // BT ignores high bits (like shifts) we can use anyextend.
12625 if (LHS.getValueType() != RHS.getValueType())
12626 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12628 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12629 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12630 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12631 DAG.getConstant(Cond, MVT::i8), BT);
12637 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12639 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12644 // SSE Condition code mapping:
12653 switch (SetCCOpcode) {
12654 default: llvm_unreachable("Unexpected SETCC condition");
12656 case ISD::SETEQ: SSECC = 0; break;
12658 case ISD::SETGT: Swap = true; // Fallthrough
12660 case ISD::SETOLT: SSECC = 1; break;
12662 case ISD::SETGE: Swap = true; // Fallthrough
12664 case ISD::SETOLE: SSECC = 2; break;
12665 case ISD::SETUO: SSECC = 3; break;
12667 case ISD::SETNE: SSECC = 4; break;
12668 case ISD::SETULE: Swap = true; // Fallthrough
12669 case ISD::SETUGE: SSECC = 5; break;
12670 case ISD::SETULT: Swap = true; // Fallthrough
12671 case ISD::SETUGT: SSECC = 6; break;
12672 case ISD::SETO: SSECC = 7; break;
12674 case ISD::SETONE: SSECC = 8; break;
12677 std::swap(Op0, Op1);
12682 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12683 // ones, and then concatenate the result back.
12684 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12685 MVT VT = Op.getSimpleValueType();
12687 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12688 "Unsupported value type for operation");
12690 unsigned NumElems = VT.getVectorNumElements();
12692 SDValue CC = Op.getOperand(2);
12694 // Extract the LHS vectors
12695 SDValue LHS = Op.getOperand(0);
12696 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12697 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12699 // Extract the RHS vectors
12700 SDValue RHS = Op.getOperand(1);
12701 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12702 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12704 // Issue the operation on the smaller types and concatenate the result back
12705 MVT EltVT = VT.getVectorElementType();
12706 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12707 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12708 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12709 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12712 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12713 const X86Subtarget *Subtarget) {
12714 SDValue Op0 = Op.getOperand(0);
12715 SDValue Op1 = Op.getOperand(1);
12716 SDValue CC = Op.getOperand(2);
12717 MVT VT = Op.getSimpleValueType();
12720 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12721 Op.getValueType().getScalarType() == MVT::i1 &&
12722 "Cannot set masked compare for this operation");
12724 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12726 bool Unsigned = false;
12729 switch (SetCCOpcode) {
12730 default: llvm_unreachable("Unexpected SETCC condition");
12731 case ISD::SETNE: SSECC = 4; break;
12732 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12733 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12734 case ISD::SETLT: Swap = true; //fall-through
12735 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12736 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12737 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12738 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12739 case ISD::SETULE: Unsigned = true; //fall-through
12740 case ISD::SETLE: SSECC = 2; break;
12744 std::swap(Op0, Op1);
12746 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12747 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12748 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12749 DAG.getConstant(SSECC, MVT::i8));
12752 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12753 /// operand \p Op1. If non-trivial (for example because it's not constant)
12754 /// return an empty value.
12755 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12757 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12761 MVT VT = Op1.getSimpleValueType();
12762 MVT EVT = VT.getVectorElementType();
12763 unsigned n = VT.getVectorNumElements();
12764 SmallVector<SDValue, 8> ULTOp1;
12766 for (unsigned i = 0; i < n; ++i) {
12767 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12768 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12771 // Avoid underflow.
12772 APInt Val = Elt->getAPIntValue();
12776 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12779 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12782 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12783 SelectionDAG &DAG) {
12784 SDValue Op0 = Op.getOperand(0);
12785 SDValue Op1 = Op.getOperand(1);
12786 SDValue CC = Op.getOperand(2);
12787 MVT VT = Op.getSimpleValueType();
12788 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12789 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12794 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12795 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12798 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12799 unsigned Opc = X86ISD::CMPP;
12800 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12801 assert(VT.getVectorNumElements() <= 16);
12802 Opc = X86ISD::CMPM;
12804 // In the two special cases we can't handle, emit two comparisons.
12807 unsigned CombineOpc;
12808 if (SetCCOpcode == ISD::SETUEQ) {
12809 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12811 assert(SetCCOpcode == ISD::SETONE);
12812 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12815 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12816 DAG.getConstant(CC0, MVT::i8));
12817 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12818 DAG.getConstant(CC1, MVT::i8));
12819 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12821 // Handle all other FP comparisons here.
12822 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12823 DAG.getConstant(SSECC, MVT::i8));
12826 // Break 256-bit integer vector compare into smaller ones.
12827 if (VT.is256BitVector() && !Subtarget->hasInt256())
12828 return Lower256IntVSETCC(Op, DAG);
12830 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12831 EVT OpVT = Op1.getValueType();
12832 if (Subtarget->hasAVX512()) {
12833 if (Op1.getValueType().is512BitVector() ||
12834 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12835 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12836 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12838 // In AVX-512 architecture setcc returns mask with i1 elements,
12839 // But there is no compare instruction for i8 and i16 elements in KNL.
12840 // We are not talking about 512-bit operands in this case, these
12841 // types are illegal.
12843 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12844 OpVT.getVectorElementType().getSizeInBits() >= 8))
12845 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12846 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12849 // We are handling one of the integer comparisons here. Since SSE only has
12850 // GT and EQ comparisons for integer, swapping operands and multiple
12851 // operations may be required for some comparisons.
12853 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12854 bool Subus = false;
12856 switch (SetCCOpcode) {
12857 default: llvm_unreachable("Unexpected SETCC condition");
12858 case ISD::SETNE: Invert = true;
12859 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12860 case ISD::SETLT: Swap = true;
12861 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12862 case ISD::SETGE: Swap = true;
12863 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12864 Invert = true; break;
12865 case ISD::SETULT: Swap = true;
12866 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12867 FlipSigns = true; break;
12868 case ISD::SETUGE: Swap = true;
12869 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12870 FlipSigns = true; Invert = true; break;
12873 // Special case: Use min/max operations for SETULE/SETUGE
12874 MVT VET = VT.getVectorElementType();
12876 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12877 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12880 switch (SetCCOpcode) {
12882 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12883 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12886 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12889 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12890 if (!MinMax && hasSubus) {
12891 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12893 // t = psubus Op0, Op1
12894 // pcmpeq t, <0..0>
12895 switch (SetCCOpcode) {
12897 case ISD::SETULT: {
12898 // If the comparison is against a constant we can turn this into a
12899 // setule. With psubus, setule does not require a swap. This is
12900 // beneficial because the constant in the register is no longer
12901 // destructed as the destination so it can be hoisted out of a loop.
12902 // Only do this pre-AVX since vpcmp* is no longer destructive.
12903 if (Subtarget->hasAVX())
12905 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12906 if (ULEOp1.getNode()) {
12908 Subus = true; Invert = false; Swap = false;
12912 // Psubus is better than flip-sign because it requires no inversion.
12913 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12914 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12918 Opc = X86ISD::SUBUS;
12924 std::swap(Op0, Op1);
12926 // Check that the operation in question is available (most are plain SSE2,
12927 // but PCMPGTQ and PCMPEQQ have different requirements).
12928 if (VT == MVT::v2i64) {
12929 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12930 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12932 // First cast everything to the right type.
12933 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12934 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12936 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12937 // bits of the inputs before performing those operations. The lower
12938 // compare is always unsigned.
12941 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12943 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12944 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12945 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12946 Sign, Zero, Sign, Zero);
12948 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12949 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12951 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12952 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12953 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12955 // Create masks for only the low parts/high parts of the 64 bit integers.
12956 static const int MaskHi[] = { 1, 1, 3, 3 };
12957 static const int MaskLo[] = { 0, 0, 2, 2 };
12958 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12959 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12960 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12962 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12963 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12966 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12968 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12971 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12972 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12973 // pcmpeqd + pshufd + pand.
12974 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12976 // First cast everything to the right type.
12977 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12978 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12981 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12983 // Make sure the lower and upper halves are both all-ones.
12984 static const int Mask[] = { 1, 0, 3, 2 };
12985 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12986 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12989 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12991 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12995 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12996 // bits of the inputs before performing those operations.
12998 EVT EltVT = VT.getVectorElementType();
12999 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13000 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13001 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13004 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13006 // If the logical-not of the result is required, perform that now.
13008 Result = DAG.getNOT(dl, Result, VT);
13011 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13014 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13015 getZeroVector(VT, Subtarget, DAG, dl));
13020 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13022 MVT VT = Op.getSimpleValueType();
13024 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13026 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13027 && "SetCC type must be 8-bit or 1-bit integer");
13028 SDValue Op0 = Op.getOperand(0);
13029 SDValue Op1 = Op.getOperand(1);
13031 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13033 // Optimize to BT if possible.
13034 // Lower (X & (1 << N)) == 0 to BT(X, N).
13035 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13036 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13037 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13038 Op1.getOpcode() == ISD::Constant &&
13039 cast<ConstantSDNode>(Op1)->isNullValue() &&
13040 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13041 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13042 if (NewSetCC.getNode()) {
13044 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13049 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13051 if (Op1.getOpcode() == ISD::Constant &&
13052 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13053 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13054 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13056 // If the input is a setcc, then reuse the input setcc or use a new one with
13057 // the inverted condition.
13058 if (Op0.getOpcode() == X86ISD::SETCC) {
13059 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13060 bool Invert = (CC == ISD::SETNE) ^
13061 cast<ConstantSDNode>(Op1)->isNullValue();
13065 CCode = X86::GetOppositeBranchCondition(CCode);
13066 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13067 DAG.getConstant(CCode, MVT::i8),
13068 Op0.getOperand(1));
13070 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13074 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13075 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13076 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13078 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13079 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13082 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13083 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13084 if (X86CC == X86::COND_INVALID)
13087 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13088 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13089 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13090 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13092 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13096 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13097 static bool isX86LogicalCmp(SDValue Op) {
13098 unsigned Opc = Op.getNode()->getOpcode();
13099 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13100 Opc == X86ISD::SAHF)
13102 if (Op.getResNo() == 1 &&
13103 (Opc == X86ISD::ADD ||
13104 Opc == X86ISD::SUB ||
13105 Opc == X86ISD::ADC ||
13106 Opc == X86ISD::SBB ||
13107 Opc == X86ISD::SMUL ||
13108 Opc == X86ISD::UMUL ||
13109 Opc == X86ISD::INC ||
13110 Opc == X86ISD::DEC ||
13111 Opc == X86ISD::OR ||
13112 Opc == X86ISD::XOR ||
13113 Opc == X86ISD::AND))
13116 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13122 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13123 if (V.getOpcode() != ISD::TRUNCATE)
13126 SDValue VOp0 = V.getOperand(0);
13127 unsigned InBits = VOp0.getValueSizeInBits();
13128 unsigned Bits = V.getValueSizeInBits();
13129 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13132 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13133 bool addTest = true;
13134 SDValue Cond = Op.getOperand(0);
13135 SDValue Op1 = Op.getOperand(1);
13136 SDValue Op2 = Op.getOperand(2);
13138 EVT VT = Op1.getValueType();
13141 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13142 // are available. Otherwise fp cmovs get lowered into a less efficient branch
13143 // sequence later on.
13144 if (Cond.getOpcode() == ISD::SETCC &&
13145 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13146 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13147 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13148 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13149 int SSECC = translateX86FSETCC(
13150 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13153 if (Subtarget->hasAVX512()) {
13154 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13155 DAG.getConstant(SSECC, MVT::i8));
13156 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13158 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13159 DAG.getConstant(SSECC, MVT::i8));
13160 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13161 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13162 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13166 if (Cond.getOpcode() == ISD::SETCC) {
13167 SDValue NewCond = LowerSETCC(Cond, DAG);
13168 if (NewCond.getNode())
13172 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13173 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13174 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13175 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13176 if (Cond.getOpcode() == X86ISD::SETCC &&
13177 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13178 isZero(Cond.getOperand(1).getOperand(1))) {
13179 SDValue Cmp = Cond.getOperand(1);
13181 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13183 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13184 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13185 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13187 SDValue CmpOp0 = Cmp.getOperand(0);
13188 // Apply further optimizations for special cases
13189 // (select (x != 0), -1, 0) -> neg & sbb
13190 // (select (x == 0), 0, -1) -> neg & sbb
13191 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13192 if (YC->isNullValue() &&
13193 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13194 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13195 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13196 DAG.getConstant(0, CmpOp0.getValueType()),
13198 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13199 DAG.getConstant(X86::COND_B, MVT::i8),
13200 SDValue(Neg.getNode(), 1));
13204 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13205 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13206 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13208 SDValue Res = // Res = 0 or -1.
13209 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13210 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13212 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13213 Res = DAG.getNOT(DL, Res, Res.getValueType());
13215 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13216 if (!N2C || !N2C->isNullValue())
13217 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13222 // Look past (and (setcc_carry (cmp ...)), 1).
13223 if (Cond.getOpcode() == ISD::AND &&
13224 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13225 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13226 if (C && C->getAPIntValue() == 1)
13227 Cond = Cond.getOperand(0);
13230 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13231 // setting operand in place of the X86ISD::SETCC.
13232 unsigned CondOpcode = Cond.getOpcode();
13233 if (CondOpcode == X86ISD::SETCC ||
13234 CondOpcode == X86ISD::SETCC_CARRY) {
13235 CC = Cond.getOperand(0);
13237 SDValue Cmp = Cond.getOperand(1);
13238 unsigned Opc = Cmp.getOpcode();
13239 MVT VT = Op.getSimpleValueType();
13241 bool IllegalFPCMov = false;
13242 if (VT.isFloatingPoint() && !VT.isVector() &&
13243 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13244 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13246 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13247 Opc == X86ISD::BT) { // FIXME
13251 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13252 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13253 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13254 Cond.getOperand(0).getValueType() != MVT::i8)) {
13255 SDValue LHS = Cond.getOperand(0);
13256 SDValue RHS = Cond.getOperand(1);
13257 unsigned X86Opcode;
13260 switch (CondOpcode) {
13261 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13262 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13263 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13264 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13265 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13266 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13267 default: llvm_unreachable("unexpected overflowing operator");
13269 if (CondOpcode == ISD::UMULO)
13270 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13273 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13275 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13277 if (CondOpcode == ISD::UMULO)
13278 Cond = X86Op.getValue(2);
13280 Cond = X86Op.getValue(1);
13282 CC = DAG.getConstant(X86Cond, MVT::i8);
13287 // Look pass the truncate if the high bits are known zero.
13288 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13289 Cond = Cond.getOperand(0);
13291 // We know the result of AND is compared against zero. Try to match
13293 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13294 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13295 if (NewSetCC.getNode()) {
13296 CC = NewSetCC.getOperand(0);
13297 Cond = NewSetCC.getOperand(1);
13304 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13305 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13308 // a < b ? -1 : 0 -> RES = ~setcc_carry
13309 // a < b ? 0 : -1 -> RES = setcc_carry
13310 // a >= b ? -1 : 0 -> RES = setcc_carry
13311 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13312 if (Cond.getOpcode() == X86ISD::SUB) {
13313 Cond = ConvertCmpIfNecessary(Cond, DAG);
13314 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13316 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13317 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13318 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13319 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13320 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13321 return DAG.getNOT(DL, Res, Res.getValueType());
13326 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13327 // widen the cmov and push the truncate through. This avoids introducing a new
13328 // branch during isel and doesn't add any extensions.
13329 if (Op.getValueType() == MVT::i8 &&
13330 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13331 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13332 if (T1.getValueType() == T2.getValueType() &&
13333 // Blacklist CopyFromReg to avoid partial register stalls.
13334 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13335 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13336 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13337 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13341 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13342 // condition is true.
13343 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13344 SDValue Ops[] = { Op2, Op1, CC, Cond };
13345 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13348 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13349 SelectionDAG &DAG) {
13350 MVT VT = Op->getSimpleValueType(0);
13351 SDValue In = Op->getOperand(0);
13352 MVT InVT = In.getSimpleValueType();
13353 MVT VTElt = VT.getVectorElementType();
13354 MVT InVTElt = InVT.getVectorElementType();
13358 if ((InVTElt == MVT::i1) &&
13359 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13360 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13362 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13363 VTElt.getSizeInBits() <= 16)) ||
13365 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13366 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13368 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13369 VTElt.getSizeInBits() >= 32))))
13370 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13372 unsigned int NumElts = VT.getVectorNumElements();
13374 if (NumElts != 8 && NumElts != 16)
13377 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13378 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13379 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13380 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13384 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13386 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13387 Constant *C = ConstantInt::get(*DAG.getContext(),
13388 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13390 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13391 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13392 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13393 MachinePointerInfo::getConstantPool(),
13394 false, false, false, Alignment);
13395 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13396 if (VT.is512BitVector())
13398 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13401 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13402 SelectionDAG &DAG) {
13403 MVT VT = Op->getSimpleValueType(0);
13404 SDValue In = Op->getOperand(0);
13405 MVT InVT = In.getSimpleValueType();
13408 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13409 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13411 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13412 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13413 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13416 if (Subtarget->hasInt256())
13417 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13419 // Optimize vectors in AVX mode
13420 // Sign extend v8i16 to v8i32 and
13423 // Divide input vector into two parts
13424 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13425 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13426 // concat the vectors to original VT
13428 unsigned NumElems = InVT.getVectorNumElements();
13429 SDValue Undef = DAG.getUNDEF(InVT);
13431 SmallVector<int,8> ShufMask1(NumElems, -1);
13432 for (unsigned i = 0; i != NumElems/2; ++i)
13435 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13437 SmallVector<int,8> ShufMask2(NumElems, -1);
13438 for (unsigned i = 0; i != NumElems/2; ++i)
13439 ShufMask2[i] = i + NumElems/2;
13441 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13443 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13444 VT.getVectorNumElements()/2);
13446 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13447 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13449 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13452 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13453 // may emit an illegal shuffle but the expansion is still better than scalar
13454 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13455 // we'll emit a shuffle and a arithmetic shift.
13456 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13457 // TODO: It is possible to support ZExt by zeroing the undef values during
13458 // the shuffle phase or after the shuffle.
13459 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13460 SelectionDAG &DAG) {
13461 MVT RegVT = Op.getSimpleValueType();
13462 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13463 assert(RegVT.isInteger() &&
13464 "We only custom lower integer vector sext loads.");
13466 // Nothing useful we can do without SSE2 shuffles.
13467 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13469 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13471 EVT MemVT = Ld->getMemoryVT();
13472 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13473 unsigned RegSz = RegVT.getSizeInBits();
13475 ISD::LoadExtType Ext = Ld->getExtensionType();
13477 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13478 && "Only anyext and sext are currently implemented.");
13479 assert(MemVT != RegVT && "Cannot extend to the same type");
13480 assert(MemVT.isVector() && "Must load a vector from memory");
13482 unsigned NumElems = RegVT.getVectorNumElements();
13483 unsigned MemSz = MemVT.getSizeInBits();
13484 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13486 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13487 // The only way in which we have a legal 256-bit vector result but not the
13488 // integer 256-bit operations needed to directly lower a sextload is if we
13489 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13490 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13491 // correctly legalized. We do this late to allow the canonical form of
13492 // sextload to persist throughout the rest of the DAG combiner -- it wants
13493 // to fold together any extensions it can, and so will fuse a sign_extend
13494 // of an sextload into a sextload targeting a wider value.
13496 if (MemSz == 128) {
13497 // Just switch this to a normal load.
13498 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13499 "it must be a legal 128-bit vector "
13501 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13502 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13503 Ld->isInvariant(), Ld->getAlignment());
13505 assert(MemSz < 128 &&
13506 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13507 // Do an sext load to a 128-bit vector type. We want to use the same
13508 // number of elements, but elements half as wide. This will end up being
13509 // recursively lowered by this routine, but will succeed as we definitely
13510 // have all the necessary features if we're using AVX1.
13512 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13513 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13515 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13516 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13517 Ld->isNonTemporal(), Ld->isInvariant(),
13518 Ld->getAlignment());
13521 // Replace chain users with the new chain.
13522 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13523 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13525 // Finally, do a normal sign-extend to the desired register.
13526 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13529 // All sizes must be a power of two.
13530 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13531 "Non-power-of-two elements are not custom lowered!");
13533 // Attempt to load the original value using scalar loads.
13534 // Find the largest scalar type that divides the total loaded size.
13535 MVT SclrLoadTy = MVT::i8;
13536 for (MVT Tp : MVT::integer_valuetypes()) {
13537 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13542 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13543 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13545 SclrLoadTy = MVT::f64;
13547 // Calculate the number of scalar loads that we need to perform
13548 // in order to load our vector from memory.
13549 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13551 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13552 "Can only lower sext loads with a single scalar load!");
13554 unsigned loadRegZize = RegSz;
13555 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13558 // Represent our vector as a sequence of elements which are the
13559 // largest scalar that we can load.
13560 EVT LoadUnitVecVT = EVT::getVectorVT(
13561 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13563 // Represent the data using the same element type that is stored in
13564 // memory. In practice, we ''widen'' MemVT.
13566 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13567 loadRegZize / MemVT.getScalarType().getSizeInBits());
13569 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13570 "Invalid vector type");
13572 // We can't shuffle using an illegal type.
13573 assert(TLI.isTypeLegal(WideVecVT) &&
13574 "We only lower types that form legal widened vector types");
13576 SmallVector<SDValue, 8> Chains;
13577 SDValue Ptr = Ld->getBasePtr();
13578 SDValue Increment =
13579 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13580 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13582 for (unsigned i = 0; i < NumLoads; ++i) {
13583 // Perform a single load.
13584 SDValue ScalarLoad =
13585 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13586 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13587 Ld->getAlignment());
13588 Chains.push_back(ScalarLoad.getValue(1));
13589 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13590 // another round of DAGCombining.
13592 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13594 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13595 ScalarLoad, DAG.getIntPtrConstant(i));
13597 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13600 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13602 // Bitcast the loaded value to a vector of the original element type, in
13603 // the size of the target vector type.
13604 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13605 unsigned SizeRatio = RegSz / MemSz;
13607 if (Ext == ISD::SEXTLOAD) {
13608 // If we have SSE4.1, we can directly emit a VSEXT node.
13609 if (Subtarget->hasSSE41()) {
13610 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13611 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13615 // Otherwise we'll shuffle the small elements in the high bits of the
13616 // larger type and perform an arithmetic shift. If the shift is not legal
13617 // it's better to scalarize.
13618 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13619 "We can't implement a sext load without an arithmetic right shift!");
13621 // Redistribute the loaded elements into the different locations.
13622 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13623 for (unsigned i = 0; i != NumElems; ++i)
13624 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13626 SDValue Shuff = DAG.getVectorShuffle(
13627 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13629 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13631 // Build the arithmetic shift.
13632 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13633 MemVT.getVectorElementType().getSizeInBits();
13635 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13637 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13641 // Redistribute the loaded elements into the different locations.
13642 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13643 for (unsigned i = 0; i != NumElems; ++i)
13644 ShuffleVec[i * SizeRatio] = i;
13646 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13647 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13649 // Bitcast to the requested type.
13650 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13651 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13655 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13656 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13657 // from the AND / OR.
13658 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13659 Opc = Op.getOpcode();
13660 if (Opc != ISD::OR && Opc != ISD::AND)
13662 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13663 Op.getOperand(0).hasOneUse() &&
13664 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13665 Op.getOperand(1).hasOneUse());
13668 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13669 // 1 and that the SETCC node has a single use.
13670 static bool isXor1OfSetCC(SDValue Op) {
13671 if (Op.getOpcode() != ISD::XOR)
13673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13674 if (N1C && N1C->getAPIntValue() == 1) {
13675 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13676 Op.getOperand(0).hasOneUse();
13681 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13682 bool addTest = true;
13683 SDValue Chain = Op.getOperand(0);
13684 SDValue Cond = Op.getOperand(1);
13685 SDValue Dest = Op.getOperand(2);
13688 bool Inverted = false;
13690 if (Cond.getOpcode() == ISD::SETCC) {
13691 // Check for setcc([su]{add,sub,mul}o == 0).
13692 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13693 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13694 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13695 Cond.getOperand(0).getResNo() == 1 &&
13696 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13697 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13698 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13699 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13700 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13701 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13703 Cond = Cond.getOperand(0);
13705 SDValue NewCond = LowerSETCC(Cond, DAG);
13706 if (NewCond.getNode())
13711 // FIXME: LowerXALUO doesn't handle these!!
13712 else if (Cond.getOpcode() == X86ISD::ADD ||
13713 Cond.getOpcode() == X86ISD::SUB ||
13714 Cond.getOpcode() == X86ISD::SMUL ||
13715 Cond.getOpcode() == X86ISD::UMUL)
13716 Cond = LowerXALUO(Cond, DAG);
13719 // Look pass (and (setcc_carry (cmp ...)), 1).
13720 if (Cond.getOpcode() == ISD::AND &&
13721 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13722 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13723 if (C && C->getAPIntValue() == 1)
13724 Cond = Cond.getOperand(0);
13727 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13728 // setting operand in place of the X86ISD::SETCC.
13729 unsigned CondOpcode = Cond.getOpcode();
13730 if (CondOpcode == X86ISD::SETCC ||
13731 CondOpcode == X86ISD::SETCC_CARRY) {
13732 CC = Cond.getOperand(0);
13734 SDValue Cmp = Cond.getOperand(1);
13735 unsigned Opc = Cmp.getOpcode();
13736 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13737 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13741 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13745 // These can only come from an arithmetic instruction with overflow,
13746 // e.g. SADDO, UADDO.
13747 Cond = Cond.getNode()->getOperand(1);
13753 CondOpcode = Cond.getOpcode();
13754 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13755 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13756 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13757 Cond.getOperand(0).getValueType() != MVT::i8)) {
13758 SDValue LHS = Cond.getOperand(0);
13759 SDValue RHS = Cond.getOperand(1);
13760 unsigned X86Opcode;
13763 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13764 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13766 switch (CondOpcode) {
13767 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13769 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13771 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13774 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13775 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13777 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13779 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13782 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13783 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13784 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13785 default: llvm_unreachable("unexpected overflowing operator");
13788 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13789 if (CondOpcode == ISD::UMULO)
13790 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13793 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13795 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13797 if (CondOpcode == ISD::UMULO)
13798 Cond = X86Op.getValue(2);
13800 Cond = X86Op.getValue(1);
13802 CC = DAG.getConstant(X86Cond, MVT::i8);
13806 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13807 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13808 if (CondOpc == ISD::OR) {
13809 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13810 // two branches instead of an explicit OR instruction with a
13812 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13813 isX86LogicalCmp(Cmp)) {
13814 CC = Cond.getOperand(0).getOperand(0);
13815 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13816 Chain, Dest, CC, Cmp);
13817 CC = Cond.getOperand(1).getOperand(0);
13821 } else { // ISD::AND
13822 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13823 // two branches instead of an explicit AND instruction with a
13824 // separate test. However, we only do this if this block doesn't
13825 // have a fall-through edge, because this requires an explicit
13826 // jmp when the condition is false.
13827 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13828 isX86LogicalCmp(Cmp) &&
13829 Op.getNode()->hasOneUse()) {
13830 X86::CondCode CCode =
13831 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13832 CCode = X86::GetOppositeBranchCondition(CCode);
13833 CC = DAG.getConstant(CCode, MVT::i8);
13834 SDNode *User = *Op.getNode()->use_begin();
13835 // Look for an unconditional branch following this conditional branch.
13836 // We need this because we need to reverse the successors in order
13837 // to implement FCMP_OEQ.
13838 if (User->getOpcode() == ISD::BR) {
13839 SDValue FalseBB = User->getOperand(1);
13841 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13842 assert(NewBR == User);
13846 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13847 Chain, Dest, CC, Cmp);
13848 X86::CondCode CCode =
13849 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13850 CCode = X86::GetOppositeBranchCondition(CCode);
13851 CC = DAG.getConstant(CCode, MVT::i8);
13857 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13858 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13859 // It should be transformed during dag combiner except when the condition
13860 // is set by a arithmetics with overflow node.
13861 X86::CondCode CCode =
13862 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13863 CCode = X86::GetOppositeBranchCondition(CCode);
13864 CC = DAG.getConstant(CCode, MVT::i8);
13865 Cond = Cond.getOperand(0).getOperand(1);
13867 } else if (Cond.getOpcode() == ISD::SETCC &&
13868 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13869 // For FCMP_OEQ, we can emit
13870 // two branches instead of an explicit AND instruction with a
13871 // separate test. However, we only do this if this block doesn't
13872 // have a fall-through edge, because this requires an explicit
13873 // jmp when the condition is false.
13874 if (Op.getNode()->hasOneUse()) {
13875 SDNode *User = *Op.getNode()->use_begin();
13876 // Look for an unconditional branch following this conditional branch.
13877 // We need this because we need to reverse the successors in order
13878 // to implement FCMP_OEQ.
13879 if (User->getOpcode() == ISD::BR) {
13880 SDValue FalseBB = User->getOperand(1);
13882 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13883 assert(NewBR == User);
13887 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13888 Cond.getOperand(0), Cond.getOperand(1));
13889 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13890 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13891 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13892 Chain, Dest, CC, Cmp);
13893 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13898 } else if (Cond.getOpcode() == ISD::SETCC &&
13899 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13900 // For FCMP_UNE, we can emit
13901 // two branches instead of an explicit AND instruction with a
13902 // separate test. However, we only do this if this block doesn't
13903 // have a fall-through edge, because this requires an explicit
13904 // jmp when the condition is false.
13905 if (Op.getNode()->hasOneUse()) {
13906 SDNode *User = *Op.getNode()->use_begin();
13907 // Look for an unconditional branch following this conditional branch.
13908 // We need this because we need to reverse the successors in order
13909 // to implement FCMP_UNE.
13910 if (User->getOpcode() == ISD::BR) {
13911 SDValue FalseBB = User->getOperand(1);
13913 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13914 assert(NewBR == User);
13917 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13918 Cond.getOperand(0), Cond.getOperand(1));
13919 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13920 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13921 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13922 Chain, Dest, CC, Cmp);
13923 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13933 // Look pass the truncate if the high bits are known zero.
13934 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13935 Cond = Cond.getOperand(0);
13937 // We know the result of AND is compared against zero. Try to match
13939 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13940 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13941 if (NewSetCC.getNode()) {
13942 CC = NewSetCC.getOperand(0);
13943 Cond = NewSetCC.getOperand(1);
13950 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13951 CC = DAG.getConstant(X86Cond, MVT::i8);
13952 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13954 Cond = ConvertCmpIfNecessary(Cond, DAG);
13955 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13956 Chain, Dest, CC, Cond);
13959 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13960 // Calls to _alloca are needed to probe the stack when allocating more than 4k
13961 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13962 // that the guard pages used by the OS virtual memory manager are allocated in
13963 // correct sequence.
13965 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13966 SelectionDAG &DAG) const {
13967 MachineFunction &MF = DAG.getMachineFunction();
13968 bool SplitStack = MF.shouldSplitStack();
13969 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
13974 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13975 SDNode* Node = Op.getNode();
13977 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13978 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13979 " not tell us which reg is the stack pointer!");
13980 EVT VT = Node->getValueType(0);
13981 SDValue Tmp1 = SDValue(Node, 0);
13982 SDValue Tmp2 = SDValue(Node, 1);
13983 SDValue Tmp3 = Node->getOperand(2);
13984 SDValue Chain = Tmp1.getOperand(0);
13986 // Chain the dynamic stack allocation so that it doesn't modify the stack
13987 // pointer when other instructions are using the stack.
13988 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13991 SDValue Size = Tmp2.getOperand(1);
13992 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13993 Chain = SP.getValue(1);
13994 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13995 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
13996 unsigned StackAlign = TFI.getStackAlignment();
13997 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13998 if (Align > StackAlign)
13999 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14000 DAG.getConstant(-(uint64_t)Align, VT));
14001 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14003 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14004 DAG.getIntPtrConstant(0, true), SDValue(),
14007 SDValue Ops[2] = { Tmp1, Tmp2 };
14008 return DAG.getMergeValues(Ops, dl);
14012 SDValue Chain = Op.getOperand(0);
14013 SDValue Size = Op.getOperand(1);
14014 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14015 EVT VT = Op.getNode()->getValueType(0);
14017 bool Is64Bit = Subtarget->is64Bit();
14018 EVT SPTy = getPointerTy();
14021 MachineRegisterInfo &MRI = MF.getRegInfo();
14024 // The 64 bit implementation of segmented stacks needs to clobber both r10
14025 // r11. This makes it impossible to use it along with nested parameters.
14026 const Function *F = MF.getFunction();
14028 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14030 if (I->hasNestAttr())
14031 report_fatal_error("Cannot use segmented stacks with functions that "
14032 "have nested arguments.");
14035 const TargetRegisterClass *AddrRegClass =
14036 getRegClassFor(getPointerTy());
14037 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14038 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14039 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14040 DAG.getRegister(Vreg, SPTy));
14041 SDValue Ops1[2] = { Value, Chain };
14042 return DAG.getMergeValues(Ops1, dl);
14045 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14047 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14048 Flag = Chain.getValue(1);
14049 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14051 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14053 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14054 unsigned SPReg = RegInfo->getStackRegister();
14055 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14056 Chain = SP.getValue(1);
14059 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14060 DAG.getConstant(-(uint64_t)Align, VT));
14061 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14064 SDValue Ops1[2] = { SP, Chain };
14065 return DAG.getMergeValues(Ops1, dl);
14069 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14070 MachineFunction &MF = DAG.getMachineFunction();
14071 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14073 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14076 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14077 // vastart just stores the address of the VarArgsFrameIndex slot into the
14078 // memory location argument.
14079 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14081 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14082 MachinePointerInfo(SV), false, false, 0);
14086 // gp_offset (0 - 6 * 8)
14087 // fp_offset (48 - 48 + 8 * 16)
14088 // overflow_arg_area (point to parameters coming in memory).
14090 SmallVector<SDValue, 8> MemOps;
14091 SDValue FIN = Op.getOperand(1);
14093 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14094 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14096 FIN, MachinePointerInfo(SV), false, false, 0);
14097 MemOps.push_back(Store);
14100 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14101 FIN, DAG.getIntPtrConstant(4));
14102 Store = DAG.getStore(Op.getOperand(0), DL,
14103 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14105 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14106 MemOps.push_back(Store);
14108 // Store ptr to overflow_arg_area
14109 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14110 FIN, DAG.getIntPtrConstant(4));
14111 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14113 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14114 MachinePointerInfo(SV, 8),
14116 MemOps.push_back(Store);
14118 // Store ptr to reg_save_area.
14119 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14120 FIN, DAG.getIntPtrConstant(8));
14121 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14123 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14124 MachinePointerInfo(SV, 16), false, false, 0);
14125 MemOps.push_back(Store);
14126 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14129 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14130 assert(Subtarget->is64Bit() &&
14131 "LowerVAARG only handles 64-bit va_arg!");
14132 assert((Subtarget->isTargetLinux() ||
14133 Subtarget->isTargetDarwin()) &&
14134 "Unhandled target in LowerVAARG");
14135 assert(Op.getNode()->getNumOperands() == 4);
14136 SDValue Chain = Op.getOperand(0);
14137 SDValue SrcPtr = Op.getOperand(1);
14138 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14139 unsigned Align = Op.getConstantOperandVal(3);
14142 EVT ArgVT = Op.getNode()->getValueType(0);
14143 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14144 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14147 // Decide which area this value should be read from.
14148 // TODO: Implement the AMD64 ABI in its entirety. This simple
14149 // selection mechanism works only for the basic types.
14150 if (ArgVT == MVT::f80) {
14151 llvm_unreachable("va_arg for f80 not yet implemented");
14152 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14153 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14154 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14155 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14157 llvm_unreachable("Unhandled argument type in LowerVAARG");
14160 if (ArgMode == 2) {
14161 // Sanity Check: Make sure using fp_offset makes sense.
14162 assert(!DAG.getTarget().Options.UseSoftFloat &&
14163 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14164 Attribute::NoImplicitFloat)) &&
14165 Subtarget->hasSSE1());
14168 // Insert VAARG_64 node into the DAG
14169 // VAARG_64 returns two values: Variable Argument Address, Chain
14170 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14171 DAG.getConstant(ArgMode, MVT::i8),
14172 DAG.getConstant(Align, MVT::i32)};
14173 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14174 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14175 VTs, InstOps, MVT::i64,
14176 MachinePointerInfo(SV),
14178 /*Volatile=*/false,
14180 /*WriteMem=*/true);
14181 Chain = VAARG.getValue(1);
14183 // Load the next argument and return it
14184 return DAG.getLoad(ArgVT, dl,
14187 MachinePointerInfo(),
14188 false, false, false, 0);
14191 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14192 SelectionDAG &DAG) {
14193 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14194 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14195 SDValue Chain = Op.getOperand(0);
14196 SDValue DstPtr = Op.getOperand(1);
14197 SDValue SrcPtr = Op.getOperand(2);
14198 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14199 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14202 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14203 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14205 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14208 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14209 // amount is a constant. Takes immediate version of shift as input.
14210 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14211 SDValue SrcOp, uint64_t ShiftAmt,
14212 SelectionDAG &DAG) {
14213 MVT ElementType = VT.getVectorElementType();
14215 // Fold this packed shift into its first operand if ShiftAmt is 0.
14219 // Check for ShiftAmt >= element width
14220 if (ShiftAmt >= ElementType.getSizeInBits()) {
14221 if (Opc == X86ISD::VSRAI)
14222 ShiftAmt = ElementType.getSizeInBits() - 1;
14224 return DAG.getConstant(0, VT);
14227 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14228 && "Unknown target vector shift-by-constant node");
14230 // Fold this packed vector shift into a build vector if SrcOp is a
14231 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14232 if (VT == SrcOp.getSimpleValueType() &&
14233 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14234 SmallVector<SDValue, 8> Elts;
14235 unsigned NumElts = SrcOp->getNumOperands();
14236 ConstantSDNode *ND;
14239 default: llvm_unreachable(nullptr);
14240 case X86ISD::VSHLI:
14241 for (unsigned i=0; i!=NumElts; ++i) {
14242 SDValue CurrentOp = SrcOp->getOperand(i);
14243 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14244 Elts.push_back(CurrentOp);
14247 ND = cast<ConstantSDNode>(CurrentOp);
14248 const APInt &C = ND->getAPIntValue();
14249 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14252 case X86ISD::VSRLI:
14253 for (unsigned i=0; i!=NumElts; ++i) {
14254 SDValue CurrentOp = SrcOp->getOperand(i);
14255 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14256 Elts.push_back(CurrentOp);
14259 ND = cast<ConstantSDNode>(CurrentOp);
14260 const APInt &C = ND->getAPIntValue();
14261 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14264 case X86ISD::VSRAI:
14265 for (unsigned i=0; i!=NumElts; ++i) {
14266 SDValue CurrentOp = SrcOp->getOperand(i);
14267 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14268 Elts.push_back(CurrentOp);
14271 ND = cast<ConstantSDNode>(CurrentOp);
14272 const APInt &C = ND->getAPIntValue();
14273 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14278 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14281 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14284 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14285 // may or may not be a constant. Takes immediate version of shift as input.
14286 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14287 SDValue SrcOp, SDValue ShAmt,
14288 SelectionDAG &DAG) {
14289 MVT SVT = ShAmt.getSimpleValueType();
14290 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14292 // Catch shift-by-constant.
14293 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14294 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14295 CShAmt->getZExtValue(), DAG);
14297 // Change opcode to non-immediate version
14299 default: llvm_unreachable("Unknown target vector shift node");
14300 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14301 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14302 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14305 const X86Subtarget &Subtarget =
14306 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14307 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14308 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14309 // Let the shuffle legalizer expand this shift amount node.
14310 SDValue Op0 = ShAmt.getOperand(0);
14311 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14312 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14314 // Need to build a vector containing shift amount.
14315 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14316 SmallVector<SDValue, 4> ShOps;
14317 ShOps.push_back(ShAmt);
14318 if (SVT == MVT::i32) {
14319 ShOps.push_back(DAG.getConstant(0, SVT));
14320 ShOps.push_back(DAG.getUNDEF(SVT));
14322 ShOps.push_back(DAG.getUNDEF(SVT));
14324 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14325 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14328 // The return type has to be a 128-bit type with the same element
14329 // type as the input type.
14330 MVT EltVT = VT.getVectorElementType();
14331 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14333 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14334 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14337 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14338 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14339 /// necessary casting for \p Mask when lowering masking intrinsics.
14340 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14341 SDValue PreservedSrc,
14342 const X86Subtarget *Subtarget,
14343 SelectionDAG &DAG) {
14344 EVT VT = Op.getValueType();
14345 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14346 MVT::i1, VT.getVectorNumElements());
14347 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14348 Mask.getValueType().getSizeInBits());
14351 assert(MaskVT.isSimple() && "invalid mask type");
14353 if (isAllOnes(Mask))
14356 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14357 // are extracted by EXTRACT_SUBVECTOR.
14358 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14359 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14360 DAG.getIntPtrConstant(0));
14362 switch (Op.getOpcode()) {
14364 case X86ISD::PCMPEQM:
14365 case X86ISD::PCMPGTM:
14367 case X86ISD::CMPMU:
14368 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14370 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14371 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14372 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14375 /// \brief Creates an SDNode for a predicated scalar operation.
14376 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14377 /// The mask is comming as MVT::i8 and it should be truncated
14378 /// to MVT::i1 while lowering masking intrinsics.
14379 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14380 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14381 /// a scalar instruction.
14382 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14383 SDValue PreservedSrc,
14384 const X86Subtarget *Subtarget,
14385 SelectionDAG &DAG) {
14386 if (isAllOnes(Mask))
14389 EVT VT = Op.getValueType();
14391 // The mask should be of type MVT::i1
14392 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14394 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14395 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14396 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14399 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14400 SelectionDAG &DAG) {
14402 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14403 EVT VT = Op.getValueType();
14404 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14406 switch(IntrData->Type) {
14407 case INTR_TYPE_1OP:
14408 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14409 case INTR_TYPE_2OP:
14410 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14412 case INTR_TYPE_3OP:
14413 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14414 Op.getOperand(2), Op.getOperand(3));
14415 case INTR_TYPE_1OP_MASK_RM: {
14416 SDValue Src = Op.getOperand(1);
14417 SDValue Src0 = Op.getOperand(2);
14418 SDValue Mask = Op.getOperand(3);
14419 SDValue RoundingMode = Op.getOperand(4);
14420 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14422 Mask, Src0, Subtarget, DAG);
14424 case INTR_TYPE_SCALAR_MASK_RM: {
14425 SDValue Src1 = Op.getOperand(1);
14426 SDValue Src2 = Op.getOperand(2);
14427 SDValue Src0 = Op.getOperand(3);
14428 SDValue Mask = Op.getOperand(4);
14429 SDValue RoundingMode = Op.getOperand(5);
14430 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14432 Mask, Src0, Subtarget, DAG);
14434 case INTR_TYPE_2OP_MASK: {
14435 SDValue Src1 = Op.getOperand(1);
14436 SDValue Src2 = Op.getOperand(2);
14437 SDValue PassThru = Op.getOperand(3);
14438 SDValue Mask = Op.getOperand(4);
14439 // We specify 2 possible opcodes for intrinsics with rounding modes.
14440 // First, we check if the intrinsic may have non-default rounding mode,
14441 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14442 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14443 if (IntrWithRoundingModeOpcode != 0) {
14444 SDValue Rnd = Op.getOperand(5);
14445 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14446 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14447 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14448 dl, Op.getValueType(),
14450 Mask, PassThru, Subtarget, DAG);
14453 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14455 Mask, PassThru, Subtarget, DAG);
14457 case FMA_OP_MASK: {
14458 SDValue Src1 = Op.getOperand(1);
14459 SDValue Src2 = Op.getOperand(2);
14460 SDValue Src3 = Op.getOperand(3);
14461 SDValue Mask = Op.getOperand(4);
14462 // We specify 2 possible opcodes for intrinsics with rounding modes.
14463 // First, we check if the intrinsic may have non-default rounding mode,
14464 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14465 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14466 if (IntrWithRoundingModeOpcode != 0) {
14467 SDValue Rnd = Op.getOperand(5);
14468 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14469 X86::STATIC_ROUNDING::CUR_DIRECTION)
14470 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14471 dl, Op.getValueType(),
14472 Src1, Src2, Src3, Rnd),
14473 Mask, Src1, Subtarget, DAG);
14475 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14476 dl, Op.getValueType(),
14478 Mask, Src1, Subtarget, DAG);
14481 case CMP_MASK_CC: {
14482 // Comparison intrinsics with masks.
14483 // Example of transformation:
14484 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14485 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14487 // (v8i1 (insert_subvector undef,
14488 // (v2i1 (and (PCMPEQM %a, %b),
14489 // (extract_subvector
14490 // (v8i1 (bitcast %mask)), 0))), 0))))
14491 EVT VT = Op.getOperand(1).getValueType();
14492 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14493 VT.getVectorNumElements());
14494 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14495 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14496 Mask.getValueType().getSizeInBits());
14498 if (IntrData->Type == CMP_MASK_CC) {
14499 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14500 Op.getOperand(2), Op.getOperand(3));
14502 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14503 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14506 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14507 DAG.getTargetConstant(0, MaskVT),
14509 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14510 DAG.getUNDEF(BitcastVT), CmpMask,
14511 DAG.getIntPtrConstant(0));
14512 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14514 case COMI: { // Comparison intrinsics
14515 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14516 SDValue LHS = Op.getOperand(1);
14517 SDValue RHS = Op.getOperand(2);
14518 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14519 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14520 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14521 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14522 DAG.getConstant(X86CC, MVT::i8), Cond);
14523 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14526 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14527 Op.getOperand(1), Op.getOperand(2), DAG);
14529 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14530 Op.getSimpleValueType(),
14532 Op.getOperand(2), DAG),
14533 Op.getOperand(4), Op.getOperand(3), Subtarget,
14535 case COMPRESS_EXPAND_IN_REG: {
14536 SDValue Mask = Op.getOperand(3);
14537 SDValue DataToCompress = Op.getOperand(1);
14538 SDValue PassThru = Op.getOperand(2);
14539 if (isAllOnes(Mask)) // return data as is
14540 return Op.getOperand(1);
14541 EVT VT = Op.getValueType();
14542 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14543 VT.getVectorNumElements());
14544 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14545 Mask.getValueType().getSizeInBits());
14547 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14548 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14549 DAG.getIntPtrConstant(0));
14551 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14555 SDValue Mask = Op.getOperand(3);
14556 EVT VT = Op.getValueType();
14557 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14558 VT.getVectorNumElements());
14559 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14560 Mask.getValueType().getSizeInBits());
14562 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14563 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14564 DAG.getIntPtrConstant(0));
14565 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14574 default: return SDValue(); // Don't custom lower most intrinsics.
14576 case Intrinsic::x86_avx512_mask_valign_q_512:
14577 case Intrinsic::x86_avx512_mask_valign_d_512:
14578 // Vector source operands are swapped.
14579 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14580 Op.getValueType(), Op.getOperand(2),
14583 Op.getOperand(5), Op.getOperand(4),
14586 // ptest and testp intrinsics. The intrinsic these come from are designed to
14587 // return an integer value, not just an instruction so lower it to the ptest
14588 // or testp pattern and a setcc for the result.
14589 case Intrinsic::x86_sse41_ptestz:
14590 case Intrinsic::x86_sse41_ptestc:
14591 case Intrinsic::x86_sse41_ptestnzc:
14592 case Intrinsic::x86_avx_ptestz_256:
14593 case Intrinsic::x86_avx_ptestc_256:
14594 case Intrinsic::x86_avx_ptestnzc_256:
14595 case Intrinsic::x86_avx_vtestz_ps:
14596 case Intrinsic::x86_avx_vtestc_ps:
14597 case Intrinsic::x86_avx_vtestnzc_ps:
14598 case Intrinsic::x86_avx_vtestz_pd:
14599 case Intrinsic::x86_avx_vtestc_pd:
14600 case Intrinsic::x86_avx_vtestnzc_pd:
14601 case Intrinsic::x86_avx_vtestz_ps_256:
14602 case Intrinsic::x86_avx_vtestc_ps_256:
14603 case Intrinsic::x86_avx_vtestnzc_ps_256:
14604 case Intrinsic::x86_avx_vtestz_pd_256:
14605 case Intrinsic::x86_avx_vtestc_pd_256:
14606 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14607 bool IsTestPacked = false;
14610 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14611 case Intrinsic::x86_avx_vtestz_ps:
14612 case Intrinsic::x86_avx_vtestz_pd:
14613 case Intrinsic::x86_avx_vtestz_ps_256:
14614 case Intrinsic::x86_avx_vtestz_pd_256:
14615 IsTestPacked = true; // Fallthrough
14616 case Intrinsic::x86_sse41_ptestz:
14617 case Intrinsic::x86_avx_ptestz_256:
14619 X86CC = X86::COND_E;
14621 case Intrinsic::x86_avx_vtestc_ps:
14622 case Intrinsic::x86_avx_vtestc_pd:
14623 case Intrinsic::x86_avx_vtestc_ps_256:
14624 case Intrinsic::x86_avx_vtestc_pd_256:
14625 IsTestPacked = true; // Fallthrough
14626 case Intrinsic::x86_sse41_ptestc:
14627 case Intrinsic::x86_avx_ptestc_256:
14629 X86CC = X86::COND_B;
14631 case Intrinsic::x86_avx_vtestnzc_ps:
14632 case Intrinsic::x86_avx_vtestnzc_pd:
14633 case Intrinsic::x86_avx_vtestnzc_ps_256:
14634 case Intrinsic::x86_avx_vtestnzc_pd_256:
14635 IsTestPacked = true; // Fallthrough
14636 case Intrinsic::x86_sse41_ptestnzc:
14637 case Intrinsic::x86_avx_ptestnzc_256:
14639 X86CC = X86::COND_A;
14643 SDValue LHS = Op.getOperand(1);
14644 SDValue RHS = Op.getOperand(2);
14645 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14646 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14647 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14648 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14649 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14651 case Intrinsic::x86_avx512_kortestz_w:
14652 case Intrinsic::x86_avx512_kortestc_w: {
14653 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14654 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14655 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14656 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14657 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14658 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14659 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14662 case Intrinsic::x86_sse42_pcmpistria128:
14663 case Intrinsic::x86_sse42_pcmpestria128:
14664 case Intrinsic::x86_sse42_pcmpistric128:
14665 case Intrinsic::x86_sse42_pcmpestric128:
14666 case Intrinsic::x86_sse42_pcmpistrio128:
14667 case Intrinsic::x86_sse42_pcmpestrio128:
14668 case Intrinsic::x86_sse42_pcmpistris128:
14669 case Intrinsic::x86_sse42_pcmpestris128:
14670 case Intrinsic::x86_sse42_pcmpistriz128:
14671 case Intrinsic::x86_sse42_pcmpestriz128: {
14675 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14676 case Intrinsic::x86_sse42_pcmpistria128:
14677 Opcode = X86ISD::PCMPISTRI;
14678 X86CC = X86::COND_A;
14680 case Intrinsic::x86_sse42_pcmpestria128:
14681 Opcode = X86ISD::PCMPESTRI;
14682 X86CC = X86::COND_A;
14684 case Intrinsic::x86_sse42_pcmpistric128:
14685 Opcode = X86ISD::PCMPISTRI;
14686 X86CC = X86::COND_B;
14688 case Intrinsic::x86_sse42_pcmpestric128:
14689 Opcode = X86ISD::PCMPESTRI;
14690 X86CC = X86::COND_B;
14692 case Intrinsic::x86_sse42_pcmpistrio128:
14693 Opcode = X86ISD::PCMPISTRI;
14694 X86CC = X86::COND_O;
14696 case Intrinsic::x86_sse42_pcmpestrio128:
14697 Opcode = X86ISD::PCMPESTRI;
14698 X86CC = X86::COND_O;
14700 case Intrinsic::x86_sse42_pcmpistris128:
14701 Opcode = X86ISD::PCMPISTRI;
14702 X86CC = X86::COND_S;
14704 case Intrinsic::x86_sse42_pcmpestris128:
14705 Opcode = X86ISD::PCMPESTRI;
14706 X86CC = X86::COND_S;
14708 case Intrinsic::x86_sse42_pcmpistriz128:
14709 Opcode = X86ISD::PCMPISTRI;
14710 X86CC = X86::COND_E;
14712 case Intrinsic::x86_sse42_pcmpestriz128:
14713 Opcode = X86ISD::PCMPESTRI;
14714 X86CC = X86::COND_E;
14717 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14718 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14719 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14720 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14721 DAG.getConstant(X86CC, MVT::i8),
14722 SDValue(PCMP.getNode(), 1));
14723 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14726 case Intrinsic::x86_sse42_pcmpistri128:
14727 case Intrinsic::x86_sse42_pcmpestri128: {
14729 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14730 Opcode = X86ISD::PCMPISTRI;
14732 Opcode = X86ISD::PCMPESTRI;
14734 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14735 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14736 return DAG.getNode(Opcode, dl, VTs, NewOps);
14741 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14742 SDValue Src, SDValue Mask, SDValue Base,
14743 SDValue Index, SDValue ScaleOp, SDValue Chain,
14744 const X86Subtarget * Subtarget) {
14746 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14747 assert(C && "Invalid scale type");
14748 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14749 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14750 Index.getSimpleValueType().getVectorNumElements());
14752 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14754 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14756 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14757 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14758 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14759 SDValue Segment = DAG.getRegister(0, MVT::i32);
14760 if (Src.getOpcode() == ISD::UNDEF)
14761 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14762 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14763 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14764 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14765 return DAG.getMergeValues(RetOps, dl);
14768 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14769 SDValue Src, SDValue Mask, SDValue Base,
14770 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14772 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14773 assert(C && "Invalid scale type");
14774 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14775 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14776 SDValue Segment = DAG.getRegister(0, MVT::i32);
14777 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14778 Index.getSimpleValueType().getVectorNumElements());
14780 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14782 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14784 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14785 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14786 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14787 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14788 return SDValue(Res, 1);
14791 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14792 SDValue Mask, SDValue Base, SDValue Index,
14793 SDValue ScaleOp, SDValue Chain) {
14795 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14796 assert(C && "Invalid scale type");
14797 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14798 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14799 SDValue Segment = DAG.getRegister(0, MVT::i32);
14801 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14803 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14805 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14807 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14808 //SDVTList VTs = DAG.getVTList(MVT::Other);
14809 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14810 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14811 return SDValue(Res, 0);
14814 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14815 // read performance monitor counters (x86_rdpmc).
14816 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14817 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14818 SmallVectorImpl<SDValue> &Results) {
14819 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14820 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14823 // The ECX register is used to select the index of the performance counter
14825 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14827 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14829 // Reads the content of a 64-bit performance counter and returns it in the
14830 // registers EDX:EAX.
14831 if (Subtarget->is64Bit()) {
14832 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14833 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14836 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14837 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14840 Chain = HI.getValue(1);
14842 if (Subtarget->is64Bit()) {
14843 // The EAX register is loaded with the low-order 32 bits. The EDX register
14844 // is loaded with the supported high-order bits of the counter.
14845 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14846 DAG.getConstant(32, MVT::i8));
14847 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14848 Results.push_back(Chain);
14852 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14853 SDValue Ops[] = { LO, HI };
14854 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14855 Results.push_back(Pair);
14856 Results.push_back(Chain);
14859 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14860 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14861 // also used to custom lower READCYCLECOUNTER nodes.
14862 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14863 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14864 SmallVectorImpl<SDValue> &Results) {
14865 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14866 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14869 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14870 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14871 // and the EAX register is loaded with the low-order 32 bits.
14872 if (Subtarget->is64Bit()) {
14873 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14874 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14877 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14878 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14881 SDValue Chain = HI.getValue(1);
14883 if (Opcode == X86ISD::RDTSCP_DAG) {
14884 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14886 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14887 // the ECX register. Add 'ecx' explicitly to the chain.
14888 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14890 // Explicitly store the content of ECX at the location passed in input
14891 // to the 'rdtscp' intrinsic.
14892 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14893 MachinePointerInfo(), false, false, 0);
14896 if (Subtarget->is64Bit()) {
14897 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14898 // the EAX register is loaded with the low-order 32 bits.
14899 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14900 DAG.getConstant(32, MVT::i8));
14901 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14902 Results.push_back(Chain);
14906 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14907 SDValue Ops[] = { LO, HI };
14908 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14909 Results.push_back(Pair);
14910 Results.push_back(Chain);
14913 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14914 SelectionDAG &DAG) {
14915 SmallVector<SDValue, 2> Results;
14917 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14919 return DAG.getMergeValues(Results, DL);
14923 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14924 SelectionDAG &DAG) {
14925 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14927 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
14932 switch(IntrData->Type) {
14934 llvm_unreachable("Unknown Intrinsic Type");
14938 // Emit the node with the right value type.
14939 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14940 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
14942 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14943 // Otherwise return the value from Rand, which is always 0, casted to i32.
14944 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14945 DAG.getConstant(1, Op->getValueType(1)),
14946 DAG.getConstant(X86::COND_B, MVT::i32),
14947 SDValue(Result.getNode(), 1) };
14948 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14949 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14952 // Return { result, isValid, chain }.
14953 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14954 SDValue(Result.getNode(), 2));
14957 //gather(v1, mask, index, base, scale);
14958 SDValue Chain = Op.getOperand(0);
14959 SDValue Src = Op.getOperand(2);
14960 SDValue Base = Op.getOperand(3);
14961 SDValue Index = Op.getOperand(4);
14962 SDValue Mask = Op.getOperand(5);
14963 SDValue Scale = Op.getOperand(6);
14964 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14968 //scatter(base, mask, index, v1, scale);
14969 SDValue Chain = Op.getOperand(0);
14970 SDValue Base = Op.getOperand(2);
14971 SDValue Mask = Op.getOperand(3);
14972 SDValue Index = Op.getOperand(4);
14973 SDValue Src = Op.getOperand(5);
14974 SDValue Scale = Op.getOperand(6);
14975 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14978 SDValue Hint = Op.getOperand(6);
14980 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14981 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14982 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14983 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
14984 SDValue Chain = Op.getOperand(0);
14985 SDValue Mask = Op.getOperand(2);
14986 SDValue Index = Op.getOperand(3);
14987 SDValue Base = Op.getOperand(4);
14988 SDValue Scale = Op.getOperand(5);
14989 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14991 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14993 SmallVector<SDValue, 2> Results;
14994 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
14995 return DAG.getMergeValues(Results, dl);
14997 // Read Performance Monitoring Counters.
14999 SmallVector<SDValue, 2> Results;
15000 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15001 return DAG.getMergeValues(Results, dl);
15003 // XTEST intrinsics.
15005 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15006 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15007 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15008 DAG.getConstant(X86::COND_NE, MVT::i8),
15010 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15011 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15012 Ret, SDValue(InTrans.getNode(), 1));
15016 SmallVector<SDValue, 2> Results;
15017 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15018 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15019 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15020 DAG.getConstant(-1, MVT::i8));
15021 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15022 Op.getOperand(4), GenCF.getValue(1));
15023 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15024 Op.getOperand(5), MachinePointerInfo(),
15026 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15027 DAG.getConstant(X86::COND_B, MVT::i8),
15029 Results.push_back(SetCC);
15030 Results.push_back(Store);
15031 return DAG.getMergeValues(Results, dl);
15033 case COMPRESS_TO_MEM: {
15035 SDValue Mask = Op.getOperand(4);
15036 SDValue DataToCompress = Op.getOperand(3);
15037 SDValue Addr = Op.getOperand(2);
15038 SDValue Chain = Op.getOperand(0);
15040 if (isAllOnes(Mask)) // return just a store
15041 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15042 MachinePointerInfo(), false, false, 0);
15044 EVT VT = DataToCompress.getValueType();
15045 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15046 VT.getVectorNumElements());
15047 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15048 Mask.getValueType().getSizeInBits());
15049 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15050 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15051 DAG.getIntPtrConstant(0));
15053 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15054 DataToCompress, DAG.getUNDEF(VT));
15055 return DAG.getStore(Chain, dl, Compressed, Addr,
15056 MachinePointerInfo(), false, false, 0);
15058 case EXPAND_FROM_MEM: {
15060 SDValue Mask = Op.getOperand(4);
15061 SDValue PathThru = Op.getOperand(3);
15062 SDValue Addr = Op.getOperand(2);
15063 SDValue Chain = Op.getOperand(0);
15064 EVT VT = Op.getValueType();
15066 if (isAllOnes(Mask)) // return just a load
15067 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15069 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15070 VT.getVectorNumElements());
15071 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15072 Mask.getValueType().getSizeInBits());
15073 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15074 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15075 DAG.getIntPtrConstant(0));
15077 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15078 false, false, false, 0);
15080 SDValue Results[] = {
15081 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15083 return DAG.getMergeValues(Results, dl);
15088 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15089 SelectionDAG &DAG) const {
15090 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15091 MFI->setReturnAddressIsTaken(true);
15093 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15096 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15098 EVT PtrVT = getPointerTy();
15101 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15102 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15103 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15104 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15105 DAG.getNode(ISD::ADD, dl, PtrVT,
15106 FrameAddr, Offset),
15107 MachinePointerInfo(), false, false, false, 0);
15110 // Just load the return address.
15111 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15112 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15113 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15116 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15117 MachineFunction &MF = DAG.getMachineFunction();
15118 MachineFrameInfo *MFI = MF.getFrameInfo();
15119 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15120 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15121 EVT VT = Op.getValueType();
15123 MFI->setFrameAddressIsTaken(true);
15125 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15126 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15127 // is not possible to crawl up the stack without looking at the unwind codes
15129 int FrameAddrIndex = FuncInfo->getFAIndex();
15130 if (!FrameAddrIndex) {
15131 // Set up a frame object for the return address.
15132 unsigned SlotSize = RegInfo->getSlotSize();
15133 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15134 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15135 FuncInfo->setFAIndex(FrameAddrIndex);
15137 return DAG.getFrameIndex(FrameAddrIndex, VT);
15140 unsigned FrameReg =
15141 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15142 SDLoc dl(Op); // FIXME probably not meaningful
15143 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15144 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15145 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15146 "Invalid Frame Register!");
15147 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15149 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15150 MachinePointerInfo(),
15151 false, false, false, 0);
15155 // FIXME? Maybe this could be a TableGen attribute on some registers and
15156 // this table could be generated automatically from RegInfo.
15157 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15159 unsigned Reg = StringSwitch<unsigned>(RegName)
15160 .Case("esp", X86::ESP)
15161 .Case("rsp", X86::RSP)
15165 report_fatal_error("Invalid register name global variable");
15168 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15169 SelectionDAG &DAG) const {
15170 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15171 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15174 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15175 SDValue Chain = Op.getOperand(0);
15176 SDValue Offset = Op.getOperand(1);
15177 SDValue Handler = Op.getOperand(2);
15180 EVT PtrVT = getPointerTy();
15181 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15182 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15183 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15184 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15185 "Invalid Frame Register!");
15186 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15187 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15189 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15190 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15191 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15192 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15194 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15196 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15197 DAG.getRegister(StoreAddrReg, PtrVT));
15200 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15201 SelectionDAG &DAG) const {
15203 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15204 DAG.getVTList(MVT::i32, MVT::Other),
15205 Op.getOperand(0), Op.getOperand(1));
15208 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15209 SelectionDAG &DAG) const {
15211 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15212 Op.getOperand(0), Op.getOperand(1));
15215 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15216 return Op.getOperand(0);
15219 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15220 SelectionDAG &DAG) const {
15221 SDValue Root = Op.getOperand(0);
15222 SDValue Trmp = Op.getOperand(1); // trampoline
15223 SDValue FPtr = Op.getOperand(2); // nested function
15224 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15227 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15228 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15230 if (Subtarget->is64Bit()) {
15231 SDValue OutChains[6];
15233 // Large code-model.
15234 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15235 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15237 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15238 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15240 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15242 // Load the pointer to the nested function into R11.
15243 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15244 SDValue Addr = Trmp;
15245 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15246 Addr, MachinePointerInfo(TrmpAddr),
15249 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15250 DAG.getConstant(2, MVT::i64));
15251 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15252 MachinePointerInfo(TrmpAddr, 2),
15255 // Load the 'nest' parameter value into R10.
15256 // R10 is specified in X86CallingConv.td
15257 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15258 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15259 DAG.getConstant(10, MVT::i64));
15260 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15261 Addr, MachinePointerInfo(TrmpAddr, 10),
15264 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15265 DAG.getConstant(12, MVT::i64));
15266 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15267 MachinePointerInfo(TrmpAddr, 12),
15270 // Jump to the nested function.
15271 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15272 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15273 DAG.getConstant(20, MVT::i64));
15274 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15275 Addr, MachinePointerInfo(TrmpAddr, 20),
15278 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15279 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15280 DAG.getConstant(22, MVT::i64));
15281 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15282 MachinePointerInfo(TrmpAddr, 22),
15285 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15287 const Function *Func =
15288 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15289 CallingConv::ID CC = Func->getCallingConv();
15294 llvm_unreachable("Unsupported calling convention");
15295 case CallingConv::C:
15296 case CallingConv::X86_StdCall: {
15297 // Pass 'nest' parameter in ECX.
15298 // Must be kept in sync with X86CallingConv.td
15299 NestReg = X86::ECX;
15301 // Check that ECX wasn't needed by an 'inreg' parameter.
15302 FunctionType *FTy = Func->getFunctionType();
15303 const AttributeSet &Attrs = Func->getAttributes();
15305 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15306 unsigned InRegCount = 0;
15309 for (FunctionType::param_iterator I = FTy->param_begin(),
15310 E = FTy->param_end(); I != E; ++I, ++Idx)
15311 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15312 // FIXME: should only count parameters that are lowered to integers.
15313 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15315 if (InRegCount > 2) {
15316 report_fatal_error("Nest register in use - reduce number of inreg"
15322 case CallingConv::X86_FastCall:
15323 case CallingConv::X86_ThisCall:
15324 case CallingConv::Fast:
15325 // Pass 'nest' parameter in EAX.
15326 // Must be kept in sync with X86CallingConv.td
15327 NestReg = X86::EAX;
15331 SDValue OutChains[4];
15332 SDValue Addr, Disp;
15334 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15335 DAG.getConstant(10, MVT::i32));
15336 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15338 // This is storing the opcode for MOV32ri.
15339 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15340 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15341 OutChains[0] = DAG.getStore(Root, dl,
15342 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15343 Trmp, MachinePointerInfo(TrmpAddr),
15346 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15347 DAG.getConstant(1, MVT::i32));
15348 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15349 MachinePointerInfo(TrmpAddr, 1),
15352 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15353 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15354 DAG.getConstant(5, MVT::i32));
15355 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15356 MachinePointerInfo(TrmpAddr, 5),
15359 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15360 DAG.getConstant(6, MVT::i32));
15361 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15362 MachinePointerInfo(TrmpAddr, 6),
15365 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15369 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15370 SelectionDAG &DAG) const {
15372 The rounding mode is in bits 11:10 of FPSR, and has the following
15374 00 Round to nearest
15379 FLT_ROUNDS, on the other hand, expects the following:
15386 To perform the conversion, we do:
15387 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15390 MachineFunction &MF = DAG.getMachineFunction();
15391 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15392 unsigned StackAlignment = TFI.getStackAlignment();
15393 MVT VT = Op.getSimpleValueType();
15396 // Save FP Control Word to stack slot
15397 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15398 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15400 MachineMemOperand *MMO =
15401 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15402 MachineMemOperand::MOStore, 2, 2);
15404 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15405 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15406 DAG.getVTList(MVT::Other),
15407 Ops, MVT::i16, MMO);
15409 // Load FP Control Word from stack slot
15410 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15411 MachinePointerInfo(), false, false, false, 0);
15413 // Transform as necessary
15415 DAG.getNode(ISD::SRL, DL, MVT::i16,
15416 DAG.getNode(ISD::AND, DL, MVT::i16,
15417 CWD, DAG.getConstant(0x800, MVT::i16)),
15418 DAG.getConstant(11, MVT::i8));
15420 DAG.getNode(ISD::SRL, DL, MVT::i16,
15421 DAG.getNode(ISD::AND, DL, MVT::i16,
15422 CWD, DAG.getConstant(0x400, MVT::i16)),
15423 DAG.getConstant(9, MVT::i8));
15426 DAG.getNode(ISD::AND, DL, MVT::i16,
15427 DAG.getNode(ISD::ADD, DL, MVT::i16,
15428 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15429 DAG.getConstant(1, MVT::i16)),
15430 DAG.getConstant(3, MVT::i16));
15432 return DAG.getNode((VT.getSizeInBits() < 16 ?
15433 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15436 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15437 MVT VT = Op.getSimpleValueType();
15439 unsigned NumBits = VT.getSizeInBits();
15442 Op = Op.getOperand(0);
15443 if (VT == MVT::i8) {
15444 // Zero extend to i32 since there is not an i8 bsr.
15446 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15449 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15450 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15451 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15453 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15456 DAG.getConstant(NumBits+NumBits-1, OpVT),
15457 DAG.getConstant(X86::COND_E, MVT::i8),
15460 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15462 // Finally xor with NumBits-1.
15463 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15466 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15470 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15471 MVT VT = Op.getSimpleValueType();
15473 unsigned NumBits = VT.getSizeInBits();
15476 Op = Op.getOperand(0);
15477 if (VT == MVT::i8) {
15478 // Zero extend to i32 since there is not an i8 bsr.
15480 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15483 // Issue a bsr (scan bits in reverse).
15484 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15485 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15487 // And xor with NumBits-1.
15488 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15491 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15495 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15496 MVT VT = Op.getSimpleValueType();
15497 unsigned NumBits = VT.getSizeInBits();
15499 Op = Op.getOperand(0);
15501 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15502 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15503 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15505 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15508 DAG.getConstant(NumBits, VT),
15509 DAG.getConstant(X86::COND_E, MVT::i8),
15512 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15515 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15516 // ones, and then concatenate the result back.
15517 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15518 MVT VT = Op.getSimpleValueType();
15520 assert(VT.is256BitVector() && VT.isInteger() &&
15521 "Unsupported value type for operation");
15523 unsigned NumElems = VT.getVectorNumElements();
15526 // Extract the LHS vectors
15527 SDValue LHS = Op.getOperand(0);
15528 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15529 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15531 // Extract the RHS vectors
15532 SDValue RHS = Op.getOperand(1);
15533 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15534 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15536 MVT EltVT = VT.getVectorElementType();
15537 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15539 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15540 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15541 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15544 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15545 assert(Op.getSimpleValueType().is256BitVector() &&
15546 Op.getSimpleValueType().isInteger() &&
15547 "Only handle AVX 256-bit vector integer operation");
15548 return Lower256IntArith(Op, DAG);
15551 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15552 assert(Op.getSimpleValueType().is256BitVector() &&
15553 Op.getSimpleValueType().isInteger() &&
15554 "Only handle AVX 256-bit vector integer operation");
15555 return Lower256IntArith(Op, DAG);
15558 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15559 SelectionDAG &DAG) {
15561 MVT VT = Op.getSimpleValueType();
15563 // Decompose 256-bit ops into smaller 128-bit ops.
15564 if (VT.is256BitVector() && !Subtarget->hasInt256())
15565 return Lower256IntArith(Op, DAG);
15567 SDValue A = Op.getOperand(0);
15568 SDValue B = Op.getOperand(1);
15570 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15571 if (VT == MVT::v4i32) {
15572 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15573 "Should not custom lower when pmuldq is available!");
15575 // Extract the odd parts.
15576 static const int UnpackMask[] = { 1, -1, 3, -1 };
15577 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15578 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15580 // Multiply the even parts.
15581 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15582 // Now multiply odd parts.
15583 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15585 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15586 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15588 // Merge the two vectors back together with a shuffle. This expands into 2
15590 static const int ShufMask[] = { 0, 4, 2, 6 };
15591 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15594 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15595 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15597 // Ahi = psrlqi(a, 32);
15598 // Bhi = psrlqi(b, 32);
15600 // AloBlo = pmuludq(a, b);
15601 // AloBhi = pmuludq(a, Bhi);
15602 // AhiBlo = pmuludq(Ahi, b);
15604 // AloBhi = psllqi(AloBhi, 32);
15605 // AhiBlo = psllqi(AhiBlo, 32);
15606 // return AloBlo + AloBhi + AhiBlo;
15608 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15609 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15611 // Bit cast to 32-bit vectors for MULUDQ
15612 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15613 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15614 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15615 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15616 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15617 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15619 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15620 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15621 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15623 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15624 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15626 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15627 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15630 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15631 assert(Subtarget->isTargetWin64() && "Unexpected target");
15632 EVT VT = Op.getValueType();
15633 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15634 "Unexpected return type for lowering");
15638 switch (Op->getOpcode()) {
15639 default: llvm_unreachable("Unexpected request for libcall!");
15640 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15641 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15642 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15643 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15644 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15645 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15649 SDValue InChain = DAG.getEntryNode();
15651 TargetLowering::ArgListTy Args;
15652 TargetLowering::ArgListEntry Entry;
15653 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15654 EVT ArgVT = Op->getOperand(i).getValueType();
15655 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15656 "Unexpected argument type for lowering");
15657 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15658 Entry.Node = StackPtr;
15659 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15661 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15662 Entry.Ty = PointerType::get(ArgTy,0);
15663 Entry.isSExt = false;
15664 Entry.isZExt = false;
15665 Args.push_back(Entry);
15668 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15671 TargetLowering::CallLoweringInfo CLI(DAG);
15672 CLI.setDebugLoc(dl).setChain(InChain)
15673 .setCallee(getLibcallCallingConv(LC),
15674 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15675 Callee, std::move(Args), 0)
15676 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15678 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15679 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15682 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15683 SelectionDAG &DAG) {
15684 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15685 EVT VT = Op0.getValueType();
15688 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15689 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15691 // PMULxD operations multiply each even value (starting at 0) of LHS with
15692 // the related value of RHS and produce a widen result.
15693 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15694 // => <2 x i64> <ae|cg>
15696 // In other word, to have all the results, we need to perform two PMULxD:
15697 // 1. one with the even values.
15698 // 2. one with the odd values.
15699 // To achieve #2, with need to place the odd values at an even position.
15701 // Place the odd value at an even position (basically, shift all values 1
15702 // step to the left):
15703 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15704 // <a|b|c|d> => <b|undef|d|undef>
15705 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15706 // <e|f|g|h> => <f|undef|h|undef>
15707 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15709 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15711 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15712 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15714 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15715 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15716 // => <2 x i64> <ae|cg>
15717 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15718 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15719 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15720 // => <2 x i64> <bf|dh>
15721 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15722 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15724 // Shuffle it back into the right order.
15725 SDValue Highs, Lows;
15726 if (VT == MVT::v8i32) {
15727 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15728 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15729 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15730 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15732 const int HighMask[] = {1, 5, 3, 7};
15733 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15734 const int LowMask[] = {0, 4, 2, 6};
15735 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15738 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15739 // unsigned multiply.
15740 if (IsSigned && !Subtarget->hasSSE41()) {
15742 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15743 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15744 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15745 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15746 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15748 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15749 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15752 // The first result of MUL_LOHI is actually the low value, followed by the
15754 SDValue Ops[] = {Lows, Highs};
15755 return DAG.getMergeValues(Ops, dl);
15758 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15759 const X86Subtarget *Subtarget) {
15760 MVT VT = Op.getSimpleValueType();
15762 SDValue R = Op.getOperand(0);
15763 SDValue Amt = Op.getOperand(1);
15765 // Optimize shl/srl/sra with constant shift amount.
15766 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15767 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15768 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15770 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15771 (Subtarget->hasInt256() &&
15772 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15773 (Subtarget->hasAVX512() &&
15774 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15775 if (Op.getOpcode() == ISD::SHL)
15776 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15778 if (Op.getOpcode() == ISD::SRL)
15779 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15781 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15782 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15786 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15787 unsigned NumElts = VT.getVectorNumElements();
15788 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15790 if (Op.getOpcode() == ISD::SHL) {
15791 // Make a large shift.
15792 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15794 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15795 // Zero out the rightmost bits.
15796 SmallVector<SDValue, 32> V(
15797 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15798 return DAG.getNode(ISD::AND, dl, VT, SHL,
15799 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15801 if (Op.getOpcode() == ISD::SRL) {
15802 // Make a large shift.
15803 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15805 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15806 // Zero out the leftmost bits.
15807 SmallVector<SDValue, 32> V(
15808 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15809 return DAG.getNode(ISD::AND, dl, VT, SRL,
15810 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15812 if (Op.getOpcode() == ISD::SRA) {
15813 if (ShiftAmt == 7) {
15814 // R s>> 7 === R s< 0
15815 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15816 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15819 // R s>> a === ((R u>> a) ^ m) - m
15820 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15821 SmallVector<SDValue, 32> V(NumElts,
15822 DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15823 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15824 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15825 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15828 llvm_unreachable("Unknown shift opcode.");
15833 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15834 if (!Subtarget->is64Bit() &&
15835 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15836 Amt.getOpcode() == ISD::BITCAST &&
15837 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15838 Amt = Amt.getOperand(0);
15839 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15840 VT.getVectorNumElements();
15841 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15842 uint64_t ShiftAmt = 0;
15843 for (unsigned i = 0; i != Ratio; ++i) {
15844 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15848 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15850 // Check remaining shift amounts.
15851 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15852 uint64_t ShAmt = 0;
15853 for (unsigned j = 0; j != Ratio; ++j) {
15854 ConstantSDNode *C =
15855 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15859 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15861 if (ShAmt != ShiftAmt)
15864 switch (Op.getOpcode()) {
15866 llvm_unreachable("Unknown shift opcode!");
15868 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15871 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15874 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15882 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15883 const X86Subtarget* Subtarget) {
15884 MVT VT = Op.getSimpleValueType();
15886 SDValue R = Op.getOperand(0);
15887 SDValue Amt = Op.getOperand(1);
15889 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15890 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15891 (Subtarget->hasInt256() &&
15892 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15893 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15894 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15896 EVT EltVT = VT.getVectorElementType();
15898 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
15899 // Check if this build_vector node is doing a splat.
15900 // If so, then set BaseShAmt equal to the splat value.
15901 BaseShAmt = BV->getSplatValue();
15902 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
15903 BaseShAmt = SDValue();
15905 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15906 Amt = Amt.getOperand(0);
15908 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
15909 if (SVN && SVN->isSplat()) {
15910 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
15911 SDValue InVec = Amt.getOperand(0);
15912 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15913 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
15914 "Unexpected shuffle index found!");
15915 BaseShAmt = InVec.getOperand(SplatIdx);
15916 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15917 if (ConstantSDNode *C =
15918 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15919 if (C->getZExtValue() == SplatIdx)
15920 BaseShAmt = InVec.getOperand(1);
15925 // Avoid introducing an extract element from a shuffle.
15926 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
15927 DAG.getIntPtrConstant(SplatIdx));
15931 if (BaseShAmt.getNode()) {
15932 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
15933 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
15934 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
15935 else if (EltVT.bitsLT(MVT::i32))
15936 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15938 switch (Op.getOpcode()) {
15940 llvm_unreachable("Unknown shift opcode!");
15942 switch (VT.SimpleTy) {
15943 default: return SDValue();
15952 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15955 switch (VT.SimpleTy) {
15956 default: return SDValue();
15963 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15966 switch (VT.SimpleTy) {
15967 default: return SDValue();
15976 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15982 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15983 if (!Subtarget->is64Bit() &&
15984 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15985 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15986 Amt.getOpcode() == ISD::BITCAST &&
15987 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15988 Amt = Amt.getOperand(0);
15989 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15990 VT.getVectorNumElements();
15991 std::vector<SDValue> Vals(Ratio);
15992 for (unsigned i = 0; i != Ratio; ++i)
15993 Vals[i] = Amt.getOperand(i);
15994 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15995 for (unsigned j = 0; j != Ratio; ++j)
15996 if (Vals[j] != Amt.getOperand(i + j))
15999 switch (Op.getOpcode()) {
16001 llvm_unreachable("Unknown shift opcode!");
16003 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16005 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16007 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16014 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16015 SelectionDAG &DAG) {
16016 MVT VT = Op.getSimpleValueType();
16018 SDValue R = Op.getOperand(0);
16019 SDValue Amt = Op.getOperand(1);
16022 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16023 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16025 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16029 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16033 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16035 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16036 if (Subtarget->hasInt256()) {
16037 if (Op.getOpcode() == ISD::SRL &&
16038 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16039 VT == MVT::v4i64 || VT == MVT::v8i32))
16041 if (Op.getOpcode() == ISD::SHL &&
16042 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16043 VT == MVT::v4i64 || VT == MVT::v8i32))
16045 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16049 // If possible, lower this packed shift into a vector multiply instead of
16050 // expanding it into a sequence of scalar shifts.
16051 // Do this only if the vector shift count is a constant build_vector.
16052 if (Op.getOpcode() == ISD::SHL &&
16053 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16054 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16055 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16056 SmallVector<SDValue, 8> Elts;
16057 EVT SVT = VT.getScalarType();
16058 unsigned SVTBits = SVT.getSizeInBits();
16059 const APInt &One = APInt(SVTBits, 1);
16060 unsigned NumElems = VT.getVectorNumElements();
16062 for (unsigned i=0; i !=NumElems; ++i) {
16063 SDValue Op = Amt->getOperand(i);
16064 if (Op->getOpcode() == ISD::UNDEF) {
16065 Elts.push_back(Op);
16069 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16070 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16071 uint64_t ShAmt = C.getZExtValue();
16072 if (ShAmt >= SVTBits) {
16073 Elts.push_back(DAG.getUNDEF(SVT));
16076 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16078 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16079 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16082 // Lower SHL with variable shift amount.
16083 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16084 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16086 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16087 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16088 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16089 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16092 // If possible, lower this shift as a sequence of two shifts by
16093 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16095 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16097 // Could be rewritten as:
16098 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16100 // The advantage is that the two shifts from the example would be
16101 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16102 // the vector shift into four scalar shifts plus four pairs of vector
16104 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16105 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16106 unsigned TargetOpcode = X86ISD::MOVSS;
16107 bool CanBeSimplified;
16108 // The splat value for the first packed shift (the 'X' from the example).
16109 SDValue Amt1 = Amt->getOperand(0);
16110 // The splat value for the second packed shift (the 'Y' from the example).
16111 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16112 Amt->getOperand(2);
16114 // See if it is possible to replace this node with a sequence of
16115 // two shifts followed by a MOVSS/MOVSD
16116 if (VT == MVT::v4i32) {
16117 // Check if it is legal to use a MOVSS.
16118 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16119 Amt2 == Amt->getOperand(3);
16120 if (!CanBeSimplified) {
16121 // Otherwise, check if we can still simplify this node using a MOVSD.
16122 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16123 Amt->getOperand(2) == Amt->getOperand(3);
16124 TargetOpcode = X86ISD::MOVSD;
16125 Amt2 = Amt->getOperand(2);
16128 // Do similar checks for the case where the machine value type
16130 CanBeSimplified = Amt1 == Amt->getOperand(1);
16131 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16132 CanBeSimplified = Amt2 == Amt->getOperand(i);
16134 if (!CanBeSimplified) {
16135 TargetOpcode = X86ISD::MOVSD;
16136 CanBeSimplified = true;
16137 Amt2 = Amt->getOperand(4);
16138 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16139 CanBeSimplified = Amt1 == Amt->getOperand(i);
16140 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16141 CanBeSimplified = Amt2 == Amt->getOperand(j);
16145 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16146 isa<ConstantSDNode>(Amt2)) {
16147 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16148 EVT CastVT = MVT::v4i32;
16150 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16151 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16153 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16154 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16155 if (TargetOpcode == X86ISD::MOVSD)
16156 CastVT = MVT::v2i64;
16157 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16158 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16159 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16161 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16165 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16166 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16169 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16170 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16172 // Turn 'a' into a mask suitable for VSELECT
16173 SDValue VSelM = DAG.getConstant(0x80, VT);
16174 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16175 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16177 SDValue CM1 = DAG.getConstant(0x0f, VT);
16178 SDValue CM2 = DAG.getConstant(0x3f, VT);
16180 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16181 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16182 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16183 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16184 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16187 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16188 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16189 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16191 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16192 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16193 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16194 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16195 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16198 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16199 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16200 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16202 // return VSELECT(r, r+r, a);
16203 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16204 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16208 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16209 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16210 // solution better.
16211 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16212 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16214 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16215 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16216 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16217 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16218 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16221 // Decompose 256-bit shifts into smaller 128-bit shifts.
16222 if (VT.is256BitVector()) {
16223 unsigned NumElems = VT.getVectorNumElements();
16224 MVT EltVT = VT.getVectorElementType();
16225 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16227 // Extract the two vectors
16228 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16229 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16231 // Recreate the shift amount vectors
16232 SDValue Amt1, Amt2;
16233 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16234 // Constant shift amount
16235 SmallVector<SDValue, 4> Amt1Csts;
16236 SmallVector<SDValue, 4> Amt2Csts;
16237 for (unsigned i = 0; i != NumElems/2; ++i)
16238 Amt1Csts.push_back(Amt->getOperand(i));
16239 for (unsigned i = NumElems/2; i != NumElems; ++i)
16240 Amt2Csts.push_back(Amt->getOperand(i));
16242 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16243 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16245 // Variable shift amount
16246 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16247 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16250 // Issue new vector shifts for the smaller types
16251 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16252 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16254 // Concatenate the result back
16255 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16261 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16262 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16263 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16264 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16265 // has only one use.
16266 SDNode *N = Op.getNode();
16267 SDValue LHS = N->getOperand(0);
16268 SDValue RHS = N->getOperand(1);
16269 unsigned BaseOp = 0;
16272 switch (Op.getOpcode()) {
16273 default: llvm_unreachable("Unknown ovf instruction!");
16275 // A subtract of one will be selected as a INC. Note that INC doesn't
16276 // set CF, so we can't do this for UADDO.
16277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16279 BaseOp = X86ISD::INC;
16280 Cond = X86::COND_O;
16283 BaseOp = X86ISD::ADD;
16284 Cond = X86::COND_O;
16287 BaseOp = X86ISD::ADD;
16288 Cond = X86::COND_B;
16291 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16292 // set CF, so we can't do this for USUBO.
16293 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16295 BaseOp = X86ISD::DEC;
16296 Cond = X86::COND_O;
16299 BaseOp = X86ISD::SUB;
16300 Cond = X86::COND_O;
16303 BaseOp = X86ISD::SUB;
16304 Cond = X86::COND_B;
16307 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16308 Cond = X86::COND_O;
16310 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16311 if (N->getValueType(0) == MVT::i8) {
16312 BaseOp = X86ISD::UMUL8;
16313 Cond = X86::COND_O;
16316 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16318 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16321 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16322 DAG.getConstant(X86::COND_O, MVT::i32),
16323 SDValue(Sum.getNode(), 2));
16325 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16329 // Also sets EFLAGS.
16330 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16331 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16334 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16335 DAG.getConstant(Cond, MVT::i32),
16336 SDValue(Sum.getNode(), 1));
16338 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16341 // Sign extension of the low part of vector elements. This may be used either
16342 // when sign extend instructions are not available or if the vector element
16343 // sizes already match the sign-extended size. If the vector elements are in
16344 // their pre-extended size and sign extend instructions are available, that will
16345 // be handled by LowerSIGN_EXTEND.
16346 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16347 SelectionDAG &DAG) const {
16349 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16350 MVT VT = Op.getSimpleValueType();
16352 if (!Subtarget->hasSSE2() || !VT.isVector())
16355 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16356 ExtraVT.getScalarType().getSizeInBits();
16358 switch (VT.SimpleTy) {
16359 default: return SDValue();
16362 if (!Subtarget->hasFp256())
16364 if (!Subtarget->hasInt256()) {
16365 // needs to be split
16366 unsigned NumElems = VT.getVectorNumElements();
16368 // Extract the LHS vectors
16369 SDValue LHS = Op.getOperand(0);
16370 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16371 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16373 MVT EltVT = VT.getVectorElementType();
16374 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16376 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16377 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16378 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16380 SDValue Extra = DAG.getValueType(ExtraVT);
16382 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16383 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16385 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16390 SDValue Op0 = Op.getOperand(0);
16392 // This is a sign extension of some low part of vector elements without
16393 // changing the size of the vector elements themselves:
16394 // Shift-Left + Shift-Right-Algebraic.
16395 SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16397 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16403 /// Returns true if the operand type is exactly twice the native width, and
16404 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16405 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16406 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16407 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16408 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16411 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16412 else if (OpWidth == 128)
16413 return Subtarget->hasCmpxchg16b();
16418 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16419 return needsCmpXchgNb(SI->getValueOperand()->getType());
16422 // Note: this turns large loads into lock cmpxchg8b/16b.
16423 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16424 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16425 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16426 return needsCmpXchgNb(PTy->getElementType());
16429 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16430 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16431 const Type *MemType = AI->getType();
16433 // If the operand is too big, we must see if cmpxchg8/16b is available
16434 // and default to library calls otherwise.
16435 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16436 return needsCmpXchgNb(MemType);
16438 AtomicRMWInst::BinOp Op = AI->getOperation();
16441 llvm_unreachable("Unknown atomic operation");
16442 case AtomicRMWInst::Xchg:
16443 case AtomicRMWInst::Add:
16444 case AtomicRMWInst::Sub:
16445 // It's better to use xadd, xsub or xchg for these in all cases.
16447 case AtomicRMWInst::Or:
16448 case AtomicRMWInst::And:
16449 case AtomicRMWInst::Xor:
16450 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16451 // prefix to a normal instruction for these operations.
16452 return !AI->use_empty();
16453 case AtomicRMWInst::Nand:
16454 case AtomicRMWInst::Max:
16455 case AtomicRMWInst::Min:
16456 case AtomicRMWInst::UMax:
16457 case AtomicRMWInst::UMin:
16458 // These always require a non-trivial set of data operations on x86. We must
16459 // use a cmpxchg loop.
16464 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16465 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16466 // no-sse2). There isn't any reason to disable it if the target processor
16468 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16472 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16473 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16474 const Type *MemType = AI->getType();
16475 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16476 // there is no benefit in turning such RMWs into loads, and it is actually
16477 // harmful as it introduces a mfence.
16478 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16481 auto Builder = IRBuilder<>(AI);
16482 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16483 auto SynchScope = AI->getSynchScope();
16484 // We must restrict the ordering to avoid generating loads with Release or
16485 // ReleaseAcquire orderings.
16486 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16487 auto Ptr = AI->getPointerOperand();
16489 // Before the load we need a fence. Here is an example lifted from
16490 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16493 // x.store(1, relaxed);
16494 // r1 = y.fetch_add(0, release);
16496 // y.fetch_add(42, acquire);
16497 // r2 = x.load(relaxed);
16498 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16499 // lowered to just a load without a fence. A mfence flushes the store buffer,
16500 // making the optimization clearly correct.
16501 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16502 // otherwise, we might be able to be more agressive on relaxed idempotent
16503 // rmw. In practice, they do not look useful, so we don't try to be
16504 // especially clever.
16505 if (SynchScope == SingleThread) {
16506 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16507 // the IR level, so we must wrap it in an intrinsic.
16509 } else if (hasMFENCE(*Subtarget)) {
16510 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16511 Intrinsic::x86_sse2_mfence);
16512 Builder.CreateCall(MFence);
16514 // FIXME: it might make sense to use a locked operation here but on a
16515 // different cache-line to prevent cache-line bouncing. In practice it
16516 // is probably a small win, and x86 processors without mfence are rare
16517 // enough that we do not bother.
16521 // Finally we can emit the atomic load.
16522 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16523 AI->getType()->getPrimitiveSizeInBits());
16524 Loaded->setAtomic(Order, SynchScope);
16525 AI->replaceAllUsesWith(Loaded);
16526 AI->eraseFromParent();
16530 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16531 SelectionDAG &DAG) {
16533 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16534 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16535 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16536 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16538 // The only fence that needs an instruction is a sequentially-consistent
16539 // cross-thread fence.
16540 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16541 if (hasMFENCE(*Subtarget))
16542 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16544 SDValue Chain = Op.getOperand(0);
16545 SDValue Zero = DAG.getConstant(0, MVT::i32);
16547 DAG.getRegister(X86::ESP, MVT::i32), // Base
16548 DAG.getTargetConstant(1, MVT::i8), // Scale
16549 DAG.getRegister(0, MVT::i32), // Index
16550 DAG.getTargetConstant(0, MVT::i32), // Disp
16551 DAG.getRegister(0, MVT::i32), // Segment.
16555 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16556 return SDValue(Res, 0);
16559 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16560 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16563 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16564 SelectionDAG &DAG) {
16565 MVT T = Op.getSimpleValueType();
16569 switch(T.SimpleTy) {
16570 default: llvm_unreachable("Invalid value type!");
16571 case MVT::i8: Reg = X86::AL; size = 1; break;
16572 case MVT::i16: Reg = X86::AX; size = 2; break;
16573 case MVT::i32: Reg = X86::EAX; size = 4; break;
16575 assert(Subtarget->is64Bit() && "Node not type legal!");
16576 Reg = X86::RAX; size = 8;
16579 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16580 Op.getOperand(2), SDValue());
16581 SDValue Ops[] = { cpIn.getValue(0),
16584 DAG.getTargetConstant(size, MVT::i8),
16585 cpIn.getValue(1) };
16586 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16587 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16588 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16592 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16593 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16594 MVT::i32, cpOut.getValue(2));
16595 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16596 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16598 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16599 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16600 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16604 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16605 SelectionDAG &DAG) {
16606 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16607 MVT DstVT = Op.getSimpleValueType();
16609 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16610 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16611 if (DstVT != MVT::f64)
16612 // This conversion needs to be expanded.
16615 SDValue InVec = Op->getOperand(0);
16617 unsigned NumElts = SrcVT.getVectorNumElements();
16618 EVT SVT = SrcVT.getVectorElementType();
16620 // Widen the vector in input in the case of MVT::v2i32.
16621 // Example: from MVT::v2i32 to MVT::v4i32.
16622 SmallVector<SDValue, 16> Elts;
16623 for (unsigned i = 0, e = NumElts; i != e; ++i)
16624 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16625 DAG.getIntPtrConstant(i)));
16627 // Explicitly mark the extra elements as Undef.
16628 Elts.append(NumElts, DAG.getUNDEF(SVT));
16630 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16631 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16632 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16633 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16634 DAG.getIntPtrConstant(0));
16637 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16638 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16639 assert((DstVT == MVT::i64 ||
16640 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16641 "Unexpected custom BITCAST");
16642 // i64 <=> MMX conversions are Legal.
16643 if (SrcVT==MVT::i64 && DstVT.isVector())
16645 if (DstVT==MVT::i64 && SrcVT.isVector())
16647 // MMX <=> MMX conversions are Legal.
16648 if (SrcVT.isVector() && DstVT.isVector())
16650 // All other conversions need to be expanded.
16654 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16655 SelectionDAG &DAG) {
16656 SDNode *Node = Op.getNode();
16659 Op = Op.getOperand(0);
16660 EVT VT = Op.getValueType();
16661 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16662 "CTPOP lowering only implemented for 128/256-bit wide vector types");
16664 unsigned NumElts = VT.getVectorNumElements();
16665 EVT EltVT = VT.getVectorElementType();
16666 unsigned Len = EltVT.getSizeInBits();
16668 // This is the vectorized version of the "best" algorithm from
16669 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16670 // with a minor tweak to use a series of adds + shifts instead of vector
16671 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16673 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16674 // v8i32 => Always profitable
16676 // FIXME: There a couple of possible improvements:
16678 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16679 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16681 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16682 "CTPOP not implemented for this vector element type.");
16684 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16685 // extra legalization.
16686 bool NeedsBitcast = EltVT == MVT::i32;
16687 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16689 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16690 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16691 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16693 // v = v - ((v >> 1) & 0x55555555...)
16694 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16695 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16696 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16698 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16700 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16701 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16703 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16705 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16706 if (VT != And.getValueType())
16707 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16708 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16710 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16711 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16712 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16713 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16714 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16716 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16717 if (NeedsBitcast) {
16718 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16719 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16720 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16723 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16724 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16725 if (VT != AndRHS.getValueType()) {
16726 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16727 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16729 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16731 // v = (v + (v >> 4)) & 0x0F0F0F0F...
16732 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16733 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16734 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16735 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16737 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16738 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16739 if (NeedsBitcast) {
16740 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16741 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16743 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16744 if (VT != And.getValueType())
16745 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16747 // The algorithm mentioned above uses:
16748 // v = (v * 0x01010101...) >> (Len - 8)
16750 // Change it to use vector adds + vector shifts which yield faster results on
16751 // Haswell than using vector integer multiplication.
16753 // For i32 elements:
16754 // v = v + (v >> 8)
16755 // v = v + (v >> 16)
16757 // For i64 elements:
16758 // v = v + (v >> 8)
16759 // v = v + (v >> 16)
16760 // v = v + (v >> 32)
16763 SmallVector<SDValue, 8> Csts;
16764 for (unsigned i = 8; i <= Len/2; i *= 2) {
16765 Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16766 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16767 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16768 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16772 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16773 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16774 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16775 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16776 if (NeedsBitcast) {
16777 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16778 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16780 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16781 if (VT != And.getValueType())
16782 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16787 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16788 SDNode *Node = Op.getNode();
16790 EVT T = Node->getValueType(0);
16791 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16792 DAG.getConstant(0, T), Node->getOperand(2));
16793 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16794 cast<AtomicSDNode>(Node)->getMemoryVT(),
16795 Node->getOperand(0),
16796 Node->getOperand(1), negOp,
16797 cast<AtomicSDNode>(Node)->getMemOperand(),
16798 cast<AtomicSDNode>(Node)->getOrdering(),
16799 cast<AtomicSDNode>(Node)->getSynchScope());
16802 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16803 SDNode *Node = Op.getNode();
16805 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16807 // Convert seq_cst store -> xchg
16808 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16809 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16810 // (The only way to get a 16-byte store is cmpxchg16b)
16811 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16812 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16813 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16814 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16815 cast<AtomicSDNode>(Node)->getMemoryVT(),
16816 Node->getOperand(0),
16817 Node->getOperand(1), Node->getOperand(2),
16818 cast<AtomicSDNode>(Node)->getMemOperand(),
16819 cast<AtomicSDNode>(Node)->getOrdering(),
16820 cast<AtomicSDNode>(Node)->getSynchScope());
16821 return Swap.getValue(1);
16823 // Other atomic stores have a simple pattern.
16827 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16828 EVT VT = Op.getNode()->getSimpleValueType(0);
16830 // Let legalize expand this if it isn't a legal type yet.
16831 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16834 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16837 bool ExtraOp = false;
16838 switch (Op.getOpcode()) {
16839 default: llvm_unreachable("Invalid code");
16840 case ISD::ADDC: Opc = X86ISD::ADD; break;
16841 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16842 case ISD::SUBC: Opc = X86ISD::SUB; break;
16843 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16847 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16849 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16850 Op.getOperand(1), Op.getOperand(2));
16853 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16854 SelectionDAG &DAG) {
16855 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16857 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16858 // which returns the values as { float, float } (in XMM0) or
16859 // { double, double } (which is returned in XMM0, XMM1).
16861 SDValue Arg = Op.getOperand(0);
16862 EVT ArgVT = Arg.getValueType();
16863 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16865 TargetLowering::ArgListTy Args;
16866 TargetLowering::ArgListEntry Entry;
16870 Entry.isSExt = false;
16871 Entry.isZExt = false;
16872 Args.push_back(Entry);
16874 bool isF64 = ArgVT == MVT::f64;
16875 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16876 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16877 // the results are returned via SRet in memory.
16878 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16879 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16880 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16882 Type *RetTy = isF64
16883 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16884 : (Type*)VectorType::get(ArgTy, 4);
16886 TargetLowering::CallLoweringInfo CLI(DAG);
16887 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16888 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16890 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16893 // Returned in xmm0 and xmm1.
16894 return CallResult.first;
16896 // Returned in bits 0:31 and 32:64 xmm0.
16897 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16898 CallResult.first, DAG.getIntPtrConstant(0));
16899 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16900 CallResult.first, DAG.getIntPtrConstant(1));
16901 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16902 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16905 /// LowerOperation - Provide custom lowering hooks for some operations.
16907 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16908 switch (Op.getOpcode()) {
16909 default: llvm_unreachable("Should not custom lower this!");
16910 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16911 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16912 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16913 return LowerCMP_SWAP(Op, Subtarget, DAG);
16914 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
16915 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16916 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16917 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16918 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16919 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
16920 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16921 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16922 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16923 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16924 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16925 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16926 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16927 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16928 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16929 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16930 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16931 case ISD::SHL_PARTS:
16932 case ISD::SRA_PARTS:
16933 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16934 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16935 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16936 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16937 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16938 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16939 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16940 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16941 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16942 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16943 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16945 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
16946 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16947 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16948 case ISD::SETCC: return LowerSETCC(Op, DAG);
16949 case ISD::SELECT: return LowerSELECT(Op, DAG);
16950 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16951 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16952 case ISD::VASTART: return LowerVASTART(Op, DAG);
16953 case ISD::VAARG: return LowerVAARG(Op, DAG);
16954 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16955 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
16956 case ISD::INTRINSIC_VOID:
16957 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16958 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16959 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16960 case ISD::FRAME_TO_ARGS_OFFSET:
16961 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16962 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16963 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16964 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16965 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16966 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16967 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16968 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16969 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16970 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16971 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16972 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16973 case ISD::UMUL_LOHI:
16974 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16977 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16983 case ISD::UMULO: return LowerXALUO(Op, DAG);
16984 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16985 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16989 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16990 case ISD::ADD: return LowerADD(Op, DAG);
16991 case ISD::SUB: return LowerSUB(Op, DAG);
16992 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16996 /// ReplaceNodeResults - Replace a node with an illegal result type
16997 /// with a new node built out of custom code.
16998 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16999 SmallVectorImpl<SDValue>&Results,
17000 SelectionDAG &DAG) const {
17002 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17003 switch (N->getOpcode()) {
17005 llvm_unreachable("Do not know how to custom type legalize this operation!");
17006 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17007 case X86ISD::FMINC:
17009 case X86ISD::FMAXC:
17010 case X86ISD::FMAX: {
17011 EVT VT = N->getValueType(0);
17012 if (VT != MVT::v2f32)
17013 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17014 SDValue UNDEF = DAG.getUNDEF(VT);
17015 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17016 N->getOperand(0), UNDEF);
17017 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17018 N->getOperand(1), UNDEF);
17019 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17022 case ISD::SIGN_EXTEND_INREG:
17027 // We don't want to expand or promote these.
17034 case ISD::UDIVREM: {
17035 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17036 Results.push_back(V);
17039 case ISD::FP_TO_SINT:
17040 case ISD::FP_TO_UINT: {
17041 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17043 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17046 std::pair<SDValue,SDValue> Vals =
17047 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17048 SDValue FIST = Vals.first, StackSlot = Vals.second;
17049 if (FIST.getNode()) {
17050 EVT VT = N->getValueType(0);
17051 // Return a load from the stack slot.
17052 if (StackSlot.getNode())
17053 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17054 MachinePointerInfo(),
17055 false, false, false, 0));
17057 Results.push_back(FIST);
17061 case ISD::UINT_TO_FP: {
17062 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17063 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17064 N->getValueType(0) != MVT::v2f32)
17066 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17068 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17070 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17071 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17072 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17073 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17074 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17075 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17078 case ISD::FP_ROUND: {
17079 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17081 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17082 Results.push_back(V);
17085 case ISD::INTRINSIC_W_CHAIN: {
17086 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17088 default : llvm_unreachable("Do not know how to custom type "
17089 "legalize this intrinsic operation!");
17090 case Intrinsic::x86_rdtsc:
17091 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17093 case Intrinsic::x86_rdtscp:
17094 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17096 case Intrinsic::x86_rdpmc:
17097 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17100 case ISD::READCYCLECOUNTER: {
17101 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17104 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17105 EVT T = N->getValueType(0);
17106 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17107 bool Regs64bit = T == MVT::i128;
17108 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17109 SDValue cpInL, cpInH;
17110 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17111 DAG.getConstant(0, HalfT));
17112 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17113 DAG.getConstant(1, HalfT));
17114 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17115 Regs64bit ? X86::RAX : X86::EAX,
17117 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17118 Regs64bit ? X86::RDX : X86::EDX,
17119 cpInH, cpInL.getValue(1));
17120 SDValue swapInL, swapInH;
17121 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17122 DAG.getConstant(0, HalfT));
17123 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17124 DAG.getConstant(1, HalfT));
17125 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17126 Regs64bit ? X86::RBX : X86::EBX,
17127 swapInL, cpInH.getValue(1));
17128 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17129 Regs64bit ? X86::RCX : X86::ECX,
17130 swapInH, swapInL.getValue(1));
17131 SDValue Ops[] = { swapInH.getValue(0),
17133 swapInH.getValue(1) };
17134 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17135 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17136 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17137 X86ISD::LCMPXCHG8_DAG;
17138 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17139 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17140 Regs64bit ? X86::RAX : X86::EAX,
17141 HalfT, Result.getValue(1));
17142 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17143 Regs64bit ? X86::RDX : X86::EDX,
17144 HalfT, cpOutL.getValue(2));
17145 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17147 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17148 MVT::i32, cpOutH.getValue(2));
17150 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17151 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17152 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17154 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17155 Results.push_back(Success);
17156 Results.push_back(EFLAGS.getValue(1));
17159 case ISD::ATOMIC_SWAP:
17160 case ISD::ATOMIC_LOAD_ADD:
17161 case ISD::ATOMIC_LOAD_SUB:
17162 case ISD::ATOMIC_LOAD_AND:
17163 case ISD::ATOMIC_LOAD_OR:
17164 case ISD::ATOMIC_LOAD_XOR:
17165 case ISD::ATOMIC_LOAD_NAND:
17166 case ISD::ATOMIC_LOAD_MIN:
17167 case ISD::ATOMIC_LOAD_MAX:
17168 case ISD::ATOMIC_LOAD_UMIN:
17169 case ISD::ATOMIC_LOAD_UMAX:
17170 case ISD::ATOMIC_LOAD: {
17171 // Delegate to generic TypeLegalization. Situations we can really handle
17172 // should have already been dealt with by AtomicExpandPass.cpp.
17175 case ISD::BITCAST: {
17176 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17177 EVT DstVT = N->getValueType(0);
17178 EVT SrcVT = N->getOperand(0)->getValueType(0);
17180 if (SrcVT != MVT::f64 ||
17181 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17184 unsigned NumElts = DstVT.getVectorNumElements();
17185 EVT SVT = DstVT.getVectorElementType();
17186 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17187 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17188 MVT::v2f64, N->getOperand(0));
17189 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17191 if (ExperimentalVectorWideningLegalization) {
17192 // If we are legalizing vectors by widening, we already have the desired
17193 // legal vector type, just return it.
17194 Results.push_back(ToVecInt);
17198 SmallVector<SDValue, 8> Elts;
17199 for (unsigned i = 0, e = NumElts; i != e; ++i)
17200 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17201 ToVecInt, DAG.getIntPtrConstant(i)));
17203 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17208 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17210 default: return nullptr;
17211 case X86ISD::BSF: return "X86ISD::BSF";
17212 case X86ISD::BSR: return "X86ISD::BSR";
17213 case X86ISD::SHLD: return "X86ISD::SHLD";
17214 case X86ISD::SHRD: return "X86ISD::SHRD";
17215 case X86ISD::FAND: return "X86ISD::FAND";
17216 case X86ISD::FANDN: return "X86ISD::FANDN";
17217 case X86ISD::FOR: return "X86ISD::FOR";
17218 case X86ISD::FXOR: return "X86ISD::FXOR";
17219 case X86ISD::FSRL: return "X86ISD::FSRL";
17220 case X86ISD::FILD: return "X86ISD::FILD";
17221 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17222 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17223 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17224 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17225 case X86ISD::FLD: return "X86ISD::FLD";
17226 case X86ISD::FST: return "X86ISD::FST";
17227 case X86ISD::CALL: return "X86ISD::CALL";
17228 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17229 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17230 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17231 case X86ISD::BT: return "X86ISD::BT";
17232 case X86ISD::CMP: return "X86ISD::CMP";
17233 case X86ISD::COMI: return "X86ISD::COMI";
17234 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17235 case X86ISD::CMPM: return "X86ISD::CMPM";
17236 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17237 case X86ISD::SETCC: return "X86ISD::SETCC";
17238 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17239 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17240 case X86ISD::CMOV: return "X86ISD::CMOV";
17241 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17242 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17243 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17244 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17245 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17246 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17247 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17248 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17249 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17250 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17251 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17252 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17253 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17254 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17255 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17256 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17257 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17258 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17259 case X86ISD::HADD: return "X86ISD::HADD";
17260 case X86ISD::HSUB: return "X86ISD::HSUB";
17261 case X86ISD::FHADD: return "X86ISD::FHADD";
17262 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17263 case X86ISD::UMAX: return "X86ISD::UMAX";
17264 case X86ISD::UMIN: return "X86ISD::UMIN";
17265 case X86ISD::SMAX: return "X86ISD::SMAX";
17266 case X86ISD::SMIN: return "X86ISD::SMIN";
17267 case X86ISD::FMAX: return "X86ISD::FMAX";
17268 case X86ISD::FMIN: return "X86ISD::FMIN";
17269 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17270 case X86ISD::FMINC: return "X86ISD::FMINC";
17271 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17272 case X86ISD::FRCP: return "X86ISD::FRCP";
17273 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17274 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17275 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17276 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17277 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17278 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17279 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17280 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17281 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17282 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17283 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17284 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17285 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17286 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17287 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17288 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17289 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17290 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17291 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17292 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17293 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17294 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17295 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17296 case X86ISD::VSHL: return "X86ISD::VSHL";
17297 case X86ISD::VSRL: return "X86ISD::VSRL";
17298 case X86ISD::VSRA: return "X86ISD::VSRA";
17299 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17300 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17301 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17302 case X86ISD::CMPP: return "X86ISD::CMPP";
17303 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17304 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17305 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17306 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17307 case X86ISD::ADD: return "X86ISD::ADD";
17308 case X86ISD::SUB: return "X86ISD::SUB";
17309 case X86ISD::ADC: return "X86ISD::ADC";
17310 case X86ISD::SBB: return "X86ISD::SBB";
17311 case X86ISD::SMUL: return "X86ISD::SMUL";
17312 case X86ISD::UMUL: return "X86ISD::UMUL";
17313 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17314 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17315 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17316 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17317 case X86ISD::INC: return "X86ISD::INC";
17318 case X86ISD::DEC: return "X86ISD::DEC";
17319 case X86ISD::OR: return "X86ISD::OR";
17320 case X86ISD::XOR: return "X86ISD::XOR";
17321 case X86ISD::AND: return "X86ISD::AND";
17322 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17323 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17324 case X86ISD::PTEST: return "X86ISD::PTEST";
17325 case X86ISD::TESTP: return "X86ISD::TESTP";
17326 case X86ISD::TESTM: return "X86ISD::TESTM";
17327 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17328 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17329 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17330 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17331 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17332 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17333 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17334 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17335 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17336 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17337 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17338 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17339 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17340 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17341 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17342 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17343 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17344 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17345 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17346 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17347 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17348 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17349 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17350 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17351 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17352 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17353 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17354 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17355 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17356 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17357 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17358 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17359 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17360 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17361 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17362 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17363 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17364 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17365 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17366 case X86ISD::SAHF: return "X86ISD::SAHF";
17367 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17368 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17369 case X86ISD::FMADD: return "X86ISD::FMADD";
17370 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17371 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17372 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17373 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17374 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17375 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17376 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17377 case X86ISD::XTEST: return "X86ISD::XTEST";
17378 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17379 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17380 case X86ISD::SELECT: return "X86ISD::SELECT";
17381 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17382 case X86ISD::RCP28: return "X86ISD::RCP28";
17383 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17384 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17385 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17386 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17387 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17391 // isLegalAddressingMode - Return true if the addressing mode represented
17392 // by AM is legal for this target, for a load/store of the specified type.
17393 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17395 // X86 supports extremely general addressing modes.
17396 CodeModel::Model M = getTargetMachine().getCodeModel();
17397 Reloc::Model R = getTargetMachine().getRelocationModel();
17399 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17400 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17405 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17407 // If a reference to this global requires an extra load, we can't fold it.
17408 if (isGlobalStubReference(GVFlags))
17411 // If BaseGV requires a register for the PIC base, we cannot also have a
17412 // BaseReg specified.
17413 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17416 // If lower 4G is not available, then we must use rip-relative addressing.
17417 if ((M != CodeModel::Small || R != Reloc::Static) &&
17418 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17422 switch (AM.Scale) {
17428 // These scales always work.
17433 // These scales are formed with basereg+scalereg. Only accept if there is
17438 default: // Other stuff never works.
17445 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17446 unsigned Bits = Ty->getScalarSizeInBits();
17448 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17449 // particularly cheaper than those without.
17453 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17454 // variable shifts just as cheap as scalar ones.
17455 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17458 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17459 // fully general vector.
17463 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17464 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17466 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17467 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17468 return NumBits1 > NumBits2;
17471 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17472 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17475 if (!isTypeLegal(EVT::getEVT(Ty1)))
17478 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17480 // Assuming the caller doesn't have a zeroext or signext return parameter,
17481 // truncation all the way down to i1 is valid.
17485 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17486 return isInt<32>(Imm);
17489 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17490 // Can also use sub to handle negated immediates.
17491 return isInt<32>(Imm);
17494 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17495 if (!VT1.isInteger() || !VT2.isInteger())
17497 unsigned NumBits1 = VT1.getSizeInBits();
17498 unsigned NumBits2 = VT2.getSizeInBits();
17499 return NumBits1 > NumBits2;
17502 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17503 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17504 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17507 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17508 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17509 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17512 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17513 EVT VT1 = Val.getValueType();
17514 if (isZExtFree(VT1, VT2))
17517 if (Val.getOpcode() != ISD::LOAD)
17520 if (!VT1.isSimple() || !VT1.isInteger() ||
17521 !VT2.isSimple() || !VT2.isInteger())
17524 switch (VT1.getSimpleVT().SimpleTy) {
17529 // X86 has 8, 16, and 32-bit zero-extending loads.
17536 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17539 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17540 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17543 VT = VT.getScalarType();
17545 if (!VT.isSimple())
17548 switch (VT.getSimpleVT().SimpleTy) {
17559 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17560 // i16 instructions are longer (0x66 prefix) and potentially slower.
17561 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17564 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17565 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17566 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17567 /// are assumed to be legal.
17569 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17571 if (!VT.isSimple())
17574 // Very little shuffling can be done for 64-bit vectors right now.
17575 if (VT.getSizeInBits() == 64)
17578 // We only care that the types being shuffled are legal. The lowering can
17579 // handle any possible shuffle mask that results.
17580 return isTypeLegal(VT.getSimpleVT());
17584 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17586 // Just delegate to the generic legality, clear masks aren't special.
17587 return isShuffleMaskLegal(Mask, VT);
17590 //===----------------------------------------------------------------------===//
17591 // X86 Scheduler Hooks
17592 //===----------------------------------------------------------------------===//
17594 /// Utility function to emit xbegin specifying the start of an RTM region.
17595 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17596 const TargetInstrInfo *TII) {
17597 DebugLoc DL = MI->getDebugLoc();
17599 const BasicBlock *BB = MBB->getBasicBlock();
17600 MachineFunction::iterator I = MBB;
17603 // For the v = xbegin(), we generate
17614 MachineBasicBlock *thisMBB = MBB;
17615 MachineFunction *MF = MBB->getParent();
17616 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17617 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17618 MF->insert(I, mainMBB);
17619 MF->insert(I, sinkMBB);
17621 // Transfer the remainder of BB and its successor edges to sinkMBB.
17622 sinkMBB->splice(sinkMBB->begin(), MBB,
17623 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17624 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17628 // # fallthrough to mainMBB
17629 // # abortion to sinkMBB
17630 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17631 thisMBB->addSuccessor(mainMBB);
17632 thisMBB->addSuccessor(sinkMBB);
17636 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17637 mainMBB->addSuccessor(sinkMBB);
17640 // EAX is live into the sinkMBB
17641 sinkMBB->addLiveIn(X86::EAX);
17642 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17643 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17646 MI->eraseFromParent();
17650 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17651 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17652 // in the .td file.
17653 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17654 const TargetInstrInfo *TII) {
17656 switch (MI->getOpcode()) {
17657 default: llvm_unreachable("illegal opcode!");
17658 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17659 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17660 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17661 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17662 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17663 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17664 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17665 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17668 DebugLoc dl = MI->getDebugLoc();
17669 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17671 unsigned NumArgs = MI->getNumOperands();
17672 for (unsigned i = 1; i < NumArgs; ++i) {
17673 MachineOperand &Op = MI->getOperand(i);
17674 if (!(Op.isReg() && Op.isImplicit()))
17675 MIB.addOperand(Op);
17677 if (MI->hasOneMemOperand())
17678 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17680 BuildMI(*BB, MI, dl,
17681 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17682 .addReg(X86::XMM0);
17684 MI->eraseFromParent();
17688 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17689 // defs in an instruction pattern
17690 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17691 const TargetInstrInfo *TII) {
17693 switch (MI->getOpcode()) {
17694 default: llvm_unreachable("illegal opcode!");
17695 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17696 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17697 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17698 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17699 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17700 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17701 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17702 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17705 DebugLoc dl = MI->getDebugLoc();
17706 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17708 unsigned NumArgs = MI->getNumOperands(); // remove the results
17709 for (unsigned i = 1; i < NumArgs; ++i) {
17710 MachineOperand &Op = MI->getOperand(i);
17711 if (!(Op.isReg() && Op.isImplicit()))
17712 MIB.addOperand(Op);
17714 if (MI->hasOneMemOperand())
17715 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17717 BuildMI(*BB, MI, dl,
17718 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17721 MI->eraseFromParent();
17725 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17726 const X86Subtarget *Subtarget) {
17727 DebugLoc dl = MI->getDebugLoc();
17728 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17729 // Address into RAX/EAX, other two args into ECX, EDX.
17730 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17731 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17732 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17733 for (int i = 0; i < X86::AddrNumOperands; ++i)
17734 MIB.addOperand(MI->getOperand(i));
17736 unsigned ValOps = X86::AddrNumOperands;
17737 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17738 .addReg(MI->getOperand(ValOps).getReg());
17739 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17740 .addReg(MI->getOperand(ValOps+1).getReg());
17742 // The instruction doesn't actually take any operands though.
17743 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17745 MI->eraseFromParent(); // The pseudo is gone now.
17749 MachineBasicBlock *
17750 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17751 MachineBasicBlock *MBB) const {
17752 // Emit va_arg instruction on X86-64.
17754 // Operands to this pseudo-instruction:
17755 // 0 ) Output : destination address (reg)
17756 // 1-5) Input : va_list address (addr, i64mem)
17757 // 6 ) ArgSize : Size (in bytes) of vararg type
17758 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17759 // 8 ) Align : Alignment of type
17760 // 9 ) EFLAGS (implicit-def)
17762 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17763 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17765 unsigned DestReg = MI->getOperand(0).getReg();
17766 MachineOperand &Base = MI->getOperand(1);
17767 MachineOperand &Scale = MI->getOperand(2);
17768 MachineOperand &Index = MI->getOperand(3);
17769 MachineOperand &Disp = MI->getOperand(4);
17770 MachineOperand &Segment = MI->getOperand(5);
17771 unsigned ArgSize = MI->getOperand(6).getImm();
17772 unsigned ArgMode = MI->getOperand(7).getImm();
17773 unsigned Align = MI->getOperand(8).getImm();
17775 // Memory Reference
17776 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17777 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17778 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17780 // Machine Information
17781 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17782 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17783 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17784 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17785 DebugLoc DL = MI->getDebugLoc();
17787 // struct va_list {
17790 // i64 overflow_area (address)
17791 // i64 reg_save_area (address)
17793 // sizeof(va_list) = 24
17794 // alignment(va_list) = 8
17796 unsigned TotalNumIntRegs = 6;
17797 unsigned TotalNumXMMRegs = 8;
17798 bool UseGPOffset = (ArgMode == 1);
17799 bool UseFPOffset = (ArgMode == 2);
17800 unsigned MaxOffset = TotalNumIntRegs * 8 +
17801 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17803 /* Align ArgSize to a multiple of 8 */
17804 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17805 bool NeedsAlign = (Align > 8);
17807 MachineBasicBlock *thisMBB = MBB;
17808 MachineBasicBlock *overflowMBB;
17809 MachineBasicBlock *offsetMBB;
17810 MachineBasicBlock *endMBB;
17812 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17813 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17814 unsigned OffsetReg = 0;
17816 if (!UseGPOffset && !UseFPOffset) {
17817 // If we only pull from the overflow region, we don't create a branch.
17818 // We don't need to alter control flow.
17819 OffsetDestReg = 0; // unused
17820 OverflowDestReg = DestReg;
17822 offsetMBB = nullptr;
17823 overflowMBB = thisMBB;
17826 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17827 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17828 // If not, pull from overflow_area. (branch to overflowMBB)
17833 // offsetMBB overflowMBB
17838 // Registers for the PHI in endMBB
17839 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17840 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17842 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17843 MachineFunction *MF = MBB->getParent();
17844 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17845 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17846 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17848 MachineFunction::iterator MBBIter = MBB;
17851 // Insert the new basic blocks
17852 MF->insert(MBBIter, offsetMBB);
17853 MF->insert(MBBIter, overflowMBB);
17854 MF->insert(MBBIter, endMBB);
17856 // Transfer the remainder of MBB and its successor edges to endMBB.
17857 endMBB->splice(endMBB->begin(), thisMBB,
17858 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17859 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17861 // Make offsetMBB and overflowMBB successors of thisMBB
17862 thisMBB->addSuccessor(offsetMBB);
17863 thisMBB->addSuccessor(overflowMBB);
17865 // endMBB is a successor of both offsetMBB and overflowMBB
17866 offsetMBB->addSuccessor(endMBB);
17867 overflowMBB->addSuccessor(endMBB);
17869 // Load the offset value into a register
17870 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17871 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17875 .addDisp(Disp, UseFPOffset ? 4 : 0)
17876 .addOperand(Segment)
17877 .setMemRefs(MMOBegin, MMOEnd);
17879 // Check if there is enough room left to pull this argument.
17880 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17882 .addImm(MaxOffset + 8 - ArgSizeA8);
17884 // Branch to "overflowMBB" if offset >= max
17885 // Fall through to "offsetMBB" otherwise
17886 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17887 .addMBB(overflowMBB);
17890 // In offsetMBB, emit code to use the reg_save_area.
17892 assert(OffsetReg != 0);
17894 // Read the reg_save_area address.
17895 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17896 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17901 .addOperand(Segment)
17902 .setMemRefs(MMOBegin, MMOEnd);
17904 // Zero-extend the offset
17905 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17906 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17909 .addImm(X86::sub_32bit);
17911 // Add the offset to the reg_save_area to get the final address.
17912 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17913 .addReg(OffsetReg64)
17914 .addReg(RegSaveReg);
17916 // Compute the offset for the next argument
17917 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17918 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17920 .addImm(UseFPOffset ? 16 : 8);
17922 // Store it back into the va_list.
17923 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17927 .addDisp(Disp, UseFPOffset ? 4 : 0)
17928 .addOperand(Segment)
17929 .addReg(NextOffsetReg)
17930 .setMemRefs(MMOBegin, MMOEnd);
17933 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
17938 // Emit code to use overflow area
17941 // Load the overflow_area address into a register.
17942 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17943 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17948 .addOperand(Segment)
17949 .setMemRefs(MMOBegin, MMOEnd);
17951 // If we need to align it, do so. Otherwise, just copy the address
17952 // to OverflowDestReg.
17954 // Align the overflow address
17955 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17956 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17958 // aligned_addr = (addr + (align-1)) & ~(align-1)
17959 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17960 .addReg(OverflowAddrReg)
17963 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17965 .addImm(~(uint64_t)(Align-1));
17967 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17968 .addReg(OverflowAddrReg);
17971 // Compute the next overflow address after this argument.
17972 // (the overflow address should be kept 8-byte aligned)
17973 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17974 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17975 .addReg(OverflowDestReg)
17976 .addImm(ArgSizeA8);
17978 // Store the new overflow address.
17979 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17984 .addOperand(Segment)
17985 .addReg(NextAddrReg)
17986 .setMemRefs(MMOBegin, MMOEnd);
17988 // If we branched, emit the PHI to the front of endMBB.
17990 BuildMI(*endMBB, endMBB->begin(), DL,
17991 TII->get(X86::PHI), DestReg)
17992 .addReg(OffsetDestReg).addMBB(offsetMBB)
17993 .addReg(OverflowDestReg).addMBB(overflowMBB);
17996 // Erase the pseudo instruction
17997 MI->eraseFromParent();
18002 MachineBasicBlock *
18003 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18005 MachineBasicBlock *MBB) const {
18006 // Emit code to save XMM registers to the stack. The ABI says that the
18007 // number of registers to save is given in %al, so it's theoretically
18008 // possible to do an indirect jump trick to avoid saving all of them,
18009 // however this code takes a simpler approach and just executes all
18010 // of the stores if %al is non-zero. It's less code, and it's probably
18011 // easier on the hardware branch predictor, and stores aren't all that
18012 // expensive anyway.
18014 // Create the new basic blocks. One block contains all the XMM stores,
18015 // and one block is the final destination regardless of whether any
18016 // stores were performed.
18017 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18018 MachineFunction *F = MBB->getParent();
18019 MachineFunction::iterator MBBIter = MBB;
18021 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18022 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18023 F->insert(MBBIter, XMMSaveMBB);
18024 F->insert(MBBIter, EndMBB);
18026 // Transfer the remainder of MBB and its successor edges to EndMBB.
18027 EndMBB->splice(EndMBB->begin(), MBB,
18028 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18029 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18031 // The original block will now fall through to the XMM save block.
18032 MBB->addSuccessor(XMMSaveMBB);
18033 // The XMMSaveMBB will fall through to the end block.
18034 XMMSaveMBB->addSuccessor(EndMBB);
18036 // Now add the instructions.
18037 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18038 DebugLoc DL = MI->getDebugLoc();
18040 unsigned CountReg = MI->getOperand(0).getReg();
18041 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18042 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18044 if (!Subtarget->isTargetWin64()) {
18045 // If %al is 0, branch around the XMM save block.
18046 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18047 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18048 MBB->addSuccessor(EndMBB);
18051 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18052 // that was just emitted, but clearly shouldn't be "saved".
18053 assert((MI->getNumOperands() <= 3 ||
18054 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18055 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18056 && "Expected last argument to be EFLAGS");
18057 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18058 // In the XMM save block, save all the XMM argument registers.
18059 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18060 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18061 MachineMemOperand *MMO =
18062 F->getMachineMemOperand(
18063 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18064 MachineMemOperand::MOStore,
18065 /*Size=*/16, /*Align=*/16);
18066 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18067 .addFrameIndex(RegSaveFrameIndex)
18068 .addImm(/*Scale=*/1)
18069 .addReg(/*IndexReg=*/0)
18070 .addImm(/*Disp=*/Offset)
18071 .addReg(/*Segment=*/0)
18072 .addReg(MI->getOperand(i).getReg())
18073 .addMemOperand(MMO);
18076 MI->eraseFromParent(); // The pseudo instruction is gone now.
18081 // The EFLAGS operand of SelectItr might be missing a kill marker
18082 // because there were multiple uses of EFLAGS, and ISel didn't know
18083 // which to mark. Figure out whether SelectItr should have had a
18084 // kill marker, and set it if it should. Returns the correct kill
18086 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18087 MachineBasicBlock* BB,
18088 const TargetRegisterInfo* TRI) {
18089 // Scan forward through BB for a use/def of EFLAGS.
18090 MachineBasicBlock::iterator miI(std::next(SelectItr));
18091 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18092 const MachineInstr& mi = *miI;
18093 if (mi.readsRegister(X86::EFLAGS))
18095 if (mi.definesRegister(X86::EFLAGS))
18096 break; // Should have kill-flag - update below.
18099 // If we hit the end of the block, check whether EFLAGS is live into a
18101 if (miI == BB->end()) {
18102 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18103 sEnd = BB->succ_end();
18104 sItr != sEnd; ++sItr) {
18105 MachineBasicBlock* succ = *sItr;
18106 if (succ->isLiveIn(X86::EFLAGS))
18111 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18112 // out. SelectMI should have a kill flag on EFLAGS.
18113 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18117 MachineBasicBlock *
18118 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18119 MachineBasicBlock *BB) const {
18120 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18121 DebugLoc DL = MI->getDebugLoc();
18123 // To "insert" a SELECT_CC instruction, we actually have to insert the
18124 // diamond control-flow pattern. The incoming instruction knows the
18125 // destination vreg to set, the condition code register to branch on, the
18126 // true/false values to select between, and a branch opcode to use.
18127 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18128 MachineFunction::iterator It = BB;
18134 // cmpTY ccX, r1, r2
18136 // fallthrough --> copy0MBB
18137 MachineBasicBlock *thisMBB = BB;
18138 MachineFunction *F = BB->getParent();
18139 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18140 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18141 F->insert(It, copy0MBB);
18142 F->insert(It, sinkMBB);
18144 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18145 // live into the sink and copy blocks.
18146 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18147 if (!MI->killsRegister(X86::EFLAGS) &&
18148 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18149 copy0MBB->addLiveIn(X86::EFLAGS);
18150 sinkMBB->addLiveIn(X86::EFLAGS);
18153 // Transfer the remainder of BB and its successor edges to sinkMBB.
18154 sinkMBB->splice(sinkMBB->begin(), BB,
18155 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18156 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18158 // Add the true and fallthrough blocks as its successors.
18159 BB->addSuccessor(copy0MBB);
18160 BB->addSuccessor(sinkMBB);
18162 // Create the conditional branch instruction.
18164 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18165 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18168 // %FalseValue = ...
18169 // # fallthrough to sinkMBB
18170 copy0MBB->addSuccessor(sinkMBB);
18173 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18175 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18176 TII->get(X86::PHI), MI->getOperand(0).getReg())
18177 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18178 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18180 MI->eraseFromParent(); // The pseudo instruction is gone now.
18184 MachineBasicBlock *
18185 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18186 MachineBasicBlock *BB) const {
18187 MachineFunction *MF = BB->getParent();
18188 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18189 DebugLoc DL = MI->getDebugLoc();
18190 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18192 assert(MF->shouldSplitStack());
18194 const bool Is64Bit = Subtarget->is64Bit();
18195 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18197 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18198 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18201 // ... [Till the alloca]
18202 // If stacklet is not large enough, jump to mallocMBB
18205 // Allocate by subtracting from RSP
18206 // Jump to continueMBB
18209 // Allocate by call to runtime
18213 // [rest of original BB]
18216 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18217 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18218 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18220 MachineRegisterInfo &MRI = MF->getRegInfo();
18221 const TargetRegisterClass *AddrRegClass =
18222 getRegClassFor(getPointerTy());
18224 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18225 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18226 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18227 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18228 sizeVReg = MI->getOperand(1).getReg(),
18229 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18231 MachineFunction::iterator MBBIter = BB;
18234 MF->insert(MBBIter, bumpMBB);
18235 MF->insert(MBBIter, mallocMBB);
18236 MF->insert(MBBIter, continueMBB);
18238 continueMBB->splice(continueMBB->begin(), BB,
18239 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18240 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18242 // Add code to the main basic block to check if the stack limit has been hit,
18243 // and if so, jump to mallocMBB otherwise to bumpMBB.
18244 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18245 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18246 .addReg(tmpSPVReg).addReg(sizeVReg);
18247 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18248 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18249 .addReg(SPLimitVReg);
18250 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18252 // bumpMBB simply decreases the stack pointer, since we know the current
18253 // stacklet has enough space.
18254 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18255 .addReg(SPLimitVReg);
18256 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18257 .addReg(SPLimitVReg);
18258 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18260 // Calls into a routine in libgcc to allocate more space from the heap.
18261 const uint32_t *RegMask =
18262 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18264 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18266 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18267 .addExternalSymbol("__morestack_allocate_stack_space")
18268 .addRegMask(RegMask)
18269 .addReg(X86::RDI, RegState::Implicit)
18270 .addReg(X86::RAX, RegState::ImplicitDefine);
18271 } else if (Is64Bit) {
18272 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18274 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18275 .addExternalSymbol("__morestack_allocate_stack_space")
18276 .addRegMask(RegMask)
18277 .addReg(X86::EDI, RegState::Implicit)
18278 .addReg(X86::EAX, RegState::ImplicitDefine);
18280 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18282 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18283 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18284 .addExternalSymbol("__morestack_allocate_stack_space")
18285 .addRegMask(RegMask)
18286 .addReg(X86::EAX, RegState::ImplicitDefine);
18290 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18293 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18294 .addReg(IsLP64 ? X86::RAX : X86::EAX);
18295 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18297 // Set up the CFG correctly.
18298 BB->addSuccessor(bumpMBB);
18299 BB->addSuccessor(mallocMBB);
18300 mallocMBB->addSuccessor(continueMBB);
18301 bumpMBB->addSuccessor(continueMBB);
18303 // Take care of the PHI nodes.
18304 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18305 MI->getOperand(0).getReg())
18306 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18307 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18309 // Delete the original pseudo instruction.
18310 MI->eraseFromParent();
18313 return continueMBB;
18316 MachineBasicBlock *
18317 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18318 MachineBasicBlock *BB) const {
18319 DebugLoc DL = MI->getDebugLoc();
18321 assert(!Subtarget->isTargetMachO());
18323 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18325 MI->eraseFromParent(); // The pseudo instruction is gone now.
18329 MachineBasicBlock *
18330 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18331 MachineBasicBlock *BB) const {
18332 // This is pretty easy. We're taking the value that we received from
18333 // our load from the relocation, sticking it in either RDI (x86-64)
18334 // or EAX and doing an indirect call. The return value will then
18335 // be in the normal return register.
18336 MachineFunction *F = BB->getParent();
18337 const X86InstrInfo *TII = Subtarget->getInstrInfo();
18338 DebugLoc DL = MI->getDebugLoc();
18340 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18341 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18343 // Get a register mask for the lowered call.
18344 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18345 // proper register mask.
18346 const uint32_t *RegMask =
18347 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18348 if (Subtarget->is64Bit()) {
18349 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18350 TII->get(X86::MOV64rm), X86::RDI)
18352 .addImm(0).addReg(0)
18353 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18354 MI->getOperand(3).getTargetFlags())
18356 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18357 addDirectMem(MIB, X86::RDI);
18358 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18359 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18360 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18361 TII->get(X86::MOV32rm), X86::EAX)
18363 .addImm(0).addReg(0)
18364 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18365 MI->getOperand(3).getTargetFlags())
18367 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18368 addDirectMem(MIB, X86::EAX);
18369 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18371 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18372 TII->get(X86::MOV32rm), X86::EAX)
18373 .addReg(TII->getGlobalBaseReg(F))
18374 .addImm(0).addReg(0)
18375 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18376 MI->getOperand(3).getTargetFlags())
18378 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18379 addDirectMem(MIB, X86::EAX);
18380 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18383 MI->eraseFromParent(); // The pseudo instruction is gone now.
18387 MachineBasicBlock *
18388 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18389 MachineBasicBlock *MBB) const {
18390 DebugLoc DL = MI->getDebugLoc();
18391 MachineFunction *MF = MBB->getParent();
18392 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18393 MachineRegisterInfo &MRI = MF->getRegInfo();
18395 const BasicBlock *BB = MBB->getBasicBlock();
18396 MachineFunction::iterator I = MBB;
18399 // Memory Reference
18400 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18401 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18404 unsigned MemOpndSlot = 0;
18406 unsigned CurOp = 0;
18408 DstReg = MI->getOperand(CurOp++).getReg();
18409 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18410 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18411 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18412 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18414 MemOpndSlot = CurOp;
18416 MVT PVT = getPointerTy();
18417 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18418 "Invalid Pointer Size!");
18420 // For v = setjmp(buf), we generate
18423 // buf[LabelOffset] = restoreMBB
18424 // SjLjSetup restoreMBB
18430 // v = phi(main, restore)
18433 // if base pointer being used, load it from frame
18436 MachineBasicBlock *thisMBB = MBB;
18437 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18438 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18439 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18440 MF->insert(I, mainMBB);
18441 MF->insert(I, sinkMBB);
18442 MF->push_back(restoreMBB);
18444 MachineInstrBuilder MIB;
18446 // Transfer the remainder of BB and its successor edges to sinkMBB.
18447 sinkMBB->splice(sinkMBB->begin(), MBB,
18448 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18449 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18452 unsigned PtrStoreOpc = 0;
18453 unsigned LabelReg = 0;
18454 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18455 Reloc::Model RM = MF->getTarget().getRelocationModel();
18456 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18457 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18459 // Prepare IP either in reg or imm.
18460 if (!UseImmLabel) {
18461 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18462 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18463 LabelReg = MRI.createVirtualRegister(PtrRC);
18464 if (Subtarget->is64Bit()) {
18465 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18469 .addMBB(restoreMBB)
18472 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18473 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18474 .addReg(XII->getGlobalBaseReg(MF))
18477 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18481 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18483 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18484 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18485 if (i == X86::AddrDisp)
18486 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18488 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18491 MIB.addReg(LabelReg);
18493 MIB.addMBB(restoreMBB);
18494 MIB.setMemRefs(MMOBegin, MMOEnd);
18496 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18497 .addMBB(restoreMBB);
18499 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18500 MIB.addRegMask(RegInfo->getNoPreservedMask());
18501 thisMBB->addSuccessor(mainMBB);
18502 thisMBB->addSuccessor(restoreMBB);
18506 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18507 mainMBB->addSuccessor(sinkMBB);
18510 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18511 TII->get(X86::PHI), DstReg)
18512 .addReg(mainDstReg).addMBB(mainMBB)
18513 .addReg(restoreDstReg).addMBB(restoreMBB);
18516 if (RegInfo->hasBasePointer(*MF)) {
18517 const bool Uses64BitFramePtr =
18518 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18519 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18520 X86FI->setRestoreBasePointer(MF);
18521 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18522 unsigned BasePtr = RegInfo->getBaseRegister();
18523 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18524 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18525 FramePtr, true, X86FI->getRestoreBasePointerOffset())
18526 .setMIFlag(MachineInstr::FrameSetup);
18528 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18529 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18530 restoreMBB->addSuccessor(sinkMBB);
18532 MI->eraseFromParent();
18536 MachineBasicBlock *
18537 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18538 MachineBasicBlock *MBB) const {
18539 DebugLoc DL = MI->getDebugLoc();
18540 MachineFunction *MF = MBB->getParent();
18541 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18542 MachineRegisterInfo &MRI = MF->getRegInfo();
18544 // Memory Reference
18545 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18546 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18548 MVT PVT = getPointerTy();
18549 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18550 "Invalid Pointer Size!");
18552 const TargetRegisterClass *RC =
18553 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18554 unsigned Tmp = MRI.createVirtualRegister(RC);
18555 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18556 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18557 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18558 unsigned SP = RegInfo->getStackRegister();
18560 MachineInstrBuilder MIB;
18562 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18563 const int64_t SPOffset = 2 * PVT.getStoreSize();
18565 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18566 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18569 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18570 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18571 MIB.addOperand(MI->getOperand(i));
18572 MIB.setMemRefs(MMOBegin, MMOEnd);
18574 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18575 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18576 if (i == X86::AddrDisp)
18577 MIB.addDisp(MI->getOperand(i), LabelOffset);
18579 MIB.addOperand(MI->getOperand(i));
18581 MIB.setMemRefs(MMOBegin, MMOEnd);
18583 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18584 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18585 if (i == X86::AddrDisp)
18586 MIB.addDisp(MI->getOperand(i), SPOffset);
18588 MIB.addOperand(MI->getOperand(i));
18590 MIB.setMemRefs(MMOBegin, MMOEnd);
18592 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18594 MI->eraseFromParent();
18598 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18599 // accumulator loops. Writing back to the accumulator allows the coalescer
18600 // to remove extra copies in the loop.
18601 MachineBasicBlock *
18602 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18603 MachineBasicBlock *MBB) const {
18604 MachineOperand &AddendOp = MI->getOperand(3);
18606 // Bail out early if the addend isn't a register - we can't switch these.
18607 if (!AddendOp.isReg())
18610 MachineFunction &MF = *MBB->getParent();
18611 MachineRegisterInfo &MRI = MF.getRegInfo();
18613 // Check whether the addend is defined by a PHI:
18614 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18615 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18616 if (!AddendDef.isPHI())
18619 // Look for the following pattern:
18621 // %addend = phi [%entry, 0], [%loop, %result]
18623 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18627 // %addend = phi [%entry, 0], [%loop, %result]
18629 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18631 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18632 assert(AddendDef.getOperand(i).isReg());
18633 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18634 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18635 if (&PHISrcInst == MI) {
18636 // Found a matching instruction.
18637 unsigned NewFMAOpc = 0;
18638 switch (MI->getOpcode()) {
18639 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18640 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18641 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18642 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18643 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18644 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18645 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18646 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18647 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18648 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18649 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18650 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18651 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18652 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18653 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18654 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18655 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18656 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18657 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18658 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18660 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18661 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18662 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18663 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18664 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18665 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18666 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18667 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18668 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18669 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18670 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18671 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18672 default: llvm_unreachable("Unrecognized FMA variant.");
18675 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18676 MachineInstrBuilder MIB =
18677 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18678 .addOperand(MI->getOperand(0))
18679 .addOperand(MI->getOperand(3))
18680 .addOperand(MI->getOperand(2))
18681 .addOperand(MI->getOperand(1));
18682 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18683 MI->eraseFromParent();
18690 MachineBasicBlock *
18691 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18692 MachineBasicBlock *BB) const {
18693 switch (MI->getOpcode()) {
18694 default: llvm_unreachable("Unexpected instr type to insert");
18695 case X86::TAILJMPd64:
18696 case X86::TAILJMPr64:
18697 case X86::TAILJMPm64:
18698 case X86::TAILJMPd64_REX:
18699 case X86::TAILJMPr64_REX:
18700 case X86::TAILJMPm64_REX:
18701 llvm_unreachable("TAILJMP64 would not be touched here.");
18702 case X86::TCRETURNdi64:
18703 case X86::TCRETURNri64:
18704 case X86::TCRETURNmi64:
18706 case X86::WIN_ALLOCA:
18707 return EmitLoweredWinAlloca(MI, BB);
18708 case X86::SEG_ALLOCA_32:
18709 case X86::SEG_ALLOCA_64:
18710 return EmitLoweredSegAlloca(MI, BB);
18711 case X86::TLSCall_32:
18712 case X86::TLSCall_64:
18713 return EmitLoweredTLSCall(MI, BB);
18714 case X86::CMOV_GR8:
18715 case X86::CMOV_FR32:
18716 case X86::CMOV_FR64:
18717 case X86::CMOV_V4F32:
18718 case X86::CMOV_V2F64:
18719 case X86::CMOV_V2I64:
18720 case X86::CMOV_V8F32:
18721 case X86::CMOV_V4F64:
18722 case X86::CMOV_V4I64:
18723 case X86::CMOV_V16F32:
18724 case X86::CMOV_V8F64:
18725 case X86::CMOV_V8I64:
18726 case X86::CMOV_GR16:
18727 case X86::CMOV_GR32:
18728 case X86::CMOV_RFP32:
18729 case X86::CMOV_RFP64:
18730 case X86::CMOV_RFP80:
18731 return EmitLoweredSelect(MI, BB);
18733 case X86::FP32_TO_INT16_IN_MEM:
18734 case X86::FP32_TO_INT32_IN_MEM:
18735 case X86::FP32_TO_INT64_IN_MEM:
18736 case X86::FP64_TO_INT16_IN_MEM:
18737 case X86::FP64_TO_INT32_IN_MEM:
18738 case X86::FP64_TO_INT64_IN_MEM:
18739 case X86::FP80_TO_INT16_IN_MEM:
18740 case X86::FP80_TO_INT32_IN_MEM:
18741 case X86::FP80_TO_INT64_IN_MEM: {
18742 MachineFunction *F = BB->getParent();
18743 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18744 DebugLoc DL = MI->getDebugLoc();
18746 // Change the floating point control register to use "round towards zero"
18747 // mode when truncating to an integer value.
18748 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18749 addFrameReference(BuildMI(*BB, MI, DL,
18750 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18752 // Load the old value of the high byte of the control word...
18754 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18755 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18758 // Set the high part to be round to zero...
18759 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18762 // Reload the modified control word now...
18763 addFrameReference(BuildMI(*BB, MI, DL,
18764 TII->get(X86::FLDCW16m)), CWFrameIdx);
18766 // Restore the memory image of control word to original value
18767 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18770 // Get the X86 opcode to use.
18772 switch (MI->getOpcode()) {
18773 default: llvm_unreachable("illegal opcode!");
18774 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18775 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18776 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18777 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18778 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18779 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18780 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18781 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18782 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18786 MachineOperand &Op = MI->getOperand(0);
18788 AM.BaseType = X86AddressMode::RegBase;
18789 AM.Base.Reg = Op.getReg();
18791 AM.BaseType = X86AddressMode::FrameIndexBase;
18792 AM.Base.FrameIndex = Op.getIndex();
18794 Op = MI->getOperand(1);
18796 AM.Scale = Op.getImm();
18797 Op = MI->getOperand(2);
18799 AM.IndexReg = Op.getImm();
18800 Op = MI->getOperand(3);
18801 if (Op.isGlobal()) {
18802 AM.GV = Op.getGlobal();
18804 AM.Disp = Op.getImm();
18806 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18807 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18809 // Reload the original control word now.
18810 addFrameReference(BuildMI(*BB, MI, DL,
18811 TII->get(X86::FLDCW16m)), CWFrameIdx);
18813 MI->eraseFromParent(); // The pseudo instruction is gone now.
18816 // String/text processing lowering.
18817 case X86::PCMPISTRM128REG:
18818 case X86::VPCMPISTRM128REG:
18819 case X86::PCMPISTRM128MEM:
18820 case X86::VPCMPISTRM128MEM:
18821 case X86::PCMPESTRM128REG:
18822 case X86::VPCMPESTRM128REG:
18823 case X86::PCMPESTRM128MEM:
18824 case X86::VPCMPESTRM128MEM:
18825 assert(Subtarget->hasSSE42() &&
18826 "Target must have SSE4.2 or AVX features enabled");
18827 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
18829 // String/text processing lowering.
18830 case X86::PCMPISTRIREG:
18831 case X86::VPCMPISTRIREG:
18832 case X86::PCMPISTRIMEM:
18833 case X86::VPCMPISTRIMEM:
18834 case X86::PCMPESTRIREG:
18835 case X86::VPCMPESTRIREG:
18836 case X86::PCMPESTRIMEM:
18837 case X86::VPCMPESTRIMEM:
18838 assert(Subtarget->hasSSE42() &&
18839 "Target must have SSE4.2 or AVX features enabled");
18840 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
18842 // Thread synchronization.
18844 return EmitMonitor(MI, BB, Subtarget);
18848 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
18850 case X86::VASTART_SAVE_XMM_REGS:
18851 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18853 case X86::VAARG_64:
18854 return EmitVAARG64WithCustomInserter(MI, BB);
18856 case X86::EH_SjLj_SetJmp32:
18857 case X86::EH_SjLj_SetJmp64:
18858 return emitEHSjLjSetJmp(MI, BB);
18860 case X86::EH_SjLj_LongJmp32:
18861 case X86::EH_SjLj_LongJmp64:
18862 return emitEHSjLjLongJmp(MI, BB);
18864 case TargetOpcode::STATEPOINT:
18865 // As an implementation detail, STATEPOINT shares the STACKMAP format at
18866 // this point in the process. We diverge later.
18867 return emitPatchPoint(MI, BB);
18869 case TargetOpcode::STACKMAP:
18870 case TargetOpcode::PATCHPOINT:
18871 return emitPatchPoint(MI, BB);
18873 case X86::VFMADDPDr213r:
18874 case X86::VFMADDPSr213r:
18875 case X86::VFMADDSDr213r:
18876 case X86::VFMADDSSr213r:
18877 case X86::VFMSUBPDr213r:
18878 case X86::VFMSUBPSr213r:
18879 case X86::VFMSUBSDr213r:
18880 case X86::VFMSUBSSr213r:
18881 case X86::VFNMADDPDr213r:
18882 case X86::VFNMADDPSr213r:
18883 case X86::VFNMADDSDr213r:
18884 case X86::VFNMADDSSr213r:
18885 case X86::VFNMSUBPDr213r:
18886 case X86::VFNMSUBPSr213r:
18887 case X86::VFNMSUBSDr213r:
18888 case X86::VFNMSUBSSr213r:
18889 case X86::VFMADDSUBPDr213r:
18890 case X86::VFMADDSUBPSr213r:
18891 case X86::VFMSUBADDPDr213r:
18892 case X86::VFMSUBADDPSr213r:
18893 case X86::VFMADDPDr213rY:
18894 case X86::VFMADDPSr213rY:
18895 case X86::VFMSUBPDr213rY:
18896 case X86::VFMSUBPSr213rY:
18897 case X86::VFNMADDPDr213rY:
18898 case X86::VFNMADDPSr213rY:
18899 case X86::VFNMSUBPDr213rY:
18900 case X86::VFNMSUBPSr213rY:
18901 case X86::VFMADDSUBPDr213rY:
18902 case X86::VFMADDSUBPSr213rY:
18903 case X86::VFMSUBADDPDr213rY:
18904 case X86::VFMSUBADDPSr213rY:
18905 return emitFMA3Instr(MI, BB);
18909 //===----------------------------------------------------------------------===//
18910 // X86 Optimization Hooks
18911 //===----------------------------------------------------------------------===//
18913 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18916 const SelectionDAG &DAG,
18917 unsigned Depth) const {
18918 unsigned BitWidth = KnownZero.getBitWidth();
18919 unsigned Opc = Op.getOpcode();
18920 assert((Opc >= ISD::BUILTIN_OP_END ||
18921 Opc == ISD::INTRINSIC_WO_CHAIN ||
18922 Opc == ISD::INTRINSIC_W_CHAIN ||
18923 Opc == ISD::INTRINSIC_VOID) &&
18924 "Should use MaskedValueIsZero if you don't know whether Op"
18925 " is a target node!");
18927 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18941 // These nodes' second result is a boolean.
18942 if (Op.getResNo() == 0)
18945 case X86ISD::SETCC:
18946 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18948 case ISD::INTRINSIC_WO_CHAIN: {
18949 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18950 unsigned NumLoBits = 0;
18953 case Intrinsic::x86_sse_movmsk_ps:
18954 case Intrinsic::x86_avx_movmsk_ps_256:
18955 case Intrinsic::x86_sse2_movmsk_pd:
18956 case Intrinsic::x86_avx_movmsk_pd_256:
18957 case Intrinsic::x86_mmx_pmovmskb:
18958 case Intrinsic::x86_sse2_pmovmskb_128:
18959 case Intrinsic::x86_avx2_pmovmskb: {
18960 // High bits of movmskp{s|d}, pmovmskb are known zero.
18962 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18963 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18964 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18965 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18966 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18967 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18968 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18969 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18971 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18980 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18982 const SelectionDAG &,
18983 unsigned Depth) const {
18984 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18985 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18986 return Op.getValueType().getScalarType().getSizeInBits();
18992 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18993 /// node is a GlobalAddress + offset.
18994 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18995 const GlobalValue* &GA,
18996 int64_t &Offset) const {
18997 if (N->getOpcode() == X86ISD::Wrapper) {
18998 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18999 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19000 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19004 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19007 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19008 /// same as extracting the high 128-bit part of 256-bit vector and then
19009 /// inserting the result into the low part of a new 256-bit vector
19010 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19011 EVT VT = SVOp->getValueType(0);
19012 unsigned NumElems = VT.getVectorNumElements();
19014 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19015 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19016 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19017 SVOp->getMaskElt(j) >= 0)
19023 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19024 /// same as extracting the low 128-bit part of 256-bit vector and then
19025 /// inserting the result into the high part of a new 256-bit vector
19026 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19027 EVT VT = SVOp->getValueType(0);
19028 unsigned NumElems = VT.getVectorNumElements();
19030 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19031 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19032 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19033 SVOp->getMaskElt(j) >= 0)
19039 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19040 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19041 TargetLowering::DAGCombinerInfo &DCI,
19042 const X86Subtarget* Subtarget) {
19044 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19045 SDValue V1 = SVOp->getOperand(0);
19046 SDValue V2 = SVOp->getOperand(1);
19047 EVT VT = SVOp->getValueType(0);
19048 unsigned NumElems = VT.getVectorNumElements();
19050 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19051 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19055 // V UNDEF BUILD_VECTOR UNDEF
19057 // CONCAT_VECTOR CONCAT_VECTOR
19060 // RESULT: V + zero extended
19062 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19063 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19064 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19067 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19070 // To match the shuffle mask, the first half of the mask should
19071 // be exactly the first vector, and all the rest a splat with the
19072 // first element of the second one.
19073 for (unsigned i = 0; i != NumElems/2; ++i)
19074 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19075 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19078 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19079 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19080 if (Ld->hasNUsesOfValue(1, 0)) {
19081 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19082 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19084 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19086 Ld->getPointerInfo(),
19087 Ld->getAlignment(),
19088 false/*isVolatile*/, true/*ReadMem*/,
19089 false/*WriteMem*/);
19091 // Make sure the newly-created LOAD is in the same position as Ld in
19092 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19093 // and update uses of Ld's output chain to use the TokenFactor.
19094 if (Ld->hasAnyUseOfValue(1)) {
19095 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19096 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19097 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19098 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19099 SDValue(ResNode.getNode(), 1));
19102 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19106 // Emit a zeroed vector and insert the desired subvector on its
19108 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19109 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19110 return DCI.CombineTo(N, InsV);
19113 //===--------------------------------------------------------------------===//
19114 // Combine some shuffles into subvector extracts and inserts:
19117 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19118 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19119 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19120 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19121 return DCI.CombineTo(N, InsV);
19124 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19125 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19126 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19127 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19128 return DCI.CombineTo(N, InsV);
19134 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19137 /// This is the leaf of the recursive combinine below. When we have found some
19138 /// chain of single-use x86 shuffle instructions and accumulated the combined
19139 /// shuffle mask represented by them, this will try to pattern match that mask
19140 /// into either a single instruction if there is a special purpose instruction
19141 /// for this operation, or into a PSHUFB instruction which is a fully general
19142 /// instruction but should only be used to replace chains over a certain depth.
19143 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19144 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19145 TargetLowering::DAGCombinerInfo &DCI,
19146 const X86Subtarget *Subtarget) {
19147 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19149 // Find the operand that enters the chain. Note that multiple uses are OK
19150 // here, we're not going to remove the operand we find.
19151 SDValue Input = Op.getOperand(0);
19152 while (Input.getOpcode() == ISD::BITCAST)
19153 Input = Input.getOperand(0);
19155 MVT VT = Input.getSimpleValueType();
19156 MVT RootVT = Root.getSimpleValueType();
19159 // Just remove no-op shuffle masks.
19160 if (Mask.size() == 1) {
19161 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19166 // Use the float domain if the operand type is a floating point type.
19167 bool FloatDomain = VT.isFloatingPoint();
19169 // For floating point shuffles, we don't have free copies in the shuffle
19170 // instructions or the ability to load as part of the instruction, so
19171 // canonicalize their shuffles to UNPCK or MOV variants.
19173 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19174 // vectors because it can have a load folded into it that UNPCK cannot. This
19175 // doesn't preclude something switching to the shorter encoding post-RA.
19177 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19178 bool Lo = Mask.equals(0, 0);
19181 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19182 // is no slower than UNPCKLPD but has the option to fold the input operand
19183 // into even an unaligned memory load.
19184 if (Lo && Subtarget->hasSSE3()) {
19185 Shuffle = X86ISD::MOVDDUP;
19186 ShuffleVT = MVT::v2f64;
19188 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19189 // than the UNPCK variants.
19190 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19191 ShuffleVT = MVT::v4f32;
19193 if (Depth == 1 && Root->getOpcode() == Shuffle)
19194 return false; // Nothing to do!
19195 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19196 DCI.AddToWorklist(Op.getNode());
19197 if (Shuffle == X86ISD::MOVDDUP)
19198 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19200 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19201 DCI.AddToWorklist(Op.getNode());
19202 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19206 if (Subtarget->hasSSE3() &&
19207 (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
19208 bool Lo = Mask.equals(0, 0, 2, 2);
19209 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19210 MVT ShuffleVT = MVT::v4f32;
19211 if (Depth == 1 && Root->getOpcode() == Shuffle)
19212 return false; // Nothing to do!
19213 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19214 DCI.AddToWorklist(Op.getNode());
19215 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19216 DCI.AddToWorklist(Op.getNode());
19217 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19221 if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
19222 bool Lo = Mask.equals(0, 0, 1, 1);
19223 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19224 MVT ShuffleVT = MVT::v4f32;
19225 if (Depth == 1 && Root->getOpcode() == Shuffle)
19226 return false; // Nothing to do!
19227 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19228 DCI.AddToWorklist(Op.getNode());
19229 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19230 DCI.AddToWorklist(Op.getNode());
19231 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19237 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19238 // variants as none of these have single-instruction variants that are
19239 // superior to the UNPCK formulation.
19240 if (!FloatDomain &&
19241 (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19242 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19243 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19244 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19246 bool Lo = Mask[0] == 0;
19247 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19248 if (Depth == 1 && Root->getOpcode() == Shuffle)
19249 return false; // Nothing to do!
19251 switch (Mask.size()) {
19253 ShuffleVT = MVT::v8i16;
19256 ShuffleVT = MVT::v16i8;
19259 llvm_unreachable("Impossible mask size!");
19261 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19262 DCI.AddToWorklist(Op.getNode());
19263 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19264 DCI.AddToWorklist(Op.getNode());
19265 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19270 // Don't try to re-form single instruction chains under any circumstances now
19271 // that we've done encoding canonicalization for them.
19275 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19276 // can replace them with a single PSHUFB instruction profitably. Intel's
19277 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19278 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19279 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19280 SmallVector<SDValue, 16> PSHUFBMask;
19281 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19282 int Ratio = 16 / Mask.size();
19283 for (unsigned i = 0; i < 16; ++i) {
19284 if (Mask[i / Ratio] == SM_SentinelUndef) {
19285 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19288 int M = Mask[i / Ratio] != SM_SentinelZero
19289 ? Ratio * Mask[i / Ratio] + i % Ratio
19291 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19293 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19294 DCI.AddToWorklist(Op.getNode());
19295 SDValue PSHUFBMaskOp =
19296 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19297 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19298 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19299 DCI.AddToWorklist(Op.getNode());
19300 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19305 // Failed to find any combines.
19309 /// \brief Fully generic combining of x86 shuffle instructions.
19311 /// This should be the last combine run over the x86 shuffle instructions. Once
19312 /// they have been fully optimized, this will recursively consider all chains
19313 /// of single-use shuffle instructions, build a generic model of the cumulative
19314 /// shuffle operation, and check for simpler instructions which implement this
19315 /// operation. We use this primarily for two purposes:
19317 /// 1) Collapse generic shuffles to specialized single instructions when
19318 /// equivalent. In most cases, this is just an encoding size win, but
19319 /// sometimes we will collapse multiple generic shuffles into a single
19320 /// special-purpose shuffle.
19321 /// 2) Look for sequences of shuffle instructions with 3 or more total
19322 /// instructions, and replace them with the slightly more expensive SSSE3
19323 /// PSHUFB instruction if available. We do this as the last combining step
19324 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19325 /// a suitable short sequence of other instructions. The PHUFB will either
19326 /// use a register or have to read from memory and so is slightly (but only
19327 /// slightly) more expensive than the other shuffle instructions.
19329 /// Because this is inherently a quadratic operation (for each shuffle in
19330 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19331 /// This should never be an issue in practice as the shuffle lowering doesn't
19332 /// produce sequences of more than 8 instructions.
19334 /// FIXME: We will currently miss some cases where the redundant shuffling
19335 /// would simplify under the threshold for PSHUFB formation because of
19336 /// combine-ordering. To fix this, we should do the redundant instruction
19337 /// combining in this recursive walk.
19338 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19339 ArrayRef<int> RootMask,
19340 int Depth, bool HasPSHUFB,
19342 TargetLowering::DAGCombinerInfo &DCI,
19343 const X86Subtarget *Subtarget) {
19344 // Bound the depth of our recursive combine because this is ultimately
19345 // quadratic in nature.
19349 // Directly rip through bitcasts to find the underlying operand.
19350 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19351 Op = Op.getOperand(0);
19353 MVT VT = Op.getSimpleValueType();
19354 if (!VT.isVector())
19355 return false; // Bail if we hit a non-vector.
19356 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19357 // version should be added.
19358 if (VT.getSizeInBits() != 128)
19361 assert(Root.getSimpleValueType().isVector() &&
19362 "Shuffles operate on vector types!");
19363 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19364 "Can only combine shuffles of the same vector register size.");
19366 if (!isTargetShuffle(Op.getOpcode()))
19368 SmallVector<int, 16> OpMask;
19370 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19371 // We only can combine unary shuffles which we can decode the mask for.
19372 if (!HaveMask || !IsUnary)
19375 assert(VT.getVectorNumElements() == OpMask.size() &&
19376 "Different mask size from vector size!");
19377 assert(((RootMask.size() > OpMask.size() &&
19378 RootMask.size() % OpMask.size() == 0) ||
19379 (OpMask.size() > RootMask.size() &&
19380 OpMask.size() % RootMask.size() == 0) ||
19381 OpMask.size() == RootMask.size()) &&
19382 "The smaller number of elements must divide the larger.");
19383 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19384 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19385 assert(((RootRatio == 1 && OpRatio == 1) ||
19386 (RootRatio == 1) != (OpRatio == 1)) &&
19387 "Must not have a ratio for both incoming and op masks!");
19389 SmallVector<int, 16> Mask;
19390 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19392 // Merge this shuffle operation's mask into our accumulated mask. Note that
19393 // this shuffle's mask will be the first applied to the input, followed by the
19394 // root mask to get us all the way to the root value arrangement. The reason
19395 // for this order is that we are recursing up the operation chain.
19396 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19397 int RootIdx = i / RootRatio;
19398 if (RootMask[RootIdx] < 0) {
19399 // This is a zero or undef lane, we're done.
19400 Mask.push_back(RootMask[RootIdx]);
19404 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19405 int OpIdx = RootMaskedIdx / OpRatio;
19406 if (OpMask[OpIdx] < 0) {
19407 // The incoming lanes are zero or undef, it doesn't matter which ones we
19409 Mask.push_back(OpMask[OpIdx]);
19413 // Ok, we have non-zero lanes, map them through.
19414 Mask.push_back(OpMask[OpIdx] * OpRatio +
19415 RootMaskedIdx % OpRatio);
19418 // See if we can recurse into the operand to combine more things.
19419 switch (Op.getOpcode()) {
19420 case X86ISD::PSHUFB:
19422 case X86ISD::PSHUFD:
19423 case X86ISD::PSHUFHW:
19424 case X86ISD::PSHUFLW:
19425 if (Op.getOperand(0).hasOneUse() &&
19426 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19427 HasPSHUFB, DAG, DCI, Subtarget))
19431 case X86ISD::UNPCKL:
19432 case X86ISD::UNPCKH:
19433 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19434 // We can't check for single use, we have to check that this shuffle is the only user.
19435 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19436 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19437 HasPSHUFB, DAG, DCI, Subtarget))
19442 // Minor canonicalization of the accumulated shuffle mask to make it easier
19443 // to match below. All this does is detect masks with squential pairs of
19444 // elements, and shrink them to the half-width mask. It does this in a loop
19445 // so it will reduce the size of the mask to the minimal width mask which
19446 // performs an equivalent shuffle.
19447 SmallVector<int, 16> WidenedMask;
19448 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19449 Mask = std::move(WidenedMask);
19450 WidenedMask.clear();
19453 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19457 /// \brief Get the PSHUF-style mask from PSHUF node.
19459 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19460 /// PSHUF-style masks that can be reused with such instructions.
19461 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19462 SmallVector<int, 4> Mask;
19464 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19468 switch (N.getOpcode()) {
19469 case X86ISD::PSHUFD:
19471 case X86ISD::PSHUFLW:
19474 case X86ISD::PSHUFHW:
19475 Mask.erase(Mask.begin(), Mask.begin() + 4);
19476 for (int &M : Mask)
19480 llvm_unreachable("No valid shuffle instruction found!");
19484 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19486 /// We walk up the chain and look for a combinable shuffle, skipping over
19487 /// shuffles that we could hoist this shuffle's transformation past without
19488 /// altering anything.
19490 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19492 TargetLowering::DAGCombinerInfo &DCI) {
19493 assert(N.getOpcode() == X86ISD::PSHUFD &&
19494 "Called with something other than an x86 128-bit half shuffle!");
19497 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19498 // of the shuffles in the chain so that we can form a fresh chain to replace
19500 SmallVector<SDValue, 8> Chain;
19501 SDValue V = N.getOperand(0);
19502 for (; V.hasOneUse(); V = V.getOperand(0)) {
19503 switch (V.getOpcode()) {
19505 return SDValue(); // Nothing combined!
19508 // Skip bitcasts as we always know the type for the target specific
19512 case X86ISD::PSHUFD:
19513 // Found another dword shuffle.
19516 case X86ISD::PSHUFLW:
19517 // Check that the low words (being shuffled) are the identity in the
19518 // dword shuffle, and the high words are self-contained.
19519 if (Mask[0] != 0 || Mask[1] != 1 ||
19520 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19523 Chain.push_back(V);
19526 case X86ISD::PSHUFHW:
19527 // Check that the high words (being shuffled) are the identity in the
19528 // dword shuffle, and the low words are self-contained.
19529 if (Mask[2] != 2 || Mask[3] != 3 ||
19530 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19533 Chain.push_back(V);
19536 case X86ISD::UNPCKL:
19537 case X86ISD::UNPCKH:
19538 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19539 // shuffle into a preceding word shuffle.
19540 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19543 // Search for a half-shuffle which we can combine with.
19544 unsigned CombineOp =
19545 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19546 if (V.getOperand(0) != V.getOperand(1) ||
19547 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19549 Chain.push_back(V);
19550 V = V.getOperand(0);
19552 switch (V.getOpcode()) {
19554 return SDValue(); // Nothing to combine.
19556 case X86ISD::PSHUFLW:
19557 case X86ISD::PSHUFHW:
19558 if (V.getOpcode() == CombineOp)
19561 Chain.push_back(V);
19565 V = V.getOperand(0);
19569 } while (V.hasOneUse());
19572 // Break out of the loop if we break out of the switch.
19576 if (!V.hasOneUse())
19577 // We fell out of the loop without finding a viable combining instruction.
19580 // Merge this node's mask and our incoming mask.
19581 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19582 for (int &M : Mask)
19584 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19585 getV4X86ShuffleImm8ForMask(Mask, DAG));
19587 // Rebuild the chain around this new shuffle.
19588 while (!Chain.empty()) {
19589 SDValue W = Chain.pop_back_val();
19591 if (V.getValueType() != W.getOperand(0).getValueType())
19592 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19594 switch (W.getOpcode()) {
19596 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19598 case X86ISD::UNPCKL:
19599 case X86ISD::UNPCKH:
19600 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19603 case X86ISD::PSHUFD:
19604 case X86ISD::PSHUFLW:
19605 case X86ISD::PSHUFHW:
19606 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19610 if (V.getValueType() != N.getValueType())
19611 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19613 // Return the new chain to replace N.
19617 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19619 /// We walk up the chain, skipping shuffles of the other half and looking
19620 /// through shuffles which switch halves trying to find a shuffle of the same
19621 /// pair of dwords.
19622 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19624 TargetLowering::DAGCombinerInfo &DCI) {
19626 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19627 "Called with something other than an x86 128-bit half shuffle!");
19629 unsigned CombineOpcode = N.getOpcode();
19631 // Walk up a single-use chain looking for a combinable shuffle.
19632 SDValue V = N.getOperand(0);
19633 for (; V.hasOneUse(); V = V.getOperand(0)) {
19634 switch (V.getOpcode()) {
19636 return false; // Nothing combined!
19639 // Skip bitcasts as we always know the type for the target specific
19643 case X86ISD::PSHUFLW:
19644 case X86ISD::PSHUFHW:
19645 if (V.getOpcode() == CombineOpcode)
19648 // Other-half shuffles are no-ops.
19651 // Break out of the loop if we break out of the switch.
19655 if (!V.hasOneUse())
19656 // We fell out of the loop without finding a viable combining instruction.
19659 // Combine away the bottom node as its shuffle will be accumulated into
19660 // a preceding shuffle.
19661 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19663 // Record the old value.
19666 // Merge this node's mask and our incoming mask (adjusted to account for all
19667 // the pshufd instructions encountered).
19668 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19669 for (int &M : Mask)
19671 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19672 getV4X86ShuffleImm8ForMask(Mask, DAG));
19674 // Check that the shuffles didn't cancel each other out. If not, we need to
19675 // combine to the new one.
19677 // Replace the combinable shuffle with the combined one, updating all users
19678 // so that we re-evaluate the chain here.
19679 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19684 /// \brief Try to combine x86 target specific shuffles.
19685 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19686 TargetLowering::DAGCombinerInfo &DCI,
19687 const X86Subtarget *Subtarget) {
19689 MVT VT = N.getSimpleValueType();
19690 SmallVector<int, 4> Mask;
19692 switch (N.getOpcode()) {
19693 case X86ISD::PSHUFD:
19694 case X86ISD::PSHUFLW:
19695 case X86ISD::PSHUFHW:
19696 Mask = getPSHUFShuffleMask(N);
19697 assert(Mask.size() == 4);
19703 // Nuke no-op shuffles that show up after combining.
19704 if (isNoopShuffleMask(Mask))
19705 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19707 // Look for simplifications involving one or two shuffle instructions.
19708 SDValue V = N.getOperand(0);
19709 switch (N.getOpcode()) {
19712 case X86ISD::PSHUFLW:
19713 case X86ISD::PSHUFHW:
19714 assert(VT == MVT::v8i16);
19717 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19718 return SDValue(); // We combined away this shuffle, so we're done.
19720 // See if this reduces to a PSHUFD which is no more expensive and can
19721 // combine with more operations. Note that it has to at least flip the
19722 // dwords as otherwise it would have been removed as a no-op.
19723 if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
19724 int DMask[] = {0, 1, 2, 3};
19725 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19726 DMask[DOffset + 0] = DOffset + 1;
19727 DMask[DOffset + 1] = DOffset + 0;
19728 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19729 DCI.AddToWorklist(V.getNode());
19730 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19731 getV4X86ShuffleImm8ForMask(DMask, DAG));
19732 DCI.AddToWorklist(V.getNode());
19733 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19736 // Look for shuffle patterns which can be implemented as a single unpack.
19737 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19738 // only works when we have a PSHUFD followed by two half-shuffles.
19739 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19740 (V.getOpcode() == X86ISD::PSHUFLW ||
19741 V.getOpcode() == X86ISD::PSHUFHW) &&
19742 V.getOpcode() != N.getOpcode() &&
19744 SDValue D = V.getOperand(0);
19745 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19746 D = D.getOperand(0);
19747 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19748 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19749 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19750 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19751 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19753 for (int i = 0; i < 4; ++i) {
19754 WordMask[i + NOffset] = Mask[i] + NOffset;
19755 WordMask[i + VOffset] = VMask[i] + VOffset;
19757 // Map the word mask through the DWord mask.
19759 for (int i = 0; i < 8; ++i)
19760 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19761 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19762 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19763 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19764 std::begin(UnpackLoMask)) ||
19765 std::equal(std::begin(MappedMask), std::end(MappedMask),
19766 std::begin(UnpackHiMask))) {
19767 // We can replace all three shuffles with an unpack.
19768 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19769 DCI.AddToWorklist(V.getNode());
19770 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19772 DL, MVT::v8i16, V, V);
19779 case X86ISD::PSHUFD:
19780 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19789 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19791 /// We combine this directly on the abstract vector shuffle nodes so it is
19792 /// easier to generically match. We also insert dummy vector shuffle nodes for
19793 /// the operands which explicitly discard the lanes which are unused by this
19794 /// operation to try to flow through the rest of the combiner the fact that
19795 /// they're unused.
19796 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
19798 EVT VT = N->getValueType(0);
19800 // We only handle target-independent shuffles.
19801 // FIXME: It would be easy and harmless to use the target shuffle mask
19802 // extraction tool to support more.
19803 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
19806 auto *SVN = cast<ShuffleVectorSDNode>(N);
19807 ArrayRef<int> Mask = SVN->getMask();
19808 SDValue V1 = N->getOperand(0);
19809 SDValue V2 = N->getOperand(1);
19811 // We require the first shuffle operand to be the SUB node, and the second to
19812 // be the ADD node.
19813 // FIXME: We should support the commuted patterns.
19814 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
19817 // If there are other uses of these operations we can't fold them.
19818 if (!V1->hasOneUse() || !V2->hasOneUse())
19821 // Ensure that both operations have the same operands. Note that we can
19822 // commute the FADD operands.
19823 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
19824 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
19825 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
19828 // We're looking for blends between FADD and FSUB nodes. We insist on these
19829 // nodes being lined up in a specific expected pattern.
19830 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
19831 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
19832 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
19835 // Only specific types are legal at this point, assert so we notice if and
19836 // when these change.
19837 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
19838 VT == MVT::v4f64) &&
19839 "Unknown vector type encountered!");
19841 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
19844 /// PerformShuffleCombine - Performs several different shuffle combines.
19845 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19846 TargetLowering::DAGCombinerInfo &DCI,
19847 const X86Subtarget *Subtarget) {
19849 SDValue N0 = N->getOperand(0);
19850 SDValue N1 = N->getOperand(1);
19851 EVT VT = N->getValueType(0);
19853 // Don't create instructions with illegal types after legalize types has run.
19854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19855 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19858 // If we have legalized the vector types, look for blends of FADD and FSUB
19859 // nodes that we can fuse into an ADDSUB node.
19860 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
19861 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
19864 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19865 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19866 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19867 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19869 // During Type Legalization, when promoting illegal vector types,
19870 // the backend might introduce new shuffle dag nodes and bitcasts.
19872 // This code performs the following transformation:
19873 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19874 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19876 // We do this only if both the bitcast and the BINOP dag nodes have
19877 // one use. Also, perform this transformation only if the new binary
19878 // operation is legal. This is to avoid introducing dag nodes that
19879 // potentially need to be further expanded (or custom lowered) into a
19880 // less optimal sequence of dag nodes.
19881 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19882 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19883 N0.getOpcode() == ISD::BITCAST) {
19884 SDValue BC0 = N0.getOperand(0);
19885 EVT SVT = BC0.getValueType();
19886 unsigned Opcode = BC0.getOpcode();
19887 unsigned NumElts = VT.getVectorNumElements();
19889 if (BC0.hasOneUse() && SVT.isVector() &&
19890 SVT.getVectorNumElements() * 2 == NumElts &&
19891 TLI.isOperationLegal(Opcode, VT)) {
19892 bool CanFold = false;
19904 unsigned SVTNumElts = SVT.getVectorNumElements();
19905 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19906 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19907 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19908 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19909 CanFold = SVOp->getMaskElt(i) < 0;
19912 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19913 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19914 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19915 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19920 // Only handle 128 wide vector from here on.
19921 if (!VT.is128BitVector())
19924 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19925 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19926 // consecutive, non-overlapping, and in the right order.
19927 SmallVector<SDValue, 16> Elts;
19928 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19929 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19931 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19935 if (isTargetShuffle(N->getOpcode())) {
19937 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19938 if (Shuffle.getNode())
19941 // Try recursively combining arbitrary sequences of x86 shuffle
19942 // instructions into higher-order shuffles. We do this after combining
19943 // specific PSHUF instruction sequences into their minimal form so that we
19944 // can evaluate how many specialized shuffle instructions are involved in
19945 // a particular chain.
19946 SmallVector<int, 1> NonceMask; // Just a placeholder.
19947 NonceMask.push_back(0);
19948 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19949 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19951 return SDValue(); // This routine will use CombineTo to replace N.
19957 /// PerformTruncateCombine - Converts truncate operation to
19958 /// a sequence of vector shuffle operations.
19959 /// It is possible when we truncate 256-bit vector to 128-bit vector
19960 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19961 TargetLowering::DAGCombinerInfo &DCI,
19962 const X86Subtarget *Subtarget) {
19966 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19967 /// specific shuffle of a load can be folded into a single element load.
19968 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19969 /// shuffles have been custom lowered so we need to handle those here.
19970 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19971 TargetLowering::DAGCombinerInfo &DCI) {
19972 if (DCI.isBeforeLegalizeOps())
19975 SDValue InVec = N->getOperand(0);
19976 SDValue EltNo = N->getOperand(1);
19978 if (!isa<ConstantSDNode>(EltNo))
19981 EVT OriginalVT = InVec.getValueType();
19983 if (InVec.getOpcode() == ISD::BITCAST) {
19984 // Don't duplicate a load with other uses.
19985 if (!InVec.hasOneUse())
19987 EVT BCVT = InVec.getOperand(0).getValueType();
19988 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
19990 InVec = InVec.getOperand(0);
19993 EVT CurrentVT = InVec.getValueType();
19995 if (!isTargetShuffle(InVec.getOpcode()))
19998 // Don't duplicate a load with other uses.
19999 if (!InVec.hasOneUse())
20002 SmallVector<int, 16> ShuffleMask;
20004 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20005 ShuffleMask, UnaryShuffle))
20008 // Select the input vector, guarding against out of range extract vector.
20009 unsigned NumElems = CurrentVT.getVectorNumElements();
20010 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20011 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20012 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20013 : InVec.getOperand(1);
20015 // If inputs to shuffle are the same for both ops, then allow 2 uses
20016 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20017 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20019 if (LdNode.getOpcode() == ISD::BITCAST) {
20020 // Don't duplicate a load with other uses.
20021 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20024 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20025 LdNode = LdNode.getOperand(0);
20028 if (!ISD::isNormalLoad(LdNode.getNode()))
20031 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20033 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20036 EVT EltVT = N->getValueType(0);
20037 // If there's a bitcast before the shuffle, check if the load type and
20038 // alignment is valid.
20039 unsigned Align = LN0->getAlignment();
20040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20041 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20042 EltVT.getTypeForEVT(*DAG.getContext()));
20044 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20047 // All checks match so transform back to vector_shuffle so that DAG combiner
20048 // can finish the job
20051 // Create shuffle node taking into account the case that its a unary shuffle
20052 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20053 : InVec.getOperand(1);
20054 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20055 InVec.getOperand(0), Shuffle,
20057 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20058 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20062 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20063 /// special and don't usually play with other vector types, it's better to
20064 /// handle them early to be sure we emit efficient code by avoiding
20065 /// store-load conversions.
20066 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20067 if (N->getValueType(0) != MVT::x86mmx ||
20068 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20069 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20072 SDValue V = N->getOperand(0);
20073 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20074 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20075 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20076 N->getValueType(0), V.getOperand(0));
20081 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20082 /// generation and convert it from being a bunch of shuffles and extracts
20083 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20084 /// storing the value and loading scalars back, while for x64 we should
20085 /// use 64-bit extracts and shifts.
20086 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20087 TargetLowering::DAGCombinerInfo &DCI) {
20088 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20089 if (NewOp.getNode())
20092 SDValue InputVector = N->getOperand(0);
20094 // Detect mmx to i32 conversion through a v2i32 elt extract.
20095 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20096 N->getValueType(0) == MVT::i32 &&
20097 InputVector.getValueType() == MVT::v2i32) {
20099 // The bitcast source is a direct mmx result.
20100 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20101 if (MMXSrc.getValueType() == MVT::x86mmx)
20102 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20103 N->getValueType(0),
20104 InputVector.getNode()->getOperand(0));
20106 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20107 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20108 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20109 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20110 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20111 MMXSrcOp.getValueType() == MVT::v1i64 &&
20112 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20113 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20114 N->getValueType(0),
20115 MMXSrcOp.getOperand(0));
20118 // Only operate on vectors of 4 elements, where the alternative shuffling
20119 // gets to be more expensive.
20120 if (InputVector.getValueType() != MVT::v4i32)
20123 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20124 // single use which is a sign-extend or zero-extend, and all elements are
20126 SmallVector<SDNode *, 4> Uses;
20127 unsigned ExtractedElements = 0;
20128 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20129 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20130 if (UI.getUse().getResNo() != InputVector.getResNo())
20133 SDNode *Extract = *UI;
20134 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20137 if (Extract->getValueType(0) != MVT::i32)
20139 if (!Extract->hasOneUse())
20141 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20142 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20144 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20147 // Record which element was extracted.
20148 ExtractedElements |=
20149 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20151 Uses.push_back(Extract);
20154 // If not all the elements were used, this may not be worthwhile.
20155 if (ExtractedElements != 15)
20158 // Ok, we've now decided to do the transformation.
20159 // If 64-bit shifts are legal, use the extract-shift sequence,
20160 // otherwise bounce the vector off the cache.
20161 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20163 SDLoc dl(InputVector);
20165 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20166 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20167 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20168 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20169 DAG.getConstant(0, VecIdxTy));
20170 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20171 DAG.getConstant(1, VecIdxTy));
20173 SDValue ShAmt = DAG.getConstant(32,
20174 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20175 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20176 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20177 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20178 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20179 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20180 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20182 // Store the value to a temporary stack slot.
20183 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20184 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20185 MachinePointerInfo(), false, false, 0);
20187 EVT ElementType = InputVector.getValueType().getVectorElementType();
20188 unsigned EltSize = ElementType.getSizeInBits() / 8;
20190 // Replace each use (extract) with a load of the appropriate element.
20191 for (unsigned i = 0; i < 4; ++i) {
20192 uint64_t Offset = EltSize * i;
20193 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20195 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20196 StackPtr, OffsetVal);
20198 // Load the scalar.
20199 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20200 ScalarAddr, MachinePointerInfo(),
20201 false, false, false, 0);
20206 // Replace the extracts
20207 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20208 UE = Uses.end(); UI != UE; ++UI) {
20209 SDNode *Extract = *UI;
20211 SDValue Idx = Extract->getOperand(1);
20212 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20213 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20216 // The replacement was made in place; don't return anything.
20220 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20221 static std::pair<unsigned, bool>
20222 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20223 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20224 if (!VT.isVector())
20225 return std::make_pair(0, false);
20227 bool NeedSplit = false;
20228 switch (VT.getSimpleVT().SimpleTy) {
20229 default: return std::make_pair(0, false);
20232 if (!Subtarget->hasVLX())
20233 return std::make_pair(0, false);
20237 if (!Subtarget->hasBWI())
20238 return std::make_pair(0, false);
20242 if (!Subtarget->hasAVX512())
20243 return std::make_pair(0, false);
20248 if (!Subtarget->hasAVX2())
20250 if (!Subtarget->hasAVX())
20251 return std::make_pair(0, false);
20256 if (!Subtarget->hasSSE2())
20257 return std::make_pair(0, false);
20260 // SSE2 has only a small subset of the operations.
20261 bool hasUnsigned = Subtarget->hasSSE41() ||
20262 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20263 bool hasSigned = Subtarget->hasSSE41() ||
20264 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20266 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20269 // Check for x CC y ? x : y.
20270 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20271 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20276 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20279 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20282 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20285 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20287 // Check for x CC y ? y : x -- a min/max with reversed arms.
20288 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20289 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20294 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20297 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20300 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20303 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20307 return std::make_pair(Opc, NeedSplit);
20311 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20312 const X86Subtarget *Subtarget) {
20314 SDValue Cond = N->getOperand(0);
20315 SDValue LHS = N->getOperand(1);
20316 SDValue RHS = N->getOperand(2);
20318 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20319 SDValue CondSrc = Cond->getOperand(0);
20320 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20321 Cond = CondSrc->getOperand(0);
20324 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20327 // A vselect where all conditions and data are constants can be optimized into
20328 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20329 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20330 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20333 unsigned MaskValue = 0;
20334 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20337 MVT VT = N->getSimpleValueType(0);
20338 unsigned NumElems = VT.getVectorNumElements();
20339 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20340 for (unsigned i = 0; i < NumElems; ++i) {
20341 // Be sure we emit undef where we can.
20342 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20343 ShuffleMask[i] = -1;
20345 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20348 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20349 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20351 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20354 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20356 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20357 TargetLowering::DAGCombinerInfo &DCI,
20358 const X86Subtarget *Subtarget) {
20360 SDValue Cond = N->getOperand(0);
20361 // Get the LHS/RHS of the select.
20362 SDValue LHS = N->getOperand(1);
20363 SDValue RHS = N->getOperand(2);
20364 EVT VT = LHS.getValueType();
20365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20367 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20368 // instructions match the semantics of the common C idiom x<y?x:y but not
20369 // x<=y?x:y, because of how they handle negative zero (which can be
20370 // ignored in unsafe-math mode).
20371 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20372 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20373 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20374 (Subtarget->hasSSE2() ||
20375 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20376 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20378 unsigned Opcode = 0;
20379 // Check for x CC y ? x : y.
20380 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20381 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20385 // Converting this to a min would handle NaNs incorrectly, and swapping
20386 // the operands would cause it to handle comparisons between positive
20387 // and negative zero incorrectly.
20388 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20389 if (!DAG.getTarget().Options.UnsafeFPMath &&
20390 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20392 std::swap(LHS, RHS);
20394 Opcode = X86ISD::FMIN;
20397 // Converting this to a min would handle comparisons between positive
20398 // and negative zero incorrectly.
20399 if (!DAG.getTarget().Options.UnsafeFPMath &&
20400 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20402 Opcode = X86ISD::FMIN;
20405 // Converting this to a min would handle both negative zeros and NaNs
20406 // incorrectly, but we can swap the operands to fix both.
20407 std::swap(LHS, RHS);
20411 Opcode = X86ISD::FMIN;
20415 // Converting this to a max would handle comparisons between positive
20416 // and negative zero incorrectly.
20417 if (!DAG.getTarget().Options.UnsafeFPMath &&
20418 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20420 Opcode = X86ISD::FMAX;
20423 // Converting this to a max would handle NaNs incorrectly, and swapping
20424 // the operands would cause it to handle comparisons between positive
20425 // and negative zero incorrectly.
20426 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20427 if (!DAG.getTarget().Options.UnsafeFPMath &&
20428 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20430 std::swap(LHS, RHS);
20432 Opcode = X86ISD::FMAX;
20435 // Converting this to a max would handle both negative zeros and NaNs
20436 // incorrectly, but we can swap the operands to fix both.
20437 std::swap(LHS, RHS);
20441 Opcode = X86ISD::FMAX;
20444 // Check for x CC y ? y : x -- a min/max with reversed arms.
20445 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20446 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20450 // Converting this to a min would handle comparisons between positive
20451 // and negative zero incorrectly, and swapping the operands would
20452 // cause it to handle NaNs incorrectly.
20453 if (!DAG.getTarget().Options.UnsafeFPMath &&
20454 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20455 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20457 std::swap(LHS, RHS);
20459 Opcode = X86ISD::FMIN;
20462 // Converting this to a min would handle NaNs incorrectly.
20463 if (!DAG.getTarget().Options.UnsafeFPMath &&
20464 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20466 Opcode = X86ISD::FMIN;
20469 // Converting this to a min would handle both negative zeros and NaNs
20470 // incorrectly, but we can swap the operands to fix both.
20471 std::swap(LHS, RHS);
20475 Opcode = X86ISD::FMIN;
20479 // Converting this to a max would handle NaNs incorrectly.
20480 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20482 Opcode = X86ISD::FMAX;
20485 // Converting this to a max would handle comparisons between positive
20486 // and negative zero incorrectly, and swapping the operands would
20487 // cause it to handle NaNs incorrectly.
20488 if (!DAG.getTarget().Options.UnsafeFPMath &&
20489 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20490 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20492 std::swap(LHS, RHS);
20494 Opcode = X86ISD::FMAX;
20497 // Converting this to a max would handle both negative zeros and NaNs
20498 // incorrectly, but we can swap the operands to fix both.
20499 std::swap(LHS, RHS);
20503 Opcode = X86ISD::FMAX;
20509 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20512 EVT CondVT = Cond.getValueType();
20513 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20514 CondVT.getVectorElementType() == MVT::i1) {
20515 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20516 // lowering on KNL. In this case we convert it to
20517 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20518 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20519 // Since SKX these selects have a proper lowering.
20520 EVT OpVT = LHS.getValueType();
20521 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20522 (OpVT.getVectorElementType() == MVT::i8 ||
20523 OpVT.getVectorElementType() == MVT::i16) &&
20524 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20525 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20526 DCI.AddToWorklist(Cond.getNode());
20527 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20530 // If this is a select between two integer constants, try to do some
20532 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20533 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20534 // Don't do this for crazy integer types.
20535 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20536 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20537 // so that TrueC (the true value) is larger than FalseC.
20538 bool NeedsCondInvert = false;
20540 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20541 // Efficiently invertible.
20542 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20543 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20544 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20545 NeedsCondInvert = true;
20546 std::swap(TrueC, FalseC);
20549 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20550 if (FalseC->getAPIntValue() == 0 &&
20551 TrueC->getAPIntValue().isPowerOf2()) {
20552 if (NeedsCondInvert) // Invert the condition if needed.
20553 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20554 DAG.getConstant(1, Cond.getValueType()));
20556 // Zero extend the condition if needed.
20557 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20559 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20560 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20561 DAG.getConstant(ShAmt, MVT::i8));
20564 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20565 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20566 if (NeedsCondInvert) // Invert the condition if needed.
20567 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20568 DAG.getConstant(1, Cond.getValueType()));
20570 // Zero extend the condition if needed.
20571 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20572 FalseC->getValueType(0), Cond);
20573 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20574 SDValue(FalseC, 0));
20577 // Optimize cases that will turn into an LEA instruction. This requires
20578 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20579 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20580 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20581 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20583 bool isFastMultiplier = false;
20585 switch ((unsigned char)Diff) {
20587 case 1: // result = add base, cond
20588 case 2: // result = lea base( , cond*2)
20589 case 3: // result = lea base(cond, cond*2)
20590 case 4: // result = lea base( , cond*4)
20591 case 5: // result = lea base(cond, cond*4)
20592 case 8: // result = lea base( , cond*8)
20593 case 9: // result = lea base(cond, cond*8)
20594 isFastMultiplier = true;
20599 if (isFastMultiplier) {
20600 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20601 if (NeedsCondInvert) // Invert the condition if needed.
20602 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20603 DAG.getConstant(1, Cond.getValueType()));
20605 // Zero extend the condition if needed.
20606 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20608 // Scale the condition by the difference.
20610 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20611 DAG.getConstant(Diff, Cond.getValueType()));
20613 // Add the base if non-zero.
20614 if (FalseC->getAPIntValue() != 0)
20615 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20616 SDValue(FalseC, 0));
20623 // Canonicalize max and min:
20624 // (x > y) ? x : y -> (x >= y) ? x : y
20625 // (x < y) ? x : y -> (x <= y) ? x : y
20626 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20627 // the need for an extra compare
20628 // against zero. e.g.
20629 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20631 // testl %edi, %edi
20633 // cmovgl %edi, %eax
20637 // cmovsl %eax, %edi
20638 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20639 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20640 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20641 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20646 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20647 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20648 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20649 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20654 // Early exit check
20655 if (!TLI.isTypeLegal(VT))
20658 // Match VSELECTs into subs with unsigned saturation.
20659 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20660 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20661 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20662 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20663 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20665 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20666 // left side invert the predicate to simplify logic below.
20668 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20670 CC = ISD::getSetCCInverse(CC, true);
20671 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20675 if (Other.getNode() && Other->getNumOperands() == 2 &&
20676 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20677 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20678 SDValue CondRHS = Cond->getOperand(1);
20680 // Look for a general sub with unsigned saturation first.
20681 // x >= y ? x-y : 0 --> subus x, y
20682 // x > y ? x-y : 0 --> subus x, y
20683 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20684 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20685 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20687 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20688 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20689 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20690 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20691 // If the RHS is a constant we have to reverse the const
20692 // canonicalization.
20693 // x > C-1 ? x+-C : 0 --> subus x, C
20694 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20695 CondRHSConst->getAPIntValue() ==
20696 (-OpRHSConst->getAPIntValue() - 1))
20697 return DAG.getNode(
20698 X86ISD::SUBUS, DL, VT, OpLHS,
20699 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20701 // Another special case: If C was a sign bit, the sub has been
20702 // canonicalized into a xor.
20703 // FIXME: Would it be better to use computeKnownBits to determine
20704 // whether it's safe to decanonicalize the xor?
20705 // x s< 0 ? x^C : 0 --> subus x, C
20706 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20707 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20708 OpRHSConst->getAPIntValue().isSignBit())
20709 // Note that we have to rebuild the RHS constant here to ensure we
20710 // don't rely on particular values of undef lanes.
20711 return DAG.getNode(
20712 X86ISD::SUBUS, DL, VT, OpLHS,
20713 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20718 // Try to match a min/max vector operation.
20719 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20720 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20721 unsigned Opc = ret.first;
20722 bool NeedSplit = ret.second;
20724 if (Opc && NeedSplit) {
20725 unsigned NumElems = VT.getVectorNumElements();
20726 // Extract the LHS vectors
20727 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20728 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20730 // Extract the RHS vectors
20731 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20732 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20734 // Create min/max for each subvector
20735 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20736 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20738 // Merge the result
20739 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20741 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20744 // Simplify vector selection if condition value type matches vselect
20746 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20747 assert(Cond.getValueType().isVector() &&
20748 "vector select expects a vector selector!");
20750 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20751 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20753 // Try invert the condition if true value is not all 1s and false value
20755 if (!TValIsAllOnes && !FValIsAllZeros &&
20756 // Check if the selector will be produced by CMPP*/PCMP*
20757 Cond.getOpcode() == ISD::SETCC &&
20758 // Check if SETCC has already been promoted
20759 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20760 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20761 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20763 if (TValIsAllZeros || FValIsAllOnes) {
20764 SDValue CC = Cond.getOperand(2);
20765 ISD::CondCode NewCC =
20766 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20767 Cond.getOperand(0).getValueType().isInteger());
20768 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20769 std::swap(LHS, RHS);
20770 TValIsAllOnes = FValIsAllOnes;
20771 FValIsAllZeros = TValIsAllZeros;
20775 if (TValIsAllOnes || FValIsAllZeros) {
20778 if (TValIsAllOnes && FValIsAllZeros)
20780 else if (TValIsAllOnes)
20781 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20782 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20783 else if (FValIsAllZeros)
20784 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20785 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20787 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20791 // If we know that this node is legal then we know that it is going to be
20792 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20793 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20794 // to simplify previous instructions.
20795 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20796 !DCI.isBeforeLegalize() &&
20797 // We explicitly check against SSE4.1, v8i16 and v16i16 because, although
20798 // vselect nodes may be marked as Custom, they might only be legal when
20799 // Cond is a build_vector of constants. This will be taken care in
20800 // a later condition.
20801 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) &&
20802 Subtarget->hasSSE41() && VT != MVT::v16i16 && VT != MVT::v8i16) &&
20803 // Don't optimize vector of constants. Those are handled by
20804 // the generic code and all the bits must be properly set for
20805 // the generic optimizer.
20806 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
20807 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20809 // Don't optimize vector selects that map to mask-registers.
20813 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20814 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20816 APInt KnownZero, KnownOne;
20817 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20818 DCI.isBeforeLegalizeOps());
20819 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20820 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
20822 // If we changed the computation somewhere in the DAG, this change
20823 // will affect all users of Cond.
20824 // Make sure it is fine and update all the nodes so that we do not
20825 // use the generic VSELECT anymore. Otherwise, we may perform
20826 // wrong optimizations as we messed up with the actual expectation
20827 // for the vector boolean values.
20828 if (Cond != TLO.Old) {
20829 // Check all uses of that condition operand to check whether it will be
20830 // consumed by non-BLEND instructions, which may depend on all bits are
20832 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20834 if (I->getOpcode() != ISD::VSELECT)
20835 // TODO: Add other opcodes eventually lowered into BLEND.
20838 // Update all the users of the condition, before committing the change,
20839 // so that the VSELECT optimizations that expect the correct vector
20840 // boolean value will not be triggered.
20841 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
20843 DAG.ReplaceAllUsesOfValueWith(
20845 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
20846 Cond, I->getOperand(1), I->getOperand(2)));
20847 DCI.CommitTargetLoweringOpt(TLO);
20850 // At this point, only Cond is changed. Change the condition
20851 // just for N to keep the opportunity to optimize all other
20852 // users their own way.
20853 DAG.ReplaceAllUsesOfValueWith(
20855 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
20856 TLO.New, N->getOperand(1), N->getOperand(2)));
20861 // We should generate an X86ISD::BLENDI from a vselect if its argument
20862 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20863 // constants. This specific pattern gets generated when we split a
20864 // selector for a 512 bit vector in a machine without AVX512 (but with
20865 // 256-bit vectors), during legalization:
20867 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20869 // Iff we find this pattern and the build_vectors are built from
20870 // constants, we translate the vselect into a shuffle_vector that we
20871 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20872 if ((N->getOpcode() == ISD::VSELECT ||
20873 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
20874 !DCI.isBeforeLegalize()) {
20875 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20876 if (Shuffle.getNode())
20883 // Check whether a boolean test is testing a boolean value generated by
20884 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20887 // Simplify the following patterns:
20888 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20889 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20890 // to (Op EFLAGS Cond)
20892 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20893 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20894 // to (Op EFLAGS !Cond)
20896 // where Op could be BRCOND or CMOV.
20898 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20899 // Quit if not CMP and SUB with its value result used.
20900 if (Cmp.getOpcode() != X86ISD::CMP &&
20901 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20904 // Quit if not used as a boolean value.
20905 if (CC != X86::COND_E && CC != X86::COND_NE)
20908 // Check CMP operands. One of them should be 0 or 1 and the other should be
20909 // an SetCC or extended from it.
20910 SDValue Op1 = Cmp.getOperand(0);
20911 SDValue Op2 = Cmp.getOperand(1);
20914 const ConstantSDNode* C = nullptr;
20915 bool needOppositeCond = (CC == X86::COND_E);
20916 bool checkAgainstTrue = false; // Is it a comparison against 1?
20918 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20920 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20922 else // Quit if all operands are not constants.
20925 if (C->getZExtValue() == 1) {
20926 needOppositeCond = !needOppositeCond;
20927 checkAgainstTrue = true;
20928 } else if (C->getZExtValue() != 0)
20929 // Quit if the constant is neither 0 or 1.
20932 bool truncatedToBoolWithAnd = false;
20933 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20934 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20935 SetCC.getOpcode() == ISD::TRUNCATE ||
20936 SetCC.getOpcode() == ISD::AND) {
20937 if (SetCC.getOpcode() == ISD::AND) {
20939 ConstantSDNode *CS;
20940 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20941 CS->getZExtValue() == 1)
20943 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20944 CS->getZExtValue() == 1)
20948 SetCC = SetCC.getOperand(OpIdx);
20949 truncatedToBoolWithAnd = true;
20951 SetCC = SetCC.getOperand(0);
20954 switch (SetCC.getOpcode()) {
20955 case X86ISD::SETCC_CARRY:
20956 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20957 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20958 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20959 // truncated to i1 using 'and'.
20960 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20962 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20963 "Invalid use of SETCC_CARRY!");
20965 case X86ISD::SETCC:
20966 // Set the condition code or opposite one if necessary.
20967 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20968 if (needOppositeCond)
20969 CC = X86::GetOppositeBranchCondition(CC);
20970 return SetCC.getOperand(1);
20971 case X86ISD::CMOV: {
20972 // Check whether false/true value has canonical one, i.e. 0 or 1.
20973 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20974 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20975 // Quit if true value is not a constant.
20978 // Quit if false value is not a constant.
20980 SDValue Op = SetCC.getOperand(0);
20981 // Skip 'zext' or 'trunc' node.
20982 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20983 Op.getOpcode() == ISD::TRUNCATE)
20984 Op = Op.getOperand(0);
20985 // A special case for rdrand/rdseed, where 0 is set if false cond is
20987 if ((Op.getOpcode() != X86ISD::RDRAND &&
20988 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20991 // Quit if false value is not the constant 0 or 1.
20992 bool FValIsFalse = true;
20993 if (FVal && FVal->getZExtValue() != 0) {
20994 if (FVal->getZExtValue() != 1)
20996 // If FVal is 1, opposite cond is needed.
20997 needOppositeCond = !needOppositeCond;
20998 FValIsFalse = false;
21000 // Quit if TVal is not the constant opposite of FVal.
21001 if (FValIsFalse && TVal->getZExtValue() != 1)
21003 if (!FValIsFalse && TVal->getZExtValue() != 0)
21005 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21006 if (needOppositeCond)
21007 CC = X86::GetOppositeBranchCondition(CC);
21008 return SetCC.getOperand(3);
21015 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21016 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21017 TargetLowering::DAGCombinerInfo &DCI,
21018 const X86Subtarget *Subtarget) {
21021 // If the flag operand isn't dead, don't touch this CMOV.
21022 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21025 SDValue FalseOp = N->getOperand(0);
21026 SDValue TrueOp = N->getOperand(1);
21027 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21028 SDValue Cond = N->getOperand(3);
21030 if (CC == X86::COND_E || CC == X86::COND_NE) {
21031 switch (Cond.getOpcode()) {
21035 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21036 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21037 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21043 Flags = checkBoolTestSetCCCombine(Cond, CC);
21044 if (Flags.getNode() &&
21045 // Extra check as FCMOV only supports a subset of X86 cond.
21046 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21047 SDValue Ops[] = { FalseOp, TrueOp,
21048 DAG.getConstant(CC, MVT::i8), Flags };
21049 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21052 // If this is a select between two integer constants, try to do some
21053 // optimizations. Note that the operands are ordered the opposite of SELECT
21055 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21056 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21057 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21058 // larger than FalseC (the false value).
21059 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21060 CC = X86::GetOppositeBranchCondition(CC);
21061 std::swap(TrueC, FalseC);
21062 std::swap(TrueOp, FalseOp);
21065 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21066 // This is efficient for any integer data type (including i8/i16) and
21068 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21069 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21070 DAG.getConstant(CC, MVT::i8), Cond);
21072 // Zero extend the condition if needed.
21073 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21075 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21076 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21077 DAG.getConstant(ShAmt, MVT::i8));
21078 if (N->getNumValues() == 2) // Dead flag value?
21079 return DCI.CombineTo(N, Cond, SDValue());
21083 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21084 // for any integer data type, including i8/i16.
21085 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21086 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21087 DAG.getConstant(CC, MVT::i8), Cond);
21089 // Zero extend the condition if needed.
21090 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21091 FalseC->getValueType(0), Cond);
21092 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21093 SDValue(FalseC, 0));
21095 if (N->getNumValues() == 2) // Dead flag value?
21096 return DCI.CombineTo(N, Cond, SDValue());
21100 // Optimize cases that will turn into an LEA instruction. This requires
21101 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21102 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21103 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21104 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21106 bool isFastMultiplier = false;
21108 switch ((unsigned char)Diff) {
21110 case 1: // result = add base, cond
21111 case 2: // result = lea base( , cond*2)
21112 case 3: // result = lea base(cond, cond*2)
21113 case 4: // result = lea base( , cond*4)
21114 case 5: // result = lea base(cond, cond*4)
21115 case 8: // result = lea base( , cond*8)
21116 case 9: // result = lea base(cond, cond*8)
21117 isFastMultiplier = true;
21122 if (isFastMultiplier) {
21123 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21124 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21125 DAG.getConstant(CC, MVT::i8), Cond);
21126 // Zero extend the condition if needed.
21127 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21129 // Scale the condition by the difference.
21131 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21132 DAG.getConstant(Diff, Cond.getValueType()));
21134 // Add the base if non-zero.
21135 if (FalseC->getAPIntValue() != 0)
21136 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21137 SDValue(FalseC, 0));
21138 if (N->getNumValues() == 2) // Dead flag value?
21139 return DCI.CombineTo(N, Cond, SDValue());
21146 // Handle these cases:
21147 // (select (x != c), e, c) -> select (x != c), e, x),
21148 // (select (x == c), c, e) -> select (x == c), x, e)
21149 // where the c is an integer constant, and the "select" is the combination
21150 // of CMOV and CMP.
21152 // The rationale for this change is that the conditional-move from a constant
21153 // needs two instructions, however, conditional-move from a register needs
21154 // only one instruction.
21156 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21157 // some instruction-combining opportunities. This opt needs to be
21158 // postponed as late as possible.
21160 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21161 // the DCI.xxxx conditions are provided to postpone the optimization as
21162 // late as possible.
21164 ConstantSDNode *CmpAgainst = nullptr;
21165 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21166 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21167 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21169 if (CC == X86::COND_NE &&
21170 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21171 CC = X86::GetOppositeBranchCondition(CC);
21172 std::swap(TrueOp, FalseOp);
21175 if (CC == X86::COND_E &&
21176 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21177 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21178 DAG.getConstant(CC, MVT::i8), Cond };
21179 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21187 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21188 const X86Subtarget *Subtarget) {
21189 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21191 default: return SDValue();
21192 // SSE/AVX/AVX2 blend intrinsics.
21193 case Intrinsic::x86_avx2_pblendvb:
21194 case Intrinsic::x86_avx2_pblendw:
21195 case Intrinsic::x86_avx2_pblendd_128:
21196 case Intrinsic::x86_avx2_pblendd_256:
21197 // Don't try to simplify this intrinsic if we don't have AVX2.
21198 if (!Subtarget->hasAVX2())
21201 case Intrinsic::x86_avx_blend_pd_256:
21202 case Intrinsic::x86_avx_blend_ps_256:
21203 case Intrinsic::x86_avx_blendv_pd_256:
21204 case Intrinsic::x86_avx_blendv_ps_256:
21205 // Don't try to simplify this intrinsic if we don't have AVX.
21206 if (!Subtarget->hasAVX())
21209 case Intrinsic::x86_sse41_pblendw:
21210 case Intrinsic::x86_sse41_blendpd:
21211 case Intrinsic::x86_sse41_blendps:
21212 case Intrinsic::x86_sse41_blendvps:
21213 case Intrinsic::x86_sse41_blendvpd:
21214 case Intrinsic::x86_sse41_pblendvb: {
21215 SDValue Op0 = N->getOperand(1);
21216 SDValue Op1 = N->getOperand(2);
21217 SDValue Mask = N->getOperand(3);
21219 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21220 if (!Subtarget->hasSSE41())
21223 // fold (blend A, A, Mask) -> A
21226 // fold (blend A, B, allZeros) -> A
21227 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21229 // fold (blend A, B, allOnes) -> B
21230 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21233 // Simplify the case where the mask is a constant i32 value.
21234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21235 if (C->isNullValue())
21237 if (C->isAllOnesValue())
21244 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21245 case Intrinsic::x86_sse2_psrai_w:
21246 case Intrinsic::x86_sse2_psrai_d:
21247 case Intrinsic::x86_avx2_psrai_w:
21248 case Intrinsic::x86_avx2_psrai_d:
21249 case Intrinsic::x86_sse2_psra_w:
21250 case Intrinsic::x86_sse2_psra_d:
21251 case Intrinsic::x86_avx2_psra_w:
21252 case Intrinsic::x86_avx2_psra_d: {
21253 SDValue Op0 = N->getOperand(1);
21254 SDValue Op1 = N->getOperand(2);
21255 EVT VT = Op0.getValueType();
21256 assert(VT.isVector() && "Expected a vector type!");
21258 if (isa<BuildVectorSDNode>(Op1))
21259 Op1 = Op1.getOperand(0);
21261 if (!isa<ConstantSDNode>(Op1))
21264 EVT SVT = VT.getVectorElementType();
21265 unsigned SVTBits = SVT.getSizeInBits();
21267 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21268 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21269 uint64_t ShAmt = C.getZExtValue();
21271 // Don't try to convert this shift into a ISD::SRA if the shift
21272 // count is bigger than or equal to the element size.
21273 if (ShAmt >= SVTBits)
21276 // Trivial case: if the shift count is zero, then fold this
21277 // into the first operand.
21281 // Replace this packed shift intrinsic with a target independent
21283 SDValue Splat = DAG.getConstant(C, VT);
21284 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21289 /// PerformMulCombine - Optimize a single multiply with constant into two
21290 /// in order to implement it with two cheaper instructions, e.g.
21291 /// LEA + SHL, LEA + LEA.
21292 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21293 TargetLowering::DAGCombinerInfo &DCI) {
21294 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21297 EVT VT = N->getValueType(0);
21298 if (VT != MVT::i64 && VT != MVT::i32)
21301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21304 uint64_t MulAmt = C->getZExtValue();
21305 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21308 uint64_t MulAmt1 = 0;
21309 uint64_t MulAmt2 = 0;
21310 if ((MulAmt % 9) == 0) {
21312 MulAmt2 = MulAmt / 9;
21313 } else if ((MulAmt % 5) == 0) {
21315 MulAmt2 = MulAmt / 5;
21316 } else if ((MulAmt % 3) == 0) {
21318 MulAmt2 = MulAmt / 3;
21321 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21324 if (isPowerOf2_64(MulAmt2) &&
21325 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21326 // If second multiplifer is pow2, issue it first. We want the multiply by
21327 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21329 std::swap(MulAmt1, MulAmt2);
21332 if (isPowerOf2_64(MulAmt1))
21333 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21334 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21336 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21337 DAG.getConstant(MulAmt1, VT));
21339 if (isPowerOf2_64(MulAmt2))
21340 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21341 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21343 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21344 DAG.getConstant(MulAmt2, VT));
21346 // Do not add new nodes to DAG combiner worklist.
21347 DCI.CombineTo(N, NewMul, false);
21352 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21353 SDValue N0 = N->getOperand(0);
21354 SDValue N1 = N->getOperand(1);
21355 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21356 EVT VT = N0.getValueType();
21358 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21359 // since the result of setcc_c is all zero's or all ones.
21360 if (VT.isInteger() && !VT.isVector() &&
21361 N1C && N0.getOpcode() == ISD::AND &&
21362 N0.getOperand(1).getOpcode() == ISD::Constant) {
21363 SDValue N00 = N0.getOperand(0);
21364 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21365 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21366 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21367 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21368 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21369 APInt ShAmt = N1C->getAPIntValue();
21370 Mask = Mask.shl(ShAmt);
21372 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21373 N00, DAG.getConstant(Mask, VT));
21377 // Hardware support for vector shifts is sparse which makes us scalarize the
21378 // vector operations in many cases. Also, on sandybridge ADD is faster than
21380 // (shl V, 1) -> add V,V
21381 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21382 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21383 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21384 // We shift all of the values by one. In many cases we do not have
21385 // hardware support for this operation. This is better expressed as an ADD
21387 if (N1SplatC->getZExtValue() == 1)
21388 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21394 /// \brief Returns a vector of 0s if the node in input is a vector logical
21395 /// shift by a constant amount which is known to be bigger than or equal
21396 /// to the vector element size in bits.
21397 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21398 const X86Subtarget *Subtarget) {
21399 EVT VT = N->getValueType(0);
21401 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21402 (!Subtarget->hasInt256() ||
21403 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21406 SDValue Amt = N->getOperand(1);
21408 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21409 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21410 APInt ShiftAmt = AmtSplat->getAPIntValue();
21411 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21413 // SSE2/AVX2 logical shifts always return a vector of 0s
21414 // if the shift amount is bigger than or equal to
21415 // the element size. The constant shift amount will be
21416 // encoded as a 8-bit immediate.
21417 if (ShiftAmt.trunc(8).uge(MaxAmount))
21418 return getZeroVector(VT, Subtarget, DAG, DL);
21424 /// PerformShiftCombine - Combine shifts.
21425 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21426 TargetLowering::DAGCombinerInfo &DCI,
21427 const X86Subtarget *Subtarget) {
21428 if (N->getOpcode() == ISD::SHL) {
21429 SDValue V = PerformSHLCombine(N, DAG);
21430 if (V.getNode()) return V;
21433 if (N->getOpcode() != ISD::SRA) {
21434 // Try to fold this logical shift into a zero vector.
21435 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21436 if (V.getNode()) return V;
21442 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21443 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21444 // and friends. Likewise for OR -> CMPNEQSS.
21445 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21446 TargetLowering::DAGCombinerInfo &DCI,
21447 const X86Subtarget *Subtarget) {
21450 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21451 // we're requiring SSE2 for both.
21452 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21453 SDValue N0 = N->getOperand(0);
21454 SDValue N1 = N->getOperand(1);
21455 SDValue CMP0 = N0->getOperand(1);
21456 SDValue CMP1 = N1->getOperand(1);
21459 // The SETCCs should both refer to the same CMP.
21460 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21463 SDValue CMP00 = CMP0->getOperand(0);
21464 SDValue CMP01 = CMP0->getOperand(1);
21465 EVT VT = CMP00.getValueType();
21467 if (VT == MVT::f32 || VT == MVT::f64) {
21468 bool ExpectingFlags = false;
21469 // Check for any users that want flags:
21470 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21471 !ExpectingFlags && UI != UE; ++UI)
21472 switch (UI->getOpcode()) {
21477 ExpectingFlags = true;
21479 case ISD::CopyToReg:
21480 case ISD::SIGN_EXTEND:
21481 case ISD::ZERO_EXTEND:
21482 case ISD::ANY_EXTEND:
21486 if (!ExpectingFlags) {
21487 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21488 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21490 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21491 X86::CondCode tmp = cc0;
21496 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21497 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21498 // FIXME: need symbolic constants for these magic numbers.
21499 // See X86ATTInstPrinter.cpp:printSSECC().
21500 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21501 if (Subtarget->hasAVX512()) {
21502 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21503 CMP01, DAG.getConstant(x86cc, MVT::i8));
21504 if (N->getValueType(0) != MVT::i1)
21505 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21509 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21510 CMP00.getValueType(), CMP00, CMP01,
21511 DAG.getConstant(x86cc, MVT::i8));
21513 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21514 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21516 if (is64BitFP && !Subtarget->is64Bit()) {
21517 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21518 // 64-bit integer, since that's not a legal type. Since
21519 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21520 // bits, but can do this little dance to extract the lowest 32 bits
21521 // and work with those going forward.
21522 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21524 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21526 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21527 Vector32, DAG.getIntPtrConstant(0));
21531 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21532 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21533 DAG.getConstant(1, IntVT));
21534 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21535 return OneBitOfTruth;
21543 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21544 /// so it can be folded inside ANDNP.
21545 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21546 EVT VT = N->getValueType(0);
21548 // Match direct AllOnes for 128 and 256-bit vectors
21549 if (ISD::isBuildVectorAllOnes(N))
21552 // Look through a bit convert.
21553 if (N->getOpcode() == ISD::BITCAST)
21554 N = N->getOperand(0).getNode();
21556 // Sometimes the operand may come from a insert_subvector building a 256-bit
21558 if (VT.is256BitVector() &&
21559 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21560 SDValue V1 = N->getOperand(0);
21561 SDValue V2 = N->getOperand(1);
21563 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21564 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21565 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21566 ISD::isBuildVectorAllOnes(V2.getNode()))
21573 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21574 // register. In most cases we actually compare or select YMM-sized registers
21575 // and mixing the two types creates horrible code. This method optimizes
21576 // some of the transition sequences.
21577 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21578 TargetLowering::DAGCombinerInfo &DCI,
21579 const X86Subtarget *Subtarget) {
21580 EVT VT = N->getValueType(0);
21581 if (!VT.is256BitVector())
21584 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21585 N->getOpcode() == ISD::ZERO_EXTEND ||
21586 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21588 SDValue Narrow = N->getOperand(0);
21589 EVT NarrowVT = Narrow->getValueType(0);
21590 if (!NarrowVT.is128BitVector())
21593 if (Narrow->getOpcode() != ISD::XOR &&
21594 Narrow->getOpcode() != ISD::AND &&
21595 Narrow->getOpcode() != ISD::OR)
21598 SDValue N0 = Narrow->getOperand(0);
21599 SDValue N1 = Narrow->getOperand(1);
21602 // The Left side has to be a trunc.
21603 if (N0.getOpcode() != ISD::TRUNCATE)
21606 // The type of the truncated inputs.
21607 EVT WideVT = N0->getOperand(0)->getValueType(0);
21611 // The right side has to be a 'trunc' or a constant vector.
21612 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21613 ConstantSDNode *RHSConstSplat = nullptr;
21614 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21615 RHSConstSplat = RHSBV->getConstantSplatNode();
21616 if (!RHSTrunc && !RHSConstSplat)
21619 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21621 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21624 // Set N0 and N1 to hold the inputs to the new wide operation.
21625 N0 = N0->getOperand(0);
21626 if (RHSConstSplat) {
21627 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21628 SDValue(RHSConstSplat, 0));
21629 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21630 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21631 } else if (RHSTrunc) {
21632 N1 = N1->getOperand(0);
21635 // Generate the wide operation.
21636 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21637 unsigned Opcode = N->getOpcode();
21639 case ISD::ANY_EXTEND:
21641 case ISD::ZERO_EXTEND: {
21642 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21643 APInt Mask = APInt::getAllOnesValue(InBits);
21644 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21645 return DAG.getNode(ISD::AND, DL, VT,
21646 Op, DAG.getConstant(Mask, VT));
21648 case ISD::SIGN_EXTEND:
21649 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21650 Op, DAG.getValueType(NarrowVT));
21652 llvm_unreachable("Unexpected opcode");
21656 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21657 TargetLowering::DAGCombinerInfo &DCI,
21658 const X86Subtarget *Subtarget) {
21659 SDValue N0 = N->getOperand(0);
21660 SDValue N1 = N->getOperand(1);
21663 // A vector zext_in_reg may be represented as a shuffle,
21664 // feeding into a bitcast (this represents anyext) feeding into
21665 // an and with a mask.
21666 // We'd like to try to combine that into a shuffle with zero
21667 // plus a bitcast, removing the and.
21668 if (N0.getOpcode() != ISD::BITCAST ||
21669 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21672 // The other side of the AND should be a splat of 2^C, where C
21673 // is the number of bits in the source type.
21674 if (N1.getOpcode() == ISD::BITCAST)
21675 N1 = N1.getOperand(0);
21676 if (N1.getOpcode() != ISD::BUILD_VECTOR)
21678 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21680 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21681 EVT SrcType = Shuffle->getValueType(0);
21683 // We expect a single-source shuffle
21684 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21687 unsigned SrcSize = SrcType.getScalarSizeInBits();
21689 APInt SplatValue, SplatUndef;
21690 unsigned SplatBitSize;
21692 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21693 SplatBitSize, HasAnyUndefs))
21696 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21697 // Make sure the splat matches the mask we expect
21698 if (SplatBitSize > ResSize ||
21699 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21702 // Make sure the input and output size make sense
21703 if (SrcSize >= ResSize || ResSize % SrcSize)
21706 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
21707 // The number of u's between each two values depends on the ratio between
21708 // the source and dest type.
21709 unsigned ZextRatio = ResSize / SrcSize;
21710 bool IsZext = true;
21711 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
21712 if (i % ZextRatio) {
21713 if (Shuffle->getMaskElt(i) > 0) {
21719 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
21720 // Expected element number
21730 // Ok, perform the transformation - replace the shuffle with
21731 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
21732 // (instead of undef) where the k elements come from the zero vector.
21733 SmallVector<int, 8> Mask;
21734 unsigned NumElems = SrcType.getVectorNumElements();
21735 for (unsigned i = 0; i < NumElems; ++i)
21737 Mask.push_back(NumElems);
21739 Mask.push_back(i / ZextRatio);
21741 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
21742 Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
21743 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
21746 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21747 TargetLowering::DAGCombinerInfo &DCI,
21748 const X86Subtarget *Subtarget) {
21749 if (DCI.isBeforeLegalizeOps())
21752 SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget);
21753 if (Zext.getNode())
21756 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21760 EVT VT = N->getValueType(0);
21761 SDValue N0 = N->getOperand(0);
21762 SDValue N1 = N->getOperand(1);
21765 // Create BEXTR instructions
21766 // BEXTR is ((X >> imm) & (2**size-1))
21767 if (VT == MVT::i32 || VT == MVT::i64) {
21768 // Check for BEXTR.
21769 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21770 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21771 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21772 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21773 if (MaskNode && ShiftNode) {
21774 uint64_t Mask = MaskNode->getZExtValue();
21775 uint64_t Shift = ShiftNode->getZExtValue();
21776 if (isMask_64(Mask)) {
21777 uint64_t MaskSize = countPopulation(Mask);
21778 if (Shift + MaskSize <= VT.getSizeInBits())
21779 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21780 DAG.getConstant(Shift | (MaskSize << 8), VT));
21788 // Want to form ANDNP nodes:
21789 // 1) In the hopes of then easily combining them with OR and AND nodes
21790 // to form PBLEND/PSIGN.
21791 // 2) To match ANDN packed intrinsics
21792 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21795 // Check LHS for vnot
21796 if (N0.getOpcode() == ISD::XOR &&
21797 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21798 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21799 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21801 // Check RHS for vnot
21802 if (N1.getOpcode() == ISD::XOR &&
21803 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21804 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21805 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21810 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21811 TargetLowering::DAGCombinerInfo &DCI,
21812 const X86Subtarget *Subtarget) {
21813 if (DCI.isBeforeLegalizeOps())
21816 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21820 SDValue N0 = N->getOperand(0);
21821 SDValue N1 = N->getOperand(1);
21822 EVT VT = N->getValueType(0);
21824 // look for psign/blend
21825 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21826 if (!Subtarget->hasSSSE3() ||
21827 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21830 // Canonicalize pandn to RHS
21831 if (N0.getOpcode() == X86ISD::ANDNP)
21833 // or (and (m, y), (pandn m, x))
21834 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21835 SDValue Mask = N1.getOperand(0);
21836 SDValue X = N1.getOperand(1);
21838 if (N0.getOperand(0) == Mask)
21839 Y = N0.getOperand(1);
21840 if (N0.getOperand(1) == Mask)
21841 Y = N0.getOperand(0);
21843 // Check to see if the mask appeared in both the AND and ANDNP and
21847 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21848 // Look through mask bitcast.
21849 if (Mask.getOpcode() == ISD::BITCAST)
21850 Mask = Mask.getOperand(0);
21851 if (X.getOpcode() == ISD::BITCAST)
21852 X = X.getOperand(0);
21853 if (Y.getOpcode() == ISD::BITCAST)
21854 Y = Y.getOperand(0);
21856 EVT MaskVT = Mask.getValueType();
21858 // Validate that the Mask operand is a vector sra node.
21859 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21860 // there is no psrai.b
21861 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21862 unsigned SraAmt = ~0;
21863 if (Mask.getOpcode() == ISD::SRA) {
21864 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21865 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21866 SraAmt = AmtConst->getZExtValue();
21867 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21868 SDValue SraC = Mask.getOperand(1);
21869 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21871 if ((SraAmt + 1) != EltBits)
21876 // Now we know we at least have a plendvb with the mask val. See if
21877 // we can form a psignb/w/d.
21878 // psign = x.type == y.type == mask.type && y = sub(0, x);
21879 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21880 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21881 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21882 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21883 "Unsupported VT for PSIGN");
21884 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21885 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21887 // PBLENDVB only available on SSE 4.1
21888 if (!Subtarget->hasSSE41())
21891 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21893 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21894 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21895 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21896 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21897 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21901 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21904 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21905 MachineFunction &MF = DAG.getMachineFunction();
21907 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
21909 // SHLD/SHRD instructions have lower register pressure, but on some
21910 // platforms they have higher latency than the equivalent
21911 // series of shifts/or that would otherwise be generated.
21912 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21913 // have higher latencies and we are not optimizing for size.
21914 if (!OptForSize && Subtarget->isSHLDSlow())
21917 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21919 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21921 if (!N0.hasOneUse() || !N1.hasOneUse())
21924 SDValue ShAmt0 = N0.getOperand(1);
21925 if (ShAmt0.getValueType() != MVT::i8)
21927 SDValue ShAmt1 = N1.getOperand(1);
21928 if (ShAmt1.getValueType() != MVT::i8)
21930 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21931 ShAmt0 = ShAmt0.getOperand(0);
21932 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21933 ShAmt1 = ShAmt1.getOperand(0);
21936 unsigned Opc = X86ISD::SHLD;
21937 SDValue Op0 = N0.getOperand(0);
21938 SDValue Op1 = N1.getOperand(0);
21939 if (ShAmt0.getOpcode() == ISD::SUB) {
21940 Opc = X86ISD::SHRD;
21941 std::swap(Op0, Op1);
21942 std::swap(ShAmt0, ShAmt1);
21945 unsigned Bits = VT.getSizeInBits();
21946 if (ShAmt1.getOpcode() == ISD::SUB) {
21947 SDValue Sum = ShAmt1.getOperand(0);
21948 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21949 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21950 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21951 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21952 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21953 return DAG.getNode(Opc, DL, VT,
21955 DAG.getNode(ISD::TRUNCATE, DL,
21958 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21959 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21961 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21962 return DAG.getNode(Opc, DL, VT,
21963 N0.getOperand(0), N1.getOperand(0),
21964 DAG.getNode(ISD::TRUNCATE, DL,
21971 // Generate NEG and CMOV for integer abs.
21972 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21973 EVT VT = N->getValueType(0);
21975 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21976 // 8-bit integer abs to NEG and CMOV.
21977 if (VT.isInteger() && VT.getSizeInBits() == 8)
21980 SDValue N0 = N->getOperand(0);
21981 SDValue N1 = N->getOperand(1);
21984 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21985 // and change it to SUB and CMOV.
21986 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21987 N0.getOpcode() == ISD::ADD &&
21988 N0.getOperand(1) == N1 &&
21989 N1.getOpcode() == ISD::SRA &&
21990 N1.getOperand(0) == N0.getOperand(0))
21991 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21992 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21993 // Generate SUB & CMOV.
21994 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21995 DAG.getConstant(0, VT), N0.getOperand(0));
21997 SDValue Ops[] = { N0.getOperand(0), Neg,
21998 DAG.getConstant(X86::COND_GE, MVT::i8),
21999 SDValue(Neg.getNode(), 1) };
22000 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22005 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22006 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22007 TargetLowering::DAGCombinerInfo &DCI,
22008 const X86Subtarget *Subtarget) {
22009 if (DCI.isBeforeLegalizeOps())
22012 if (Subtarget->hasCMov()) {
22013 SDValue RV = performIntegerAbsCombine(N, DAG);
22021 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22022 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22023 TargetLowering::DAGCombinerInfo &DCI,
22024 const X86Subtarget *Subtarget) {
22025 LoadSDNode *Ld = cast<LoadSDNode>(N);
22026 EVT RegVT = Ld->getValueType(0);
22027 EVT MemVT = Ld->getMemoryVT();
22029 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22031 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22032 // into two 16-byte operations.
22033 ISD::LoadExtType Ext = Ld->getExtensionType();
22034 unsigned Alignment = Ld->getAlignment();
22035 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22036 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22037 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22038 unsigned NumElems = RegVT.getVectorNumElements();
22042 SDValue Ptr = Ld->getBasePtr();
22043 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22045 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22047 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22048 Ld->getPointerInfo(), Ld->isVolatile(),
22049 Ld->isNonTemporal(), Ld->isInvariant(),
22051 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22052 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22053 Ld->getPointerInfo(), Ld->isVolatile(),
22054 Ld->isNonTemporal(), Ld->isInvariant(),
22055 std::min(16U, Alignment));
22056 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22058 Load2.getValue(1));
22060 SDValue NewVec = DAG.getUNDEF(RegVT);
22061 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22062 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22063 return DCI.CombineTo(N, NewVec, TF, true);
22069 /// PerformMLOADCombine - Resolve extending loads
22070 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22071 TargetLowering::DAGCombinerInfo &DCI,
22072 const X86Subtarget *Subtarget) {
22073 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22074 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22077 EVT VT = Mld->getValueType(0);
22078 unsigned NumElems = VT.getVectorNumElements();
22079 EVT LdVT = Mld->getMemoryVT();
22082 assert(LdVT != VT && "Cannot extend to the same type");
22083 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22084 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22085 // From, To sizes and ElemCount must be pow of two
22086 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22087 "Unexpected size for extending masked load");
22089 unsigned SizeRatio = ToSz / FromSz;
22090 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22092 // Create a type on which we perform the shuffle
22093 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22094 LdVT.getScalarType(), NumElems*SizeRatio);
22095 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22097 // Convert Src0 value
22098 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22099 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22100 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22101 for (unsigned i = 0; i != NumElems; ++i)
22102 ShuffleVec[i] = i * SizeRatio;
22104 // Can't shuffle using an illegal type.
22105 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22106 && "WideVecVT should be legal");
22107 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22108 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22110 // Prepare the new mask
22112 SDValue Mask = Mld->getMask();
22113 if (Mask.getValueType() == VT) {
22114 // Mask and original value have the same type
22115 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22116 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22117 for (unsigned i = 0; i != NumElems; ++i)
22118 ShuffleVec[i] = i * SizeRatio;
22119 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22120 ShuffleVec[i] = NumElems*SizeRatio;
22121 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22122 DAG.getConstant(0, WideVecVT),
22126 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22127 unsigned WidenNumElts = NumElems*SizeRatio;
22128 unsigned MaskNumElts = VT.getVectorNumElements();
22129 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22132 unsigned NumConcat = WidenNumElts / MaskNumElts;
22133 SmallVector<SDValue, 16> Ops(NumConcat);
22134 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22136 for (unsigned i = 1; i != NumConcat; ++i)
22139 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22142 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22143 Mld->getBasePtr(), NewMask, WideSrc0,
22144 Mld->getMemoryVT(), Mld->getMemOperand(),
22146 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22147 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22150 /// PerformMSTORECombine - Resolve truncating stores
22151 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22152 const X86Subtarget *Subtarget) {
22153 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22154 if (!Mst->isTruncatingStore())
22157 EVT VT = Mst->getValue().getValueType();
22158 unsigned NumElems = VT.getVectorNumElements();
22159 EVT StVT = Mst->getMemoryVT();
22162 assert(StVT != VT && "Cannot truncate to the same type");
22163 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22164 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22166 // From, To sizes and ElemCount must be pow of two
22167 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22168 "Unexpected size for truncating masked store");
22169 // We are going to use the original vector elt for storing.
22170 // Accumulated smaller vector elements must be a multiple of the store size.
22171 assert (((NumElems * FromSz) % ToSz) == 0 &&
22172 "Unexpected ratio for truncating masked store");
22174 unsigned SizeRatio = FromSz / ToSz;
22175 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22177 // Create a type on which we perform the shuffle
22178 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22179 StVT.getScalarType(), NumElems*SizeRatio);
22181 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22183 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22184 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22185 for (unsigned i = 0; i != NumElems; ++i)
22186 ShuffleVec[i] = i * SizeRatio;
22188 // Can't shuffle using an illegal type.
22189 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22190 && "WideVecVT should be legal");
22192 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22193 DAG.getUNDEF(WideVecVT),
22197 SDValue Mask = Mst->getMask();
22198 if (Mask.getValueType() == VT) {
22199 // Mask and original value have the same type
22200 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22201 for (unsigned i = 0; i != NumElems; ++i)
22202 ShuffleVec[i] = i * SizeRatio;
22203 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22204 ShuffleVec[i] = NumElems*SizeRatio;
22205 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22206 DAG.getConstant(0, WideVecVT),
22210 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22211 unsigned WidenNumElts = NumElems*SizeRatio;
22212 unsigned MaskNumElts = VT.getVectorNumElements();
22213 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22216 unsigned NumConcat = WidenNumElts / MaskNumElts;
22217 SmallVector<SDValue, 16> Ops(NumConcat);
22218 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22220 for (unsigned i = 1; i != NumConcat; ++i)
22223 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22226 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22227 NewMask, StVT, Mst->getMemOperand(), false);
22229 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22230 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22231 const X86Subtarget *Subtarget) {
22232 StoreSDNode *St = cast<StoreSDNode>(N);
22233 EVT VT = St->getValue().getValueType();
22234 EVT StVT = St->getMemoryVT();
22236 SDValue StoredVal = St->getOperand(1);
22237 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22239 // If we are saving a concatenation of two XMM registers and 32-byte stores
22240 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22241 unsigned Alignment = St->getAlignment();
22242 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22243 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22244 StVT == VT && !IsAligned) {
22245 unsigned NumElems = VT.getVectorNumElements();
22249 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22250 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22252 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22253 SDValue Ptr0 = St->getBasePtr();
22254 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22256 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22257 St->getPointerInfo(), St->isVolatile(),
22258 St->isNonTemporal(), Alignment);
22259 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22260 St->getPointerInfo(), St->isVolatile(),
22261 St->isNonTemporal(),
22262 std::min(16U, Alignment));
22263 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22266 // Optimize trunc store (of multiple scalars) to shuffle and store.
22267 // First, pack all of the elements in one place. Next, store to memory
22268 // in fewer chunks.
22269 if (St->isTruncatingStore() && VT.isVector()) {
22270 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22271 unsigned NumElems = VT.getVectorNumElements();
22272 assert(StVT != VT && "Cannot truncate to the same type");
22273 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22274 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22276 // From, To sizes and ElemCount must be pow of two
22277 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22278 // We are going to use the original vector elt for storing.
22279 // Accumulated smaller vector elements must be a multiple of the store size.
22280 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22282 unsigned SizeRatio = FromSz / ToSz;
22284 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22286 // Create a type on which we perform the shuffle
22287 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22288 StVT.getScalarType(), NumElems*SizeRatio);
22290 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22292 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22293 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22294 for (unsigned i = 0; i != NumElems; ++i)
22295 ShuffleVec[i] = i * SizeRatio;
22297 // Can't shuffle using an illegal type.
22298 if (!TLI.isTypeLegal(WideVecVT))
22301 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22302 DAG.getUNDEF(WideVecVT),
22304 // At this point all of the data is stored at the bottom of the
22305 // register. We now need to save it to mem.
22307 // Find the largest store unit
22308 MVT StoreType = MVT::i8;
22309 for (MVT Tp : MVT::integer_valuetypes()) {
22310 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22314 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22315 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22316 (64 <= NumElems * ToSz))
22317 StoreType = MVT::f64;
22319 // Bitcast the original vector into a vector of store-size units
22320 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22321 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22322 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22323 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22324 SmallVector<SDValue, 8> Chains;
22325 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22326 TLI.getPointerTy());
22327 SDValue Ptr = St->getBasePtr();
22329 // Perform one or more big stores into memory.
22330 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22331 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22332 StoreType, ShuffWide,
22333 DAG.getIntPtrConstant(i));
22334 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22335 St->getPointerInfo(), St->isVolatile(),
22336 St->isNonTemporal(), St->getAlignment());
22337 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22338 Chains.push_back(Ch);
22341 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22344 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22345 // the FP state in cases where an emms may be missing.
22346 // A preferable solution to the general problem is to figure out the right
22347 // places to insert EMMS. This qualifies as a quick hack.
22349 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22350 if (VT.getSizeInBits() != 64)
22353 const Function *F = DAG.getMachineFunction().getFunction();
22354 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22355 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22356 && Subtarget->hasSSE2();
22357 if ((VT.isVector() ||
22358 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22359 isa<LoadSDNode>(St->getValue()) &&
22360 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22361 St->getChain().hasOneUse() && !St->isVolatile()) {
22362 SDNode* LdVal = St->getValue().getNode();
22363 LoadSDNode *Ld = nullptr;
22364 int TokenFactorIndex = -1;
22365 SmallVector<SDValue, 8> Ops;
22366 SDNode* ChainVal = St->getChain().getNode();
22367 // Must be a store of a load. We currently handle two cases: the load
22368 // is a direct child, and it's under an intervening TokenFactor. It is
22369 // possible to dig deeper under nested TokenFactors.
22370 if (ChainVal == LdVal)
22371 Ld = cast<LoadSDNode>(St->getChain());
22372 else if (St->getValue().hasOneUse() &&
22373 ChainVal->getOpcode() == ISD::TokenFactor) {
22374 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22375 if (ChainVal->getOperand(i).getNode() == LdVal) {
22376 TokenFactorIndex = i;
22377 Ld = cast<LoadSDNode>(St->getValue());
22379 Ops.push_back(ChainVal->getOperand(i));
22383 if (!Ld || !ISD::isNormalLoad(Ld))
22386 // If this is not the MMX case, i.e. we are just turning i64 load/store
22387 // into f64 load/store, avoid the transformation if there are multiple
22388 // uses of the loaded value.
22389 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22394 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22395 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22397 if (Subtarget->is64Bit() || F64IsLegal) {
22398 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22399 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22400 Ld->getPointerInfo(), Ld->isVolatile(),
22401 Ld->isNonTemporal(), Ld->isInvariant(),
22402 Ld->getAlignment());
22403 SDValue NewChain = NewLd.getValue(1);
22404 if (TokenFactorIndex != -1) {
22405 Ops.push_back(NewChain);
22406 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22408 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22409 St->getPointerInfo(),
22410 St->isVolatile(), St->isNonTemporal(),
22411 St->getAlignment());
22414 // Otherwise, lower to two pairs of 32-bit loads / stores.
22415 SDValue LoAddr = Ld->getBasePtr();
22416 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22417 DAG.getConstant(4, MVT::i32));
22419 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22420 Ld->getPointerInfo(),
22421 Ld->isVolatile(), Ld->isNonTemporal(),
22422 Ld->isInvariant(), Ld->getAlignment());
22423 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22424 Ld->getPointerInfo().getWithOffset(4),
22425 Ld->isVolatile(), Ld->isNonTemporal(),
22427 MinAlign(Ld->getAlignment(), 4));
22429 SDValue NewChain = LoLd.getValue(1);
22430 if (TokenFactorIndex != -1) {
22431 Ops.push_back(LoLd);
22432 Ops.push_back(HiLd);
22433 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22436 LoAddr = St->getBasePtr();
22437 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22438 DAG.getConstant(4, MVT::i32));
22440 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22441 St->getPointerInfo(),
22442 St->isVolatile(), St->isNonTemporal(),
22443 St->getAlignment());
22444 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22445 St->getPointerInfo().getWithOffset(4),
22447 St->isNonTemporal(),
22448 MinAlign(St->getAlignment(), 4));
22449 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22454 /// Return 'true' if this vector operation is "horizontal"
22455 /// and return the operands for the horizontal operation in LHS and RHS. A
22456 /// horizontal operation performs the binary operation on successive elements
22457 /// of its first operand, then on successive elements of its second operand,
22458 /// returning the resulting values in a vector. For example, if
22459 /// A = < float a0, float a1, float a2, float a3 >
22461 /// B = < float b0, float b1, float b2, float b3 >
22462 /// then the result of doing a horizontal operation on A and B is
22463 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22464 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22465 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22466 /// set to A, RHS to B, and the routine returns 'true'.
22467 /// Note that the binary operation should have the property that if one of the
22468 /// operands is UNDEF then the result is UNDEF.
22469 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22470 // Look for the following pattern: if
22471 // A = < float a0, float a1, float a2, float a3 >
22472 // B = < float b0, float b1, float b2, float b3 >
22474 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22475 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22476 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22477 // which is A horizontal-op B.
22479 // At least one of the operands should be a vector shuffle.
22480 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22481 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22484 MVT VT = LHS.getSimpleValueType();
22486 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22487 "Unsupported vector type for horizontal add/sub");
22489 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22490 // operate independently on 128-bit lanes.
22491 unsigned NumElts = VT.getVectorNumElements();
22492 unsigned NumLanes = VT.getSizeInBits()/128;
22493 unsigned NumLaneElts = NumElts / NumLanes;
22494 assert((NumLaneElts % 2 == 0) &&
22495 "Vector type should have an even number of elements in each lane");
22496 unsigned HalfLaneElts = NumLaneElts/2;
22498 // View LHS in the form
22499 // LHS = VECTOR_SHUFFLE A, B, LMask
22500 // If LHS is not a shuffle then pretend it is the shuffle
22501 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22502 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22505 SmallVector<int, 16> LMask(NumElts);
22506 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22507 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22508 A = LHS.getOperand(0);
22509 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22510 B = LHS.getOperand(1);
22511 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22512 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22514 if (LHS.getOpcode() != ISD::UNDEF)
22516 for (unsigned i = 0; i != NumElts; ++i)
22520 // Likewise, view RHS in the form
22521 // RHS = VECTOR_SHUFFLE C, D, RMask
22523 SmallVector<int, 16> RMask(NumElts);
22524 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22525 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22526 C = RHS.getOperand(0);
22527 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22528 D = RHS.getOperand(1);
22529 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22530 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22532 if (RHS.getOpcode() != ISD::UNDEF)
22534 for (unsigned i = 0; i != NumElts; ++i)
22538 // Check that the shuffles are both shuffling the same vectors.
22539 if (!(A == C && B == D) && !(A == D && B == C))
22542 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22543 if (!A.getNode() && !B.getNode())
22546 // If A and B occur in reverse order in RHS, then "swap" them (which means
22547 // rewriting the mask).
22549 CommuteVectorShuffleMask(RMask, NumElts);
22551 // At this point LHS and RHS are equivalent to
22552 // LHS = VECTOR_SHUFFLE A, B, LMask
22553 // RHS = VECTOR_SHUFFLE A, B, RMask
22554 // Check that the masks correspond to performing a horizontal operation.
22555 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22556 for (unsigned i = 0; i != NumLaneElts; ++i) {
22557 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22559 // Ignore any UNDEF components.
22560 if (LIdx < 0 || RIdx < 0 ||
22561 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22562 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22565 // Check that successive elements are being operated on. If not, this is
22566 // not a horizontal operation.
22567 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22568 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22569 if (!(LIdx == Index && RIdx == Index + 1) &&
22570 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22575 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22576 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22580 /// Do target-specific dag combines on floating point adds.
22581 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22582 const X86Subtarget *Subtarget) {
22583 EVT VT = N->getValueType(0);
22584 SDValue LHS = N->getOperand(0);
22585 SDValue RHS = N->getOperand(1);
22587 // Try to synthesize horizontal adds from adds of shuffles.
22588 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22589 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22590 isHorizontalBinOp(LHS, RHS, true))
22591 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22595 /// Do target-specific dag combines on floating point subs.
22596 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22597 const X86Subtarget *Subtarget) {
22598 EVT VT = N->getValueType(0);
22599 SDValue LHS = N->getOperand(0);
22600 SDValue RHS = N->getOperand(1);
22602 // Try to synthesize horizontal subs from subs of shuffles.
22603 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22604 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22605 isHorizontalBinOp(LHS, RHS, false))
22606 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22610 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22611 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22612 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22614 // F[X]OR(0.0, x) -> x
22615 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22616 if (C->getValueAPF().isPosZero())
22617 return N->getOperand(1);
22619 // F[X]OR(x, 0.0) -> x
22620 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22621 if (C->getValueAPF().isPosZero())
22622 return N->getOperand(0);
22626 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22627 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22628 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22630 // Only perform optimizations if UnsafeMath is used.
22631 if (!DAG.getTarget().Options.UnsafeFPMath)
22634 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22635 // into FMINC and FMAXC, which are Commutative operations.
22636 unsigned NewOp = 0;
22637 switch (N->getOpcode()) {
22638 default: llvm_unreachable("unknown opcode");
22639 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22640 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22643 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22644 N->getOperand(0), N->getOperand(1));
22647 /// Do target-specific dag combines on X86ISD::FAND nodes.
22648 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22649 // FAND(0.0, x) -> 0.0
22650 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22651 if (C->getValueAPF().isPosZero())
22652 return N->getOperand(0);
22654 // FAND(x, 0.0) -> 0.0
22655 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22656 if (C->getValueAPF().isPosZero())
22657 return N->getOperand(1);
22662 /// Do target-specific dag combines on X86ISD::FANDN nodes
22663 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22664 // FANDN(0.0, x) -> x
22665 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22666 if (C->getValueAPF().isPosZero())
22667 return N->getOperand(1);
22669 // FANDN(x, 0.0) -> 0.0
22670 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22671 if (C->getValueAPF().isPosZero())
22672 return N->getOperand(1);
22677 static SDValue PerformBTCombine(SDNode *N,
22679 TargetLowering::DAGCombinerInfo &DCI) {
22680 // BT ignores high bits in the bit index operand.
22681 SDValue Op1 = N->getOperand(1);
22682 if (Op1.hasOneUse()) {
22683 unsigned BitWidth = Op1.getValueSizeInBits();
22684 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22685 APInt KnownZero, KnownOne;
22686 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22687 !DCI.isBeforeLegalizeOps());
22688 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22689 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22690 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22691 DCI.CommitTargetLoweringOpt(TLO);
22696 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22697 SDValue Op = N->getOperand(0);
22698 if (Op.getOpcode() == ISD::BITCAST)
22699 Op = Op.getOperand(0);
22700 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22701 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22702 VT.getVectorElementType().getSizeInBits() ==
22703 OpVT.getVectorElementType().getSizeInBits()) {
22704 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22709 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22710 const X86Subtarget *Subtarget) {
22711 EVT VT = N->getValueType(0);
22712 if (!VT.isVector())
22715 SDValue N0 = N->getOperand(0);
22716 SDValue N1 = N->getOperand(1);
22717 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22720 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22721 // both SSE and AVX2 since there is no sign-extended shift right
22722 // operation on a vector with 64-bit elements.
22723 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22724 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22725 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22726 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22727 SDValue N00 = N0.getOperand(0);
22729 // EXTLOAD has a better solution on AVX2,
22730 // it may be replaced with X86ISD::VSEXT node.
22731 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22732 if (!ISD::isNormalLoad(N00.getNode()))
22735 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22736 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22738 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22744 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22745 TargetLowering::DAGCombinerInfo &DCI,
22746 const X86Subtarget *Subtarget) {
22747 SDValue N0 = N->getOperand(0);
22748 EVT VT = N->getValueType(0);
22750 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
22751 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
22752 // This exposes the sext to the sdivrem lowering, so that it directly extends
22753 // from AH (which we otherwise need to do contortions to access).
22754 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
22755 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
22757 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22758 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
22759 N0.getOperand(0), N0.getOperand(1));
22760 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22761 return R.getValue(1);
22764 if (!DCI.isBeforeLegalizeOps())
22767 if (!Subtarget->hasFp256())
22770 if (VT.isVector() && VT.getSizeInBits() == 256) {
22771 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22779 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22780 const X86Subtarget* Subtarget) {
22782 EVT VT = N->getValueType(0);
22784 // Let legalize expand this if it isn't a legal type yet.
22785 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22788 EVT ScalarVT = VT.getScalarType();
22789 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22790 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22793 SDValue A = N->getOperand(0);
22794 SDValue B = N->getOperand(1);
22795 SDValue C = N->getOperand(2);
22797 bool NegA = (A.getOpcode() == ISD::FNEG);
22798 bool NegB = (B.getOpcode() == ISD::FNEG);
22799 bool NegC = (C.getOpcode() == ISD::FNEG);
22801 // Negative multiplication when NegA xor NegB
22802 bool NegMul = (NegA != NegB);
22804 A = A.getOperand(0);
22806 B = B.getOperand(0);
22808 C = C.getOperand(0);
22812 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22814 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22816 return DAG.getNode(Opcode, dl, VT, A, B, C);
22819 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22820 TargetLowering::DAGCombinerInfo &DCI,
22821 const X86Subtarget *Subtarget) {
22822 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22823 // (and (i32 x86isd::setcc_carry), 1)
22824 // This eliminates the zext. This transformation is necessary because
22825 // ISD::SETCC is always legalized to i8.
22827 SDValue N0 = N->getOperand(0);
22828 EVT VT = N->getValueType(0);
22830 if (N0.getOpcode() == ISD::AND &&
22832 N0.getOperand(0).hasOneUse()) {
22833 SDValue N00 = N0.getOperand(0);
22834 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22835 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22836 if (!C || C->getZExtValue() != 1)
22838 return DAG.getNode(ISD::AND, dl, VT,
22839 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22840 N00.getOperand(0), N00.getOperand(1)),
22841 DAG.getConstant(1, VT));
22845 if (N0.getOpcode() == ISD::TRUNCATE &&
22847 N0.getOperand(0).hasOneUse()) {
22848 SDValue N00 = N0.getOperand(0);
22849 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22850 return DAG.getNode(ISD::AND, dl, VT,
22851 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22852 N00.getOperand(0), N00.getOperand(1)),
22853 DAG.getConstant(1, VT));
22856 if (VT.is256BitVector()) {
22857 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22862 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
22863 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
22864 // This exposes the zext to the udivrem lowering, so that it directly extends
22865 // from AH (which we otherwise need to do contortions to access).
22866 if (N0.getOpcode() == ISD::UDIVREM &&
22867 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
22868 (VT == MVT::i32 || VT == MVT::i64)) {
22869 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
22870 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
22871 N0.getOperand(0), N0.getOperand(1));
22872 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
22873 return R.getValue(1);
22879 // Optimize x == -y --> x+y == 0
22880 // x != -y --> x+y != 0
22881 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22882 const X86Subtarget* Subtarget) {
22883 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22884 SDValue LHS = N->getOperand(0);
22885 SDValue RHS = N->getOperand(1);
22886 EVT VT = N->getValueType(0);
22889 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22891 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22892 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22893 LHS.getValueType(), RHS, LHS.getOperand(1));
22894 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22895 addV, DAG.getConstant(0, addV.getValueType()), CC);
22897 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22898 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22899 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22900 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22901 RHS.getValueType(), LHS, RHS.getOperand(1));
22902 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22903 addV, DAG.getConstant(0, addV.getValueType()), CC);
22906 if (VT.getScalarType() == MVT::i1) {
22907 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22908 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22909 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22910 if (!IsSEXT0 && !IsVZero0)
22912 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22913 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22914 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22916 if (!IsSEXT1 && !IsVZero1)
22919 if (IsSEXT0 && IsVZero1) {
22920 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22921 if (CC == ISD::SETEQ)
22922 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22923 return LHS.getOperand(0);
22925 if (IsSEXT1 && IsVZero0) {
22926 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22927 if (CC == ISD::SETEQ)
22928 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22929 return RHS.getOperand(0);
22936 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
22937 SelectionDAG &DAG) {
22939 MVT VT = Load->getSimpleValueType(0);
22940 MVT EVT = VT.getVectorElementType();
22941 SDValue Addr = Load->getOperand(1);
22942 SDValue NewAddr = DAG.getNode(
22943 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
22944 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
22947 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
22948 DAG.getMachineFunction().getMachineMemOperand(
22949 Load->getMemOperand(), 0, EVT.getStoreSize()));
22953 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22954 const X86Subtarget *Subtarget) {
22956 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22957 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22958 "X86insertps is only defined for v4x32");
22960 SDValue Ld = N->getOperand(1);
22961 if (MayFoldLoad(Ld)) {
22962 // Extract the countS bits from the immediate so we can get the proper
22963 // address when narrowing the vector load to a specific element.
22964 // When the second source op is a memory address, interps doesn't use
22965 // countS and just gets an f32 from that address.
22966 unsigned DestIndex =
22967 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22968 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22972 // Create this as a scalar to vector to match the instruction pattern.
22973 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22974 // countS bits are ignored when loading from memory on insertps, which
22975 // means we don't need to explicitly set them to 0.
22976 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22977 LoadScalarToVector, N->getOperand(2));
22980 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
22981 SDValue V0 = N->getOperand(0);
22982 SDValue V1 = N->getOperand(1);
22984 EVT VT = N->getValueType(0);
22986 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
22987 // operands and changing the mask to 1. This saves us a bunch of
22988 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
22989 // x86InstrInfo knows how to commute this back after instruction selection
22990 // if it would help register allocation.
22992 // TODO: If optimizing for size or a processor that doesn't suffer from
22993 // partial register update stalls, this should be transformed into a MOVSD
22994 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
22996 if (VT == MVT::v2f64)
22997 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
22998 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
22999 SDValue NewMask = DAG.getConstant(1, MVT::i8);
23000 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23006 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23007 // as "sbb reg,reg", since it can be extended without zext and produces
23008 // an all-ones bit which is more useful than 0/1 in some cases.
23009 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23012 return DAG.getNode(ISD::AND, DL, VT,
23013 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23014 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23015 DAG.getConstant(1, VT));
23016 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23017 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23018 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23019 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23022 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23023 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23024 TargetLowering::DAGCombinerInfo &DCI,
23025 const X86Subtarget *Subtarget) {
23027 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23028 SDValue EFLAGS = N->getOperand(1);
23030 if (CC == X86::COND_A) {
23031 // Try to convert COND_A into COND_B in an attempt to facilitate
23032 // materializing "setb reg".
23034 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23035 // cannot take an immediate as its first operand.
23037 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23038 EFLAGS.getValueType().isInteger() &&
23039 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23040 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23041 EFLAGS.getNode()->getVTList(),
23042 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23043 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23044 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23048 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23049 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23051 if (CC == X86::COND_B)
23052 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23056 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23057 if (Flags.getNode()) {
23058 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23059 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23065 // Optimize branch condition evaluation.
23067 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23068 TargetLowering::DAGCombinerInfo &DCI,
23069 const X86Subtarget *Subtarget) {
23071 SDValue Chain = N->getOperand(0);
23072 SDValue Dest = N->getOperand(1);
23073 SDValue EFLAGS = N->getOperand(3);
23074 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23078 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23079 if (Flags.getNode()) {
23080 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23081 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23088 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23089 SelectionDAG &DAG) {
23090 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23091 // optimize away operation when it's from a constant.
23093 // The general transformation is:
23094 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23095 // AND(VECTOR_CMP(x,y), constant2)
23096 // constant2 = UNARYOP(constant)
23098 // Early exit if this isn't a vector operation, the operand of the
23099 // unary operation isn't a bitwise AND, or if the sizes of the operations
23100 // aren't the same.
23101 EVT VT = N->getValueType(0);
23102 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23103 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23104 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23107 // Now check that the other operand of the AND is a constant. We could
23108 // make the transformation for non-constant splats as well, but it's unclear
23109 // that would be a benefit as it would not eliminate any operations, just
23110 // perform one more step in scalar code before moving to the vector unit.
23111 if (BuildVectorSDNode *BV =
23112 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23113 // Bail out if the vector isn't a constant.
23114 if (!BV->isConstant())
23117 // Everything checks out. Build up the new and improved node.
23119 EVT IntVT = BV->getValueType(0);
23120 // Create a new constant of the appropriate type for the transformed
23122 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23123 // The AND node needs bitcasts to/from an integer vector type around it.
23124 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23125 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23126 N->getOperand(0)->getOperand(0), MaskConst);
23127 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23134 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23135 const X86Subtarget *Subtarget) {
23136 // First try to optimize away the conversion entirely when it's
23137 // conditionally from a constant. Vectors only.
23138 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23139 if (Res != SDValue())
23142 // Now move on to more general possibilities.
23143 SDValue Op0 = N->getOperand(0);
23144 EVT InVT = Op0->getValueType(0);
23146 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23147 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23149 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23150 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23151 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23154 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23155 // a 32-bit target where SSE doesn't support i64->FP operations.
23156 if (Op0.getOpcode() == ISD::LOAD) {
23157 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23158 EVT VT = Ld->getValueType(0);
23159 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23160 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23161 !Subtarget->is64Bit() && VT == MVT::i64) {
23162 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23163 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23164 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23171 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23172 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23173 X86TargetLowering::DAGCombinerInfo &DCI) {
23174 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23175 // the result is either zero or one (depending on the input carry bit).
23176 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23177 if (X86::isZeroNode(N->getOperand(0)) &&
23178 X86::isZeroNode(N->getOperand(1)) &&
23179 // We don't have a good way to replace an EFLAGS use, so only do this when
23181 SDValue(N, 1).use_empty()) {
23183 EVT VT = N->getValueType(0);
23184 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23185 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23186 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23187 DAG.getConstant(X86::COND_B,MVT::i8),
23189 DAG.getConstant(1, VT));
23190 return DCI.CombineTo(N, Res1, CarryOut);
23196 // fold (add Y, (sete X, 0)) -> adc 0, Y
23197 // (add Y, (setne X, 0)) -> sbb -1, Y
23198 // (sub (sete X, 0), Y) -> sbb 0, Y
23199 // (sub (setne X, 0), Y) -> adc -1, Y
23200 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23203 // Look through ZExts.
23204 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23205 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23208 SDValue SetCC = Ext.getOperand(0);
23209 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23212 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23213 if (CC != X86::COND_E && CC != X86::COND_NE)
23216 SDValue Cmp = SetCC.getOperand(1);
23217 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23218 !X86::isZeroNode(Cmp.getOperand(1)) ||
23219 !Cmp.getOperand(0).getValueType().isInteger())
23222 SDValue CmpOp0 = Cmp.getOperand(0);
23223 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23224 DAG.getConstant(1, CmpOp0.getValueType()));
23226 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23227 if (CC == X86::COND_NE)
23228 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23229 DL, OtherVal.getValueType(), OtherVal,
23230 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23231 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23232 DL, OtherVal.getValueType(), OtherVal,
23233 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23236 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23237 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23238 const X86Subtarget *Subtarget) {
23239 EVT VT = N->getValueType(0);
23240 SDValue Op0 = N->getOperand(0);
23241 SDValue Op1 = N->getOperand(1);
23243 // Try to synthesize horizontal adds from adds of shuffles.
23244 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23245 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23246 isHorizontalBinOp(Op0, Op1, true))
23247 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23249 return OptimizeConditionalInDecrement(N, DAG);
23252 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23253 const X86Subtarget *Subtarget) {
23254 SDValue Op0 = N->getOperand(0);
23255 SDValue Op1 = N->getOperand(1);
23257 // X86 can't encode an immediate LHS of a sub. See if we can push the
23258 // negation into a preceding instruction.
23259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23260 // If the RHS of the sub is a XOR with one use and a constant, invert the
23261 // immediate. Then add one to the LHS of the sub so we can turn
23262 // X-Y -> X+~Y+1, saving one register.
23263 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23264 isa<ConstantSDNode>(Op1.getOperand(1))) {
23265 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23266 EVT VT = Op0.getValueType();
23267 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23269 DAG.getConstant(~XorC, VT));
23270 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23271 DAG.getConstant(C->getAPIntValue()+1, VT));
23275 // Try to synthesize horizontal adds from adds of shuffles.
23276 EVT VT = N->getValueType(0);
23277 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23278 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23279 isHorizontalBinOp(Op0, Op1, true))
23280 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23282 return OptimizeConditionalInDecrement(N, DAG);
23285 /// performVZEXTCombine - Performs build vector combines
23286 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23287 TargetLowering::DAGCombinerInfo &DCI,
23288 const X86Subtarget *Subtarget) {
23290 MVT VT = N->getSimpleValueType(0);
23291 SDValue Op = N->getOperand(0);
23292 MVT OpVT = Op.getSimpleValueType();
23293 MVT OpEltVT = OpVT.getVectorElementType();
23294 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23296 // (vzext (bitcast (vzext (x)) -> (vzext x)
23298 while (V.getOpcode() == ISD::BITCAST)
23299 V = V.getOperand(0);
23301 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23302 MVT InnerVT = V.getSimpleValueType();
23303 MVT InnerEltVT = InnerVT.getVectorElementType();
23305 // If the element sizes match exactly, we can just do one larger vzext. This
23306 // is always an exact type match as vzext operates on integer types.
23307 if (OpEltVT == InnerEltVT) {
23308 assert(OpVT == InnerVT && "Types must match for vzext!");
23309 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23312 // The only other way we can combine them is if only a single element of the
23313 // inner vzext is used in the input to the outer vzext.
23314 if (InnerEltVT.getSizeInBits() < InputBits)
23317 // In this case, the inner vzext is completely dead because we're going to
23318 // only look at bits inside of the low element. Just do the outer vzext on
23319 // a bitcast of the input to the inner.
23320 return DAG.getNode(X86ISD::VZEXT, DL, VT,
23321 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23324 // Check if we can bypass extracting and re-inserting an element of an input
23325 // vector. Essentialy:
23326 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23327 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23328 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23329 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23330 SDValue ExtractedV = V.getOperand(0);
23331 SDValue OrigV = ExtractedV.getOperand(0);
23332 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23333 if (ExtractIdx->getZExtValue() == 0) {
23334 MVT OrigVT = OrigV.getSimpleValueType();
23335 // Extract a subvector if necessary...
23336 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23337 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23338 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23339 OrigVT.getVectorNumElements() / Ratio);
23340 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23341 DAG.getIntPtrConstant(0));
23343 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23344 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23351 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23352 DAGCombinerInfo &DCI) const {
23353 SelectionDAG &DAG = DCI.DAG;
23354 switch (N->getOpcode()) {
23356 case ISD::EXTRACT_VECTOR_ELT:
23357 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23360 case X86ISD::SHRUNKBLEND:
23361 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23362 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
23363 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23364 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23365 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23366 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23367 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23370 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23371 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23372 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23373 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23374 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23375 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23376 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23377 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
23378 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23379 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23380 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23382 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23384 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23385 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23386 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23387 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23388 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23389 case ISD::ANY_EXTEND:
23390 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23391 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23392 case ISD::SIGN_EXTEND_INREG:
23393 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23394 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23395 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23396 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23397 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23398 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23399 case X86ISD::SHUFP: // Handle all target specific shuffles
23400 case X86ISD::PALIGNR:
23401 case X86ISD::UNPCKH:
23402 case X86ISD::UNPCKL:
23403 case X86ISD::MOVHLPS:
23404 case X86ISD::MOVLHPS:
23405 case X86ISD::PSHUFB:
23406 case X86ISD::PSHUFD:
23407 case X86ISD::PSHUFHW:
23408 case X86ISD::PSHUFLW:
23409 case X86ISD::MOVSS:
23410 case X86ISD::MOVSD:
23411 case X86ISD::VPERMILPI:
23412 case X86ISD::VPERM2X128:
23413 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23414 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23415 case ISD::INTRINSIC_WO_CHAIN:
23416 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23417 case X86ISD::INSERTPS: {
23418 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23419 return PerformINSERTPSCombine(N, DAG, Subtarget);
23422 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
23423 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23429 /// isTypeDesirableForOp - Return true if the target has native support for
23430 /// the specified value type and it is 'desirable' to use the type for the
23431 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23432 /// instruction encodings are longer and some i16 instructions are slow.
23433 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23434 if (!isTypeLegal(VT))
23436 if (VT != MVT::i16)
23443 case ISD::SIGN_EXTEND:
23444 case ISD::ZERO_EXTEND:
23445 case ISD::ANY_EXTEND:
23458 /// IsDesirableToPromoteOp - This method query the target whether it is
23459 /// beneficial for dag combiner to promote the specified node. If true, it
23460 /// should return the desired promotion type by reference.
23461 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23462 EVT VT = Op.getValueType();
23463 if (VT != MVT::i16)
23466 bool Promote = false;
23467 bool Commute = false;
23468 switch (Op.getOpcode()) {
23471 LoadSDNode *LD = cast<LoadSDNode>(Op);
23472 // If the non-extending load has a single use and it's not live out, then it
23473 // might be folded.
23474 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23475 Op.hasOneUse()*/) {
23476 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23477 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23478 // The only case where we'd want to promote LOAD (rather then it being
23479 // promoted as an operand is when it's only use is liveout.
23480 if (UI->getOpcode() != ISD::CopyToReg)
23487 case ISD::SIGN_EXTEND:
23488 case ISD::ZERO_EXTEND:
23489 case ISD::ANY_EXTEND:
23494 SDValue N0 = Op.getOperand(0);
23495 // Look out for (store (shl (load), x)).
23496 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23509 SDValue N0 = Op.getOperand(0);
23510 SDValue N1 = Op.getOperand(1);
23511 if (!Commute && MayFoldLoad(N1))
23513 // Avoid disabling potential load folding opportunities.
23514 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23516 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23526 //===----------------------------------------------------------------------===//
23527 // X86 Inline Assembly Support
23528 //===----------------------------------------------------------------------===//
23531 // Helper to match a string separated by whitespace.
23532 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23533 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23535 for (unsigned i = 0, e = args.size(); i != e; ++i) {
23536 StringRef piece(*args[i]);
23537 if (!s.startswith(piece)) // Check if the piece matches.
23540 s = s.substr(piece.size());
23541 StringRef::size_type pos = s.find_first_not_of(" \t");
23542 if (pos == 0) // We matched a prefix.
23550 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23553 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23555 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23556 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23557 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23558 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23560 if (AsmPieces.size() == 3)
23562 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23569 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23570 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23572 std::string AsmStr = IA->getAsmString();
23574 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23575 if (!Ty || Ty->getBitWidth() % 16 != 0)
23578 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23579 SmallVector<StringRef, 4> AsmPieces;
23580 SplitString(AsmStr, AsmPieces, ";\n");
23582 switch (AsmPieces.size()) {
23583 default: return false;
23585 // FIXME: this should verify that we are targeting a 486 or better. If not,
23586 // we will turn this bswap into something that will be lowered to logical
23587 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23588 // lower so don't worry about this.
23590 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23591 matchAsm(AsmPieces[0], "bswapl", "$0") ||
23592 matchAsm(AsmPieces[0], "bswapq", "$0") ||
23593 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23594 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23595 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23596 // No need to check constraints, nothing other than the equivalent of
23597 // "=r,0" would be valid here.
23598 return IntrinsicLowering::LowerToByteSwap(CI);
23601 // rorw $$8, ${0:w} --> llvm.bswap.i16
23602 if (CI->getType()->isIntegerTy(16) &&
23603 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23604 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23605 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23607 const std::string &ConstraintsStr = IA->getConstraintString();
23608 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23609 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23610 if (clobbersFlagRegisters(AsmPieces))
23611 return IntrinsicLowering::LowerToByteSwap(CI);
23615 if (CI->getType()->isIntegerTy(32) &&
23616 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23617 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23618 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23619 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23621 const std::string &ConstraintsStr = IA->getConstraintString();
23622 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23623 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23624 if (clobbersFlagRegisters(AsmPieces))
23625 return IntrinsicLowering::LowerToByteSwap(CI);
23628 if (CI->getType()->isIntegerTy(64)) {
23629 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23630 if (Constraints.size() >= 2 &&
23631 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23632 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23633 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23634 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23635 matchAsm(AsmPieces[1], "bswap", "%edx") &&
23636 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23637 return IntrinsicLowering::LowerToByteSwap(CI);
23645 /// getConstraintType - Given a constraint letter, return the type of
23646 /// constraint it is for this target.
23647 X86TargetLowering::ConstraintType
23648 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23649 if (Constraint.size() == 1) {
23650 switch (Constraint[0]) {
23661 return C_RegisterClass;
23685 return TargetLowering::getConstraintType(Constraint);
23688 /// Examine constraint type and operand type and determine a weight value.
23689 /// This object must already have been set up with the operand type
23690 /// and the current alternative constraint selected.
23691 TargetLowering::ConstraintWeight
23692 X86TargetLowering::getSingleConstraintMatchWeight(
23693 AsmOperandInfo &info, const char *constraint) const {
23694 ConstraintWeight weight = CW_Invalid;
23695 Value *CallOperandVal = info.CallOperandVal;
23696 // If we don't have a value, we can't do a match,
23697 // but allow it at the lowest weight.
23698 if (!CallOperandVal)
23700 Type *type = CallOperandVal->getType();
23701 // Look at the constraint type.
23702 switch (*constraint) {
23704 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23715 if (CallOperandVal->getType()->isIntegerTy())
23716 weight = CW_SpecificReg;
23721 if (type->isFloatingPointTy())
23722 weight = CW_SpecificReg;
23725 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23726 weight = CW_SpecificReg;
23730 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23731 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23732 weight = CW_Register;
23735 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23736 if (C->getZExtValue() <= 31)
23737 weight = CW_Constant;
23741 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23742 if (C->getZExtValue() <= 63)
23743 weight = CW_Constant;
23747 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23748 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23749 weight = CW_Constant;
23753 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23754 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23755 weight = CW_Constant;
23759 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23760 if (C->getZExtValue() <= 3)
23761 weight = CW_Constant;
23765 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23766 if (C->getZExtValue() <= 0xff)
23767 weight = CW_Constant;
23772 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23773 weight = CW_Constant;
23777 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23778 if ((C->getSExtValue() >= -0x80000000LL) &&
23779 (C->getSExtValue() <= 0x7fffffffLL))
23780 weight = CW_Constant;
23784 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23785 if (C->getZExtValue() <= 0xffffffff)
23786 weight = CW_Constant;
23793 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23794 /// with another that has more specific requirements based on the type of the
23795 /// corresponding operand.
23796 const char *X86TargetLowering::
23797 LowerXConstraint(EVT ConstraintVT) const {
23798 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23799 // 'f' like normal targets.
23800 if (ConstraintVT.isFloatingPoint()) {
23801 if (Subtarget->hasSSE2())
23803 if (Subtarget->hasSSE1())
23807 return TargetLowering::LowerXConstraint(ConstraintVT);
23810 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23811 /// vector. If it is invalid, don't add anything to Ops.
23812 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23813 std::string &Constraint,
23814 std::vector<SDValue>&Ops,
23815 SelectionDAG &DAG) const {
23818 // Only support length 1 constraints for now.
23819 if (Constraint.length() > 1) return;
23821 char ConstraintLetter = Constraint[0];
23822 switch (ConstraintLetter) {
23825 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23826 if (C->getZExtValue() <= 31) {
23827 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23833 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23834 if (C->getZExtValue() <= 63) {
23835 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23841 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23842 if (isInt<8>(C->getSExtValue())) {
23843 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23850 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
23851 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
23852 Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
23858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23859 if (C->getZExtValue() <= 3) {
23860 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23866 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23867 if (C->getZExtValue() <= 255) {
23868 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23875 if (C->getZExtValue() <= 127) {
23876 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23882 // 32-bit signed value
23883 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23884 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23885 C->getSExtValue())) {
23886 // Widen to 64 bits here to get it sign extended.
23887 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23890 // FIXME gcc accepts some relocatable values here too, but only in certain
23891 // memory models; it's complicated.
23896 // 32-bit unsigned value
23897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23898 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23899 C->getZExtValue())) {
23900 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23904 // FIXME gcc accepts some relocatable values here too, but only in certain
23905 // memory models; it's complicated.
23909 // Literal immediates are always ok.
23910 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23911 // Widen to 64 bits here to get it sign extended.
23912 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23916 // In any sort of PIC mode addresses need to be computed at runtime by
23917 // adding in a register or some sort of table lookup. These can't
23918 // be used as immediates.
23919 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23922 // If we are in non-pic codegen mode, we allow the address of a global (with
23923 // an optional displacement) to be used with 'i'.
23924 GlobalAddressSDNode *GA = nullptr;
23925 int64_t Offset = 0;
23927 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23929 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23930 Offset += GA->getOffset();
23932 } else if (Op.getOpcode() == ISD::ADD) {
23933 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23934 Offset += C->getZExtValue();
23935 Op = Op.getOperand(0);
23938 } else if (Op.getOpcode() == ISD::SUB) {
23939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23940 Offset += -C->getZExtValue();
23941 Op = Op.getOperand(0);
23946 // Otherwise, this isn't something we can handle, reject it.
23950 const GlobalValue *GV = GA->getGlobal();
23951 // If we require an extra load to get this address, as in PIC mode, we
23952 // can't accept it.
23953 if (isGlobalStubReference(
23954 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23957 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23958 GA->getValueType(0), Offset);
23963 if (Result.getNode()) {
23964 Ops.push_back(Result);
23967 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23970 std::pair<unsigned, const TargetRegisterClass*>
23971 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23973 // First, see if this is a constraint that directly corresponds to an LLVM
23975 if (Constraint.size() == 1) {
23976 // GCC Constraint Letters
23977 switch (Constraint[0]) {
23979 // TODO: Slight differences here in allocation order and leaving
23980 // RIP in the class. Do they matter any more here than they do
23981 // in the normal allocation?
23982 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23983 if (Subtarget->is64Bit()) {
23984 if (VT == MVT::i32 || VT == MVT::f32)
23985 return std::make_pair(0U, &X86::GR32RegClass);
23986 if (VT == MVT::i16)
23987 return std::make_pair(0U, &X86::GR16RegClass);
23988 if (VT == MVT::i8 || VT == MVT::i1)
23989 return std::make_pair(0U, &X86::GR8RegClass);
23990 if (VT == MVT::i64 || VT == MVT::f64)
23991 return std::make_pair(0U, &X86::GR64RegClass);
23994 // 32-bit fallthrough
23995 case 'Q': // Q_REGS
23996 if (VT == MVT::i32 || VT == MVT::f32)
23997 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23998 if (VT == MVT::i16)
23999 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24000 if (VT == MVT::i8 || VT == MVT::i1)
24001 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24002 if (VT == MVT::i64)
24003 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24005 case 'r': // GENERAL_REGS
24006 case 'l': // INDEX_REGS
24007 if (VT == MVT::i8 || VT == MVT::i1)
24008 return std::make_pair(0U, &X86::GR8RegClass);
24009 if (VT == MVT::i16)
24010 return std::make_pair(0U, &X86::GR16RegClass);
24011 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24012 return std::make_pair(0U, &X86::GR32RegClass);
24013 return std::make_pair(0U, &X86::GR64RegClass);
24014 case 'R': // LEGACY_REGS
24015 if (VT == MVT::i8 || VT == MVT::i1)
24016 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24017 if (VT == MVT::i16)
24018 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24019 if (VT == MVT::i32 || !Subtarget->is64Bit())
24020 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24021 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24022 case 'f': // FP Stack registers.
24023 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24024 // value to the correct fpstack register class.
24025 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24026 return std::make_pair(0U, &X86::RFP32RegClass);
24027 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24028 return std::make_pair(0U, &X86::RFP64RegClass);
24029 return std::make_pair(0U, &X86::RFP80RegClass);
24030 case 'y': // MMX_REGS if MMX allowed.
24031 if (!Subtarget->hasMMX()) break;
24032 return std::make_pair(0U, &X86::VR64RegClass);
24033 case 'Y': // SSE_REGS if SSE2 allowed
24034 if (!Subtarget->hasSSE2()) break;
24036 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24037 if (!Subtarget->hasSSE1()) break;
24039 switch (VT.SimpleTy) {
24041 // Scalar SSE types.
24044 return std::make_pair(0U, &X86::FR32RegClass);
24047 return std::make_pair(0U, &X86::FR64RegClass);
24055 return std::make_pair(0U, &X86::VR128RegClass);
24063 return std::make_pair(0U, &X86::VR256RegClass);
24068 return std::make_pair(0U, &X86::VR512RegClass);
24074 // Use the default implementation in TargetLowering to convert the register
24075 // constraint into a member of a register class.
24076 std::pair<unsigned, const TargetRegisterClass*> Res;
24077 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
24079 // Not found as a standard register?
24081 // Map st(0) -> st(7) -> ST0
24082 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24083 tolower(Constraint[1]) == 's' &&
24084 tolower(Constraint[2]) == 't' &&
24085 Constraint[3] == '(' &&
24086 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24087 Constraint[5] == ')' &&
24088 Constraint[6] == '}') {
24090 Res.first = X86::FP0+Constraint[4]-'0';
24091 Res.second = &X86::RFP80RegClass;
24095 // GCC allows "st(0)" to be called just plain "st".
24096 if (StringRef("{st}").equals_lower(Constraint)) {
24097 Res.first = X86::FP0;
24098 Res.second = &X86::RFP80RegClass;
24103 if (StringRef("{flags}").equals_lower(Constraint)) {
24104 Res.first = X86::EFLAGS;
24105 Res.second = &X86::CCRRegClass;
24109 // 'A' means EAX + EDX.
24110 if (Constraint == "A") {
24111 Res.first = X86::EAX;
24112 Res.second = &X86::GR32_ADRegClass;
24118 // Otherwise, check to see if this is a register class of the wrong value
24119 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24120 // turn into {ax},{dx}.
24121 if (Res.second->hasType(VT))
24122 return Res; // Correct type already, nothing to do.
24124 // All of the single-register GCC register classes map their values onto
24125 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24126 // really want an 8-bit or 32-bit register, map to the appropriate register
24127 // class and return the appropriate register.
24128 if (Res.second == &X86::GR16RegClass) {
24129 if (VT == MVT::i8 || VT == MVT::i1) {
24130 unsigned DestReg = 0;
24131 switch (Res.first) {
24133 case X86::AX: DestReg = X86::AL; break;
24134 case X86::DX: DestReg = X86::DL; break;
24135 case X86::CX: DestReg = X86::CL; break;
24136 case X86::BX: DestReg = X86::BL; break;
24139 Res.first = DestReg;
24140 Res.second = &X86::GR8RegClass;
24142 } else if (VT == MVT::i32 || VT == MVT::f32) {
24143 unsigned DestReg = 0;
24144 switch (Res.first) {
24146 case X86::AX: DestReg = X86::EAX; break;
24147 case X86::DX: DestReg = X86::EDX; break;
24148 case X86::CX: DestReg = X86::ECX; break;
24149 case X86::BX: DestReg = X86::EBX; break;
24150 case X86::SI: DestReg = X86::ESI; break;
24151 case X86::DI: DestReg = X86::EDI; break;
24152 case X86::BP: DestReg = X86::EBP; break;
24153 case X86::SP: DestReg = X86::ESP; break;
24156 Res.first = DestReg;
24157 Res.second = &X86::GR32RegClass;
24159 } else if (VT == MVT::i64 || VT == MVT::f64) {
24160 unsigned DestReg = 0;
24161 switch (Res.first) {
24163 case X86::AX: DestReg = X86::RAX; break;
24164 case X86::DX: DestReg = X86::RDX; break;
24165 case X86::CX: DestReg = X86::RCX; break;
24166 case X86::BX: DestReg = X86::RBX; break;
24167 case X86::SI: DestReg = X86::RSI; break;
24168 case X86::DI: DestReg = X86::RDI; break;
24169 case X86::BP: DestReg = X86::RBP; break;
24170 case X86::SP: DestReg = X86::RSP; break;
24173 Res.first = DestReg;
24174 Res.second = &X86::GR64RegClass;
24177 } else if (Res.second == &X86::FR32RegClass ||
24178 Res.second == &X86::FR64RegClass ||
24179 Res.second == &X86::VR128RegClass ||
24180 Res.second == &X86::VR256RegClass ||
24181 Res.second == &X86::FR32XRegClass ||
24182 Res.second == &X86::FR64XRegClass ||
24183 Res.second == &X86::VR128XRegClass ||
24184 Res.second == &X86::VR256XRegClass ||
24185 Res.second == &X86::VR512RegClass) {
24186 // Handle references to XMM physical registers that got mapped into the
24187 // wrong class. This can happen with constraints like {xmm0} where the
24188 // target independent register mapper will just pick the first match it can
24189 // find, ignoring the required type.
24191 if (VT == MVT::f32 || VT == MVT::i32)
24192 Res.second = &X86::FR32RegClass;
24193 else if (VT == MVT::f64 || VT == MVT::i64)
24194 Res.second = &X86::FR64RegClass;
24195 else if (X86::VR128RegClass.hasType(VT))
24196 Res.second = &X86::VR128RegClass;
24197 else if (X86::VR256RegClass.hasType(VT))
24198 Res.second = &X86::VR256RegClass;
24199 else if (X86::VR512RegClass.hasType(VT))
24200 Res.second = &X86::VR512RegClass;
24206 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24208 // Scaling factors are not free at all.
24209 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24210 // will take 2 allocations in the out of order engine instead of 1
24211 // for plain addressing mode, i.e. inst (reg1).
24213 // vaddps (%rsi,%drx), %ymm0, %ymm1
24214 // Requires two allocations (one for the load, one for the computation)
24216 // vaddps (%rsi), %ymm0, %ymm1
24217 // Requires just 1 allocation, i.e., freeing allocations for other operations
24218 // and having less micro operations to execute.
24220 // For some X86 architectures, this is even worse because for instance for
24221 // stores, the complex addressing mode forces the instruction to use the
24222 // "load" ports instead of the dedicated "store" port.
24223 // E.g., on Haswell:
24224 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24225 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24226 if (isLegalAddressingMode(AM, Ty))
24227 // Scale represents reg2 * scale, thus account for 1
24228 // as soon as we use a second register.
24229 return AM.Scale != 0;
24233 bool X86TargetLowering::isTargetFTOL() const {
24234 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();