1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
59 #define DEBUG_TYPE "x86-isel"
61 STATISTIC(NumTailCalls, "Number of tail calls");
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64 "x86-experimental-vector-widening-legalization", cl::init(false),
65 cl::desc("Enable an experimental vector type legalization through widening "
66 "rather than promotion."),
69 static cl::opt<int> ReciprocalEstimateRefinementSteps(
70 "x86-recip-refinement-steps", cl::init(1),
71 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
72 "result of the hardware reciprocal estimate instruction."),
75 // Forward declarations.
76 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
79 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
80 SelectionDAG &DAG, SDLoc dl,
81 unsigned vectorWidth) {
82 assert((vectorWidth == 128 || vectorWidth == 256) &&
83 "Unsupported vector width");
84 EVT VT = Vec.getValueType();
85 EVT ElVT = VT.getVectorElementType();
86 unsigned Factor = VT.getSizeInBits()/vectorWidth;
87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88 VT.getVectorNumElements()/Factor);
90 // Extract from UNDEF is UNDEF.
91 if (Vec.getOpcode() == ISD::UNDEF)
92 return DAG.getUNDEF(ResultVT);
94 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
95 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
97 // This is the index of the first element of the vectorWidth-bit chunk
99 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
102 // If the input is a buildvector just emit a smaller one.
103 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
104 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
105 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
108 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
109 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit boundary. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
163 SelectionDAG &DAG,SDLoc dl) {
164 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
165 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
169 SelectionDAG &DAG, SDLoc dl) {
170 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
171 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
175 /// instructions. This is used because creating CONCAT_VECTOR nodes of
176 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
177 /// large BUILD_VECTORS.
178 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
179 unsigned NumElems, SelectionDAG &DAG,
181 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
182 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
186 unsigned NumElems, SelectionDAG &DAG,
188 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
189 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
193 const X86Subtarget &STI)
194 : TargetLowering(TM), Subtarget(&STI) {
195 X86ScalarSSEf64 = Subtarget->hasSSE2();
196 X86ScalarSSEf32 = Subtarget->hasSSE1();
197 TD = getDataLayout();
199 // Set up the TargetLowering object.
200 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
202 // X86 is weird. It always uses i8 for shift amounts and setcc results.
203 setBooleanContents(ZeroOrOneBooleanContent);
204 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
205 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
207 // For 64-bit, since we have so many registers, use the ILP scheduler.
208 // For 32-bit, use the register pressure specific scheduling.
209 // For Atom, always use ILP scheduling.
210 if (Subtarget->isAtom())
211 setSchedulingPreference(Sched::ILP);
212 else if (Subtarget->is64Bit())
213 setSchedulingPreference(Sched::ILP);
215 setSchedulingPreference(Sched::RegPressure);
216 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
217 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
219 // Bypass expensive divides on Atom when compiling with O2.
220 if (TM.getOptLevel() >= CodeGenOpt::Default) {
221 if (Subtarget->hasSlowDivide32())
222 addBypassSlowDiv(32, 8);
223 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
224 addBypassSlowDiv(64, 16);
227 if (Subtarget->isTargetKnownWindowsMSVC()) {
228 // Setup Windows compiler runtime calls.
229 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
230 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
231 setLibcallName(RTLIB::SREM_I64, "_allrem");
232 setLibcallName(RTLIB::UREM_I64, "_aullrem");
233 setLibcallName(RTLIB::MUL_I64, "_allmul");
234 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
235 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
236 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
237 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
238 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
240 // The _ftol2 runtime function has an unusual calling conv, which
241 // is modeled by a special pseudo-instruction.
242 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
243 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
244 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
245 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
248 if (Subtarget->isTargetDarwin()) {
249 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
250 setUseUnderscoreSetJmp(false);
251 setUseUnderscoreLongJmp(false);
252 } else if (Subtarget->isTargetWindowsGNU()) {
253 // MS runtime is weird: it exports _setjmp, but longjmp!
254 setUseUnderscoreSetJmp(true);
255 setUseUnderscoreLongJmp(false);
257 setUseUnderscoreSetJmp(true);
258 setUseUnderscoreLongJmp(true);
261 // Set up the register classes.
262 addRegisterClass(MVT::i8, &X86::GR8RegClass);
263 addRegisterClass(MVT::i16, &X86::GR16RegClass);
264 addRegisterClass(MVT::i32, &X86::GR32RegClass);
265 if (Subtarget->is64Bit())
266 addRegisterClass(MVT::i64, &X86::GR64RegClass);
268 for (MVT VT : MVT::integer_valuetypes())
269 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
271 // We don't accept any truncstore of integer registers.
272 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
273 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
274 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
275 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
276 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
277 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
279 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
281 // SETOEQ and SETUNE require checking two conditions.
282 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
283 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
284 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
285 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
286 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
287 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
289 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
291 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
292 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
293 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
295 if (Subtarget->is64Bit()) {
296 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
297 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
298 } else if (!TM.Options.UseSoftFloat) {
299 // We have an algorithm for SSE2->double, and we turn this into a
300 // 64-bit FILD followed by conditional FADD for other targets.
301 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
302 // We have an algorithm for SSE2, and we turn this into a 64-bit
303 // FILD for other targets.
304 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
307 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
309 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
310 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
312 if (!TM.Options.UseSoftFloat) {
313 // SSE has no i16 to fp conversion, only i32
314 if (X86ScalarSSEf32) {
315 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
316 // f32 and f64 cases are Legal, f80 case is not
317 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
319 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
320 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
323 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
324 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
327 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
328 // are Legal, f80 is custom lowered.
329 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
330 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
332 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
334 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
335 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
337 if (X86ScalarSSEf32) {
338 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
339 // f32 and f64 cases are Legal, f80 case is not
340 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
342 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
343 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
346 // Handle FP_TO_UINT by promoting the destination to a larger signed
348 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
349 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
350 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
352 if (Subtarget->is64Bit()) {
353 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
354 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
355 } else if (!TM.Options.UseSoftFloat) {
356 // Since AVX is a superset of SSE3, only check for SSE here.
357 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
358 // Expand FP_TO_UINT into a select.
359 // FIXME: We would like to use a Custom expander here eventually to do
360 // the optimal thing for SSE vs. the default expansion in the legalizer.
361 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
363 // With SSE3 we can use fisttpll to convert to a signed i64; without
364 // SSE, we're stuck with a fistpll.
365 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
368 if (isTargetFTOL()) {
369 // Use the _ftol2 runtime function, which has a pseudo-instruction
370 // to handle its weird calling convention.
371 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
374 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
375 if (!X86ScalarSSEf64) {
376 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
377 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
378 if (Subtarget->is64Bit()) {
379 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
380 // Without SSE, i64->f64 goes through memory.
381 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
385 // Scalar integer divide and remainder are lowered to use operations that
386 // produce two results, to match the available instructions. This exposes
387 // the two-result form to trivial CSE, which is able to combine x/y and x%y
388 // into a single instruction.
390 // Scalar integer multiply-high is also lowered to use two-result
391 // operations, to match the available instructions. However, plain multiply
392 // (low) operations are left as Legal, as there are single-result
393 // instructions for this in x86. Using the two-result multiply instructions
394 // when both high and low results are needed must be arranged by dagcombine.
395 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
397 setOperationAction(ISD::MULHS, VT, Expand);
398 setOperationAction(ISD::MULHU, VT, Expand);
399 setOperationAction(ISD::SDIV, VT, Expand);
400 setOperationAction(ISD::UDIV, VT, Expand);
401 setOperationAction(ISD::SREM, VT, Expand);
402 setOperationAction(ISD::UREM, VT, Expand);
404 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
405 setOperationAction(ISD::ADDC, VT, Custom);
406 setOperationAction(ISD::ADDE, VT, Custom);
407 setOperationAction(ISD::SUBC, VT, Custom);
408 setOperationAction(ISD::SUBE, VT, Custom);
411 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
412 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
413 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
414 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
415 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
416 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
417 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
418 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
419 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
420 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
421 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
422 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
423 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
424 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
425 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
426 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
427 if (Subtarget->is64Bit())
428 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
429 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
430 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
431 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
432 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
433 setOperationAction(ISD::FREM , MVT::f32 , Expand);
434 setOperationAction(ISD::FREM , MVT::f64 , Expand);
435 setOperationAction(ISD::FREM , MVT::f80 , Expand);
436 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
438 // Promote the i8 variants and force them on up to i32 which has a shorter
440 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
441 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
442 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
443 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
444 if (Subtarget->hasBMI()) {
445 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
446 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
447 if (Subtarget->is64Bit())
448 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
450 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
451 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
452 if (Subtarget->is64Bit())
453 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
456 if (Subtarget->hasLZCNT()) {
457 // When promoting the i8 variants, force them to i32 for a shorter
459 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
460 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
461 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
462 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
463 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
464 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
469 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
470 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
471 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
474 if (Subtarget->is64Bit()) {
475 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
480 // Special handling for half-precision floating point conversions.
481 // If we don't have F16C support, then lower half float conversions
482 // into library calls.
483 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
484 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
485 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
488 // There's never any support for operations beyond MVT::f32.
489 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
490 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
491 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
492 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
494 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
495 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
496 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
497 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
498 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
499 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
501 if (Subtarget->hasPOPCNT()) {
502 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
504 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
505 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
506 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
507 if (Subtarget->is64Bit())
508 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
511 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
513 if (!Subtarget->hasMOVBE())
514 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
516 // These should be promoted to a larger select which is supported.
517 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
518 // X86 wants to expand cmov itself.
519 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
520 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
521 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
522 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
523 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
524 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
525 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
526 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
527 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
528 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
529 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
530 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
531 if (Subtarget->is64Bit()) {
532 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
533 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
535 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
536 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
537 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
538 // support continuation, user-level threading, and etc.. As a result, no
539 // other SjLj exception interfaces are implemented and please don't build
540 // your own exception handling based on them.
541 // LLVM/Clang supports zero-cost DWARF exception handling.
542 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
543 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
546 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
547 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
548 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
549 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
550 if (Subtarget->is64Bit())
551 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
552 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
553 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
554 if (Subtarget->is64Bit()) {
555 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
556 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
557 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
558 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
559 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
561 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
562 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
563 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
564 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
567 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
568 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
571 if (Subtarget->hasSSE1())
572 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
574 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
576 // Expand certain atomics
577 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
579 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
580 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
581 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
584 if (Subtarget->hasCmpxchg16b()) {
585 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
588 // FIXME - use subtarget debug flags
589 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
590 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
591 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
594 if (Subtarget->is64Bit()) {
595 setExceptionPointerRegister(X86::RAX);
596 setExceptionSelectorRegister(X86::RDX);
598 setExceptionPointerRegister(X86::EAX);
599 setExceptionSelectorRegister(X86::EDX);
601 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
602 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
604 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
605 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
607 setOperationAction(ISD::TRAP, MVT::Other, Legal);
608 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
610 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
611 setOperationAction(ISD::VASTART , MVT::Other, Custom);
612 setOperationAction(ISD::VAEND , MVT::Other, Expand);
613 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
614 // TargetInfo::X86_64ABIBuiltinVaList
615 setOperationAction(ISD::VAARG , MVT::Other, Custom);
616 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
618 // TargetInfo::CharPtrBuiltinVaList
619 setOperationAction(ISD::VAARG , MVT::Other, Expand);
620 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
623 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
624 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
626 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
628 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
629 // f32 and f64 use SSE.
630 // Set up the FP register classes.
631 addRegisterClass(MVT::f32, &X86::FR32RegClass);
632 addRegisterClass(MVT::f64, &X86::FR64RegClass);
634 // Use ANDPD to simulate FABS.
635 setOperationAction(ISD::FABS , MVT::f64, Custom);
636 setOperationAction(ISD::FABS , MVT::f32, Custom);
638 // Use XORP to simulate FNEG.
639 setOperationAction(ISD::FNEG , MVT::f64, Custom);
640 setOperationAction(ISD::FNEG , MVT::f32, Custom);
642 // Use ANDPD and ORPD to simulate FCOPYSIGN.
643 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
644 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
646 // Lower this to FGETSIGNx86 plus an AND.
647 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
648 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
650 // We don't support sin/cos/fmod
651 setOperationAction(ISD::FSIN , MVT::f64, Expand);
652 setOperationAction(ISD::FCOS , MVT::f64, Expand);
653 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
654 setOperationAction(ISD::FSIN , MVT::f32, Expand);
655 setOperationAction(ISD::FCOS , MVT::f32, Expand);
656 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
658 // Expand FP immediates into loads from the stack, except for the special
660 addLegalFPImmediate(APFloat(+0.0)); // xorpd
661 addLegalFPImmediate(APFloat(+0.0f)); // xorps
662 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
663 // Use SSE for f32, x87 for f64.
664 // Set up the FP register classes.
665 addRegisterClass(MVT::f32, &X86::FR32RegClass);
666 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
668 // Use ANDPS to simulate FABS.
669 setOperationAction(ISD::FABS , MVT::f32, Custom);
671 // Use XORP to simulate FNEG.
672 setOperationAction(ISD::FNEG , MVT::f32, Custom);
674 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
676 // Use ANDPS and ORPS to simulate FCOPYSIGN.
677 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
678 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
680 // We don't support sin/cos/fmod
681 setOperationAction(ISD::FSIN , MVT::f32, Expand);
682 setOperationAction(ISD::FCOS , MVT::f32, Expand);
683 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
685 // Special cases we handle for FP constants.
686 addLegalFPImmediate(APFloat(+0.0f)); // xorps
687 addLegalFPImmediate(APFloat(+0.0)); // FLD0
688 addLegalFPImmediate(APFloat(+1.0)); // FLD1
689 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
690 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
692 if (!TM.Options.UnsafeFPMath) {
693 setOperationAction(ISD::FSIN , MVT::f64, Expand);
694 setOperationAction(ISD::FCOS , MVT::f64, Expand);
695 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
697 } else if (!TM.Options.UseSoftFloat) {
698 // f32 and f64 in x87.
699 // Set up the FP register classes.
700 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
701 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
703 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
704 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
705 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
706 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
708 if (!TM.Options.UnsafeFPMath) {
709 setOperationAction(ISD::FSIN , MVT::f64, Expand);
710 setOperationAction(ISD::FSIN , MVT::f32, Expand);
711 setOperationAction(ISD::FCOS , MVT::f64, Expand);
712 setOperationAction(ISD::FCOS , MVT::f32, Expand);
713 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
714 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
716 addLegalFPImmediate(APFloat(+0.0)); // FLD0
717 addLegalFPImmediate(APFloat(+1.0)); // FLD1
718 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
719 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
720 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
721 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
722 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
723 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
726 // We don't support FMA.
727 setOperationAction(ISD::FMA, MVT::f64, Expand);
728 setOperationAction(ISD::FMA, MVT::f32, Expand);
730 // Long double always uses X87.
731 if (!TM.Options.UseSoftFloat) {
732 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
733 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
734 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
736 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
737 addLegalFPImmediate(TmpFlt); // FLD0
739 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
742 APFloat TmpFlt2(+1.0);
743 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
745 addLegalFPImmediate(TmpFlt2); // FLD1
746 TmpFlt2.changeSign();
747 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
750 if (!TM.Options.UnsafeFPMath) {
751 setOperationAction(ISD::FSIN , MVT::f80, Expand);
752 setOperationAction(ISD::FCOS , MVT::f80, Expand);
753 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
756 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
757 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
758 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
759 setOperationAction(ISD::FRINT, MVT::f80, Expand);
760 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
761 setOperationAction(ISD::FMA, MVT::f80, Expand);
764 // Always use a library call for pow.
765 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
766 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
767 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
769 setOperationAction(ISD::FLOG, MVT::f80, Expand);
770 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
771 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
772 setOperationAction(ISD::FEXP, MVT::f80, Expand);
773 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
774 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
775 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
777 // First set operation action for all vector types to either promote
778 // (for widening) or expand (for scalarization). Then we will selectively
779 // turn on ones that can be effectively codegen'd.
780 for (MVT VT : MVT::vector_valuetypes()) {
781 setOperationAction(ISD::ADD , VT, Expand);
782 setOperationAction(ISD::SUB , VT, Expand);
783 setOperationAction(ISD::FADD, VT, Expand);
784 setOperationAction(ISD::FNEG, VT, Expand);
785 setOperationAction(ISD::FSUB, VT, Expand);
786 setOperationAction(ISD::MUL , VT, Expand);
787 setOperationAction(ISD::FMUL, VT, Expand);
788 setOperationAction(ISD::SDIV, VT, Expand);
789 setOperationAction(ISD::UDIV, VT, Expand);
790 setOperationAction(ISD::FDIV, VT, Expand);
791 setOperationAction(ISD::SREM, VT, Expand);
792 setOperationAction(ISD::UREM, VT, Expand);
793 setOperationAction(ISD::LOAD, VT, Expand);
794 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
796 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
797 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
798 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
799 setOperationAction(ISD::FABS, VT, Expand);
800 setOperationAction(ISD::FSIN, VT, Expand);
801 setOperationAction(ISD::FSINCOS, VT, Expand);
802 setOperationAction(ISD::FCOS, VT, Expand);
803 setOperationAction(ISD::FSINCOS, VT, Expand);
804 setOperationAction(ISD::FREM, VT, Expand);
805 setOperationAction(ISD::FMA, VT, Expand);
806 setOperationAction(ISD::FPOWI, VT, Expand);
807 setOperationAction(ISD::FSQRT, VT, Expand);
808 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
809 setOperationAction(ISD::FFLOOR, VT, Expand);
810 setOperationAction(ISD::FCEIL, VT, Expand);
811 setOperationAction(ISD::FTRUNC, VT, Expand);
812 setOperationAction(ISD::FRINT, VT, Expand);
813 setOperationAction(ISD::FNEARBYINT, VT, Expand);
814 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
815 setOperationAction(ISD::MULHS, VT, Expand);
816 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
817 setOperationAction(ISD::MULHU, VT, Expand);
818 setOperationAction(ISD::SDIVREM, VT, Expand);
819 setOperationAction(ISD::UDIVREM, VT, Expand);
820 setOperationAction(ISD::FPOW, VT, Expand);
821 setOperationAction(ISD::CTPOP, VT, Expand);
822 setOperationAction(ISD::CTTZ, VT, Expand);
823 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
824 setOperationAction(ISD::CTLZ, VT, Expand);
825 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
826 setOperationAction(ISD::SHL, VT, Expand);
827 setOperationAction(ISD::SRA, VT, Expand);
828 setOperationAction(ISD::SRL, VT, Expand);
829 setOperationAction(ISD::ROTL, VT, Expand);
830 setOperationAction(ISD::ROTR, VT, Expand);
831 setOperationAction(ISD::BSWAP, VT, Expand);
832 setOperationAction(ISD::SETCC, VT, Expand);
833 setOperationAction(ISD::FLOG, VT, Expand);
834 setOperationAction(ISD::FLOG2, VT, Expand);
835 setOperationAction(ISD::FLOG10, VT, Expand);
836 setOperationAction(ISD::FEXP, VT, Expand);
837 setOperationAction(ISD::FEXP2, VT, Expand);
838 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
839 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
840 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
841 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
842 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
843 setOperationAction(ISD::TRUNCATE, VT, Expand);
844 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
845 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
846 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
847 setOperationAction(ISD::VSELECT, VT, Expand);
848 setOperationAction(ISD::SELECT_CC, VT, Expand);
849 for (MVT InnerVT : MVT::vector_valuetypes()) {
850 setTruncStoreAction(InnerVT, VT, Expand);
852 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
853 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
855 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
856 // types, we have to deal with them whether we ask for Expansion or not.
857 // Setting Expand causes its own optimisation problems though, so leave
859 if (VT.getVectorElementType() == MVT::i1)
860 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
864 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
865 // with -msoft-float, disable use of MMX as well.
866 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
867 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
868 // No operations on x86mmx supported, everything uses intrinsics.
871 // MMX-sized vectors (other than x86mmx) are expected to be expanded
872 // into smaller operations.
873 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
874 setOperationAction(ISD::MULHS, MMXTy, Expand);
875 setOperationAction(ISD::AND, MMXTy, Expand);
876 setOperationAction(ISD::OR, MMXTy, Expand);
877 setOperationAction(ISD::XOR, MMXTy, Expand);
878 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
879 setOperationAction(ISD::SELECT, MMXTy, Expand);
880 setOperationAction(ISD::BITCAST, MMXTy, Expand);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
884 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
885 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
887 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
888 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
889 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
890 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
891 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
892 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
893 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
894 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
895 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
897 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
899 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
900 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
903 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
904 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
906 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
907 // registers cannot be used even for integer operations.
908 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
909 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
910 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
911 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
913 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
914 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
915 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
916 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
917 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
918 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
919 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
920 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
921 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
922 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
923 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
924 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
925 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
926 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
927 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
928 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
929 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
930 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
931 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
932 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
933 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
934 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
936 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
937 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
938 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
939 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
941 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
942 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
943 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
944 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
945 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
947 // Only provide customized ctpop vector bit twiddling for vector types we
948 // know to perform better than using the popcnt instructions on each vector
949 // element. If popcnt isn't supported, always provide the custom version.
950 if (!Subtarget->hasPOPCNT()) {
951 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
952 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
955 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
956 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
957 MVT VT = (MVT::SimpleValueType)i;
958 // Do not attempt to custom lower non-power-of-2 vectors
959 if (!isPowerOf2_32(VT.getVectorNumElements()))
961 // Do not attempt to custom lower non-128-bit vectors
962 if (!VT.is128BitVector())
964 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
965 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
966 setOperationAction(ISD::VSELECT, VT, Custom);
967 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
970 // We support custom legalizing of sext and anyext loads for specific
971 // memory vector types which we can load as a scalar (or sequence of
972 // scalars) and extend in-register to a legal 128-bit vector type. For sext
973 // loads these must work with a single scalar load.
974 for (MVT VT : MVT::integer_vector_valuetypes()) {
975 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
976 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
977 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
978 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
979 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
980 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
981 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
982 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
983 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
986 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
987 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
989 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
990 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
991 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
995 if (Subtarget->is64Bit()) {
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1000 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1004 // Do not attempt to promote non-128-bit vectors
1005 if (!VT.is128BitVector())
1008 setOperationAction(ISD::AND, VT, Promote);
1009 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1010 setOperationAction(ISD::OR, VT, Promote);
1011 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1012 setOperationAction(ISD::XOR, VT, Promote);
1013 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1014 setOperationAction(ISD::LOAD, VT, Promote);
1015 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1016 setOperationAction(ISD::SELECT, VT, Promote);
1017 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1020 // Custom lower v2i64 and v2f64 selects.
1021 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1022 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1023 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1024 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1026 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1027 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1031 // As there is no 64-bit GPR available, we need build a special custom
1032 // sequence to convert from v2i32 to v2f32.
1033 if (!Subtarget->is64Bit())
1034 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1036 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1037 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1039 for (MVT VT : MVT::fp_vector_valuetypes())
1040 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
1042 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1043 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1044 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1047 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1048 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1049 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1050 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1051 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1052 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1053 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
1056 // FIXME: Do we need to handle scalar-to-vector here?
1057 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1059 // We directly match byte blends in the backend as they match the VSELECT
1061 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1063 // SSE41 brings specific instructions for doing vector sign extend even in
1064 // cases where we don't have SRA.
1065 for (MVT VT : MVT::integer_vector_valuetypes()) {
1066 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1067 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1068 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1071 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1072 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1073 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1074 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1075 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1076 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1077 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1079 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1080 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1081 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1082 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1083 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1084 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1086 // i8 and i16 vectors are custom because the source register and source
1087 // source memory operand types are not the same width. f32 vectors are
1088 // custom since the immediate controlling the insert encodes additional
1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1091 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1092 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1093 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1095 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1096 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1098 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1100 // FIXME: these should be Legal, but that's only for the case where
1101 // the index is constant. For now custom expand to deal with that.
1102 if (Subtarget->is64Bit()) {
1103 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1108 if (Subtarget->hasSSE2()) {
1109 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1110 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1112 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1113 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1115 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1116 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1118 // In the customized shift lowering, the legal cases in AVX2 will be
1120 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1121 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1123 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1124 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1126 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1129 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1130 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1131 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1132 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1133 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1134 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1135 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1137 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1138 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1139 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1141 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1145 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1146 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1147 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1148 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1152 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1154 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1158 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1159 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1160 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1161 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1165 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1167 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1168 // even though v8i16 is a legal type.
1169 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1170 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1171 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1173 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1174 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1175 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1177 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1178 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1180 for (MVT VT : MVT::fp_vector_valuetypes())
1181 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1183 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1184 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1186 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1187 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1189 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1190 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1194 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1198 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1199 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1201 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1202 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1203 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1204 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1205 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1206 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1207 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1208 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1209 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1210 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1211 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1212 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1214 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1215 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1216 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1217 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1218 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1219 setOperationAction(ISD::FMA, MVT::f32, Legal);
1220 setOperationAction(ISD::FMA, MVT::f64, Legal);
1223 if (Subtarget->hasInt256()) {
1224 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1225 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1226 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1227 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1229 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1230 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1231 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1232 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1234 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1235 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1236 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1237 // Don't lower v32i8 because there is no 128-bit byte mul
1239 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1240 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1241 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1242 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1244 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1245 // when we have a 256bit-wide blend with immediate.
1246 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1248 // Only provide customized ctpop vector bit twiddling for vector types we
1249 // know to perform better than using the popcnt instructions on each
1250 // vector element. If popcnt isn't supported, always provide the custom
1252 if (!Subtarget->hasPOPCNT())
1253 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1255 // Custom CTPOP always performs better on natively supported v8i32
1256 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1258 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1259 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1260 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1261 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1262 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1263 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1264 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1266 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1267 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1268 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1269 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1270 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1271 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1273 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1274 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1275 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1276 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1278 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1279 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1280 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1281 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1283 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1284 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1285 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1286 // Don't lower v32i8 because there is no 128-bit byte mul
1289 // In the customized shift lowering, the legal cases in AVX2 will be
1291 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1292 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1294 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1295 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1297 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1299 // Custom lower several nodes for 256-bit types.
1300 for (MVT VT : MVT::vector_valuetypes()) {
1301 if (VT.getScalarSizeInBits() >= 32) {
1302 setOperationAction(ISD::MLOAD, VT, Legal);
1303 setOperationAction(ISD::MSTORE, VT, Legal);
1305 // Extract subvector is special because the value type
1306 // (result) is 128-bit but the source is 256-bit wide.
1307 if (VT.is128BitVector()) {
1308 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1310 // Do not attempt to custom lower other non-256-bit vectors
1311 if (!VT.is256BitVector())
1314 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1315 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1316 setOperationAction(ISD::VSELECT, VT, Custom);
1317 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1318 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1319 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1320 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1321 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1324 if (Subtarget->hasInt256())
1325 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1328 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1329 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1330 MVT VT = (MVT::SimpleValueType)i;
1332 // Do not attempt to promote non-256-bit vectors
1333 if (!VT.is256BitVector())
1336 setOperationAction(ISD::AND, VT, Promote);
1337 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1338 setOperationAction(ISD::OR, VT, Promote);
1339 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1340 setOperationAction(ISD::XOR, VT, Promote);
1341 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1342 setOperationAction(ISD::LOAD, VT, Promote);
1343 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1344 setOperationAction(ISD::SELECT, VT, Promote);
1345 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1349 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1350 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1351 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1352 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1353 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1355 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1356 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1357 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1359 for (MVT VT : MVT::fp_vector_valuetypes())
1360 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1362 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1363 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1364 setOperationAction(ISD::XOR, MVT::i1, Legal);
1365 setOperationAction(ISD::OR, MVT::i1, Legal);
1366 setOperationAction(ISD::AND, MVT::i1, Legal);
1367 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1368 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1369 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1370 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1371 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1373 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1374 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1375 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1376 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1377 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1378 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1380 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1381 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1382 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1383 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1384 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1385 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1386 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1387 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1390 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1391 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1392 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1393 if (Subtarget->is64Bit()) {
1394 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1395 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1396 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1397 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1399 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1400 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1401 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1402 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1403 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1404 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1405 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1406 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1407 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1408 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1409 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1410 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1411 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1412 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1414 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1415 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1416 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1417 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1418 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1419 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1420 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1421 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1422 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1423 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1424 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1425 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1426 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1428 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1429 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1430 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1431 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1432 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1433 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1434 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1435 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1436 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1437 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1439 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1445 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1446 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1448 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1454 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1456 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1460 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1461 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1463 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1464 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1466 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1468 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1469 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1471 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1472 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1474 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1475 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1477 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1478 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1479 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1481 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1482 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1484 if (Subtarget->hasCDI()) {
1485 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1486 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1489 // Custom lower several nodes.
1490 for (MVT VT : MVT::vector_valuetypes()) {
1491 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1492 // Extract subvector is special because the value type
1493 // (result) is 256/128-bit but the source is 512-bit wide.
1494 if (VT.is128BitVector() || VT.is256BitVector()) {
1495 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1497 if (VT.getVectorElementType() == MVT::i1)
1498 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1500 // Do not attempt to custom lower other non-512-bit vectors
1501 if (!VT.is512BitVector())
1504 if ( EltSize >= 32) {
1505 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1506 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1507 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1508 setOperationAction(ISD::VSELECT, VT, Legal);
1509 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1510 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1511 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1512 setOperationAction(ISD::MLOAD, VT, Legal);
1513 setOperationAction(ISD::MSTORE, VT, Legal);
1516 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517 MVT VT = (MVT::SimpleValueType)i;
1519 // Do not attempt to promote non-512-bit vectors.
1520 if (!VT.is512BitVector())
1523 setOperationAction(ISD::SELECT, VT, Promote);
1524 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1528 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1532 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1533 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1536 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1537 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1538 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1539 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1540 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1541 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1542 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1543 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1544 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1545 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1546 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1547 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1549 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1550 const MVT VT = (MVT::SimpleValueType)i;
1552 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1554 // Do not attempt to promote non-512-bit vectors.
1555 if (!VT.is512BitVector())
1559 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1560 setOperationAction(ISD::VSELECT, VT, Legal);
1565 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1566 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1567 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1569 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1570 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1571 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1572 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1573 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1574 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1576 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1577 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1578 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1579 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1580 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1581 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1584 // We want to custom lower some of our intrinsics.
1585 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1586 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1587 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1588 if (!Subtarget->is64Bit())
1589 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1591 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1592 // handle type legalization for these operations here.
1594 // FIXME: We really should do custom legalization for addition and
1595 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1596 // than generic legalization for 64-bit multiplication-with-overflow, though.
1597 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1598 // Add/Sub/Mul with overflow operations are custom lowered.
1600 setOperationAction(ISD::SADDO, VT, Custom);
1601 setOperationAction(ISD::UADDO, VT, Custom);
1602 setOperationAction(ISD::SSUBO, VT, Custom);
1603 setOperationAction(ISD::USUBO, VT, Custom);
1604 setOperationAction(ISD::SMULO, VT, Custom);
1605 setOperationAction(ISD::UMULO, VT, Custom);
1609 if (!Subtarget->is64Bit()) {
1610 // These libcalls are not available in 32-bit.
1611 setLibcallName(RTLIB::SHL_I128, nullptr);
1612 setLibcallName(RTLIB::SRL_I128, nullptr);
1613 setLibcallName(RTLIB::SRA_I128, nullptr);
1616 // Combine sin / cos into one node or libcall if possible.
1617 if (Subtarget->hasSinCos()) {
1618 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1619 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1620 if (Subtarget->isTargetDarwin()) {
1621 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1622 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1623 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1624 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1628 if (Subtarget->isTargetWin64()) {
1629 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1630 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1631 setOperationAction(ISD::SREM, MVT::i128, Custom);
1632 setOperationAction(ISD::UREM, MVT::i128, Custom);
1633 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1634 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1637 // We have target-specific dag combine patterns for the following nodes:
1638 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1639 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1640 setTargetDAGCombine(ISD::BITCAST);
1641 setTargetDAGCombine(ISD::VSELECT);
1642 setTargetDAGCombine(ISD::SELECT);
1643 setTargetDAGCombine(ISD::SHL);
1644 setTargetDAGCombine(ISD::SRA);
1645 setTargetDAGCombine(ISD::SRL);
1646 setTargetDAGCombine(ISD::OR);
1647 setTargetDAGCombine(ISD::AND);
1648 setTargetDAGCombine(ISD::ADD);
1649 setTargetDAGCombine(ISD::FADD);
1650 setTargetDAGCombine(ISD::FSUB);
1651 setTargetDAGCombine(ISD::FMA);
1652 setTargetDAGCombine(ISD::SUB);
1653 setTargetDAGCombine(ISD::LOAD);
1654 setTargetDAGCombine(ISD::MLOAD);
1655 setTargetDAGCombine(ISD::STORE);
1656 setTargetDAGCombine(ISD::MSTORE);
1657 setTargetDAGCombine(ISD::ZERO_EXTEND);
1658 setTargetDAGCombine(ISD::ANY_EXTEND);
1659 setTargetDAGCombine(ISD::SIGN_EXTEND);
1660 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1661 setTargetDAGCombine(ISD::TRUNCATE);
1662 setTargetDAGCombine(ISD::SINT_TO_FP);
1663 setTargetDAGCombine(ISD::SETCC);
1664 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1665 setTargetDAGCombine(ISD::BUILD_VECTOR);
1666 setTargetDAGCombine(ISD::MUL);
1667 setTargetDAGCombine(ISD::XOR);
1669 computeRegisterProperties(Subtarget->getRegisterInfo());
1671 // On Darwin, -Os means optimize for size without hurting performance,
1672 // do not reduce the limit.
1673 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1674 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1675 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1676 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1677 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1678 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1679 setPrefLoopAlignment(4); // 2^4 bytes.
1681 // Predictable cmov don't hurt on atom because it's in-order.
1682 PredictableSelectIsExpensive = !Subtarget->isAtom();
1683 EnableExtLdPromotion = true;
1684 setPrefFunctionAlignment(4); // 2^4 bytes.
1686 verifyIntrinsicTables();
1689 // This has so far only been implemented for 64-bit MachO.
1690 bool X86TargetLowering::useLoadStackGuardNode() const {
1691 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1694 TargetLoweringBase::LegalizeTypeAction
1695 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1696 if (ExperimentalVectorWideningLegalization &&
1697 VT.getVectorNumElements() != 1 &&
1698 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1699 return TypeWidenVector;
1701 return TargetLoweringBase::getPreferredVectorAction(VT);
1704 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1706 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1708 const unsigned NumElts = VT.getVectorNumElements();
1709 const EVT EltVT = VT.getVectorElementType();
1710 if (VT.is512BitVector()) {
1711 if (Subtarget->hasAVX512())
1712 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1713 EltVT == MVT::f32 || EltVT == MVT::f64)
1715 case 8: return MVT::v8i1;
1716 case 16: return MVT::v16i1;
1718 if (Subtarget->hasBWI())
1719 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1721 case 32: return MVT::v32i1;
1722 case 64: return MVT::v64i1;
1726 if (VT.is256BitVector() || VT.is128BitVector()) {
1727 if (Subtarget->hasVLX())
1728 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1729 EltVT == MVT::f32 || EltVT == MVT::f64)
1731 case 2: return MVT::v2i1;
1732 case 4: return MVT::v4i1;
1733 case 8: return MVT::v8i1;
1735 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1736 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1738 case 8: return MVT::v8i1;
1739 case 16: return MVT::v16i1;
1740 case 32: return MVT::v32i1;
1744 return VT.changeVectorElementTypeToInteger();
1747 /// Helper for getByValTypeAlignment to determine
1748 /// the desired ByVal argument alignment.
1749 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1752 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1753 if (VTy->getBitWidth() == 128)
1755 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1756 unsigned EltAlign = 0;
1757 getMaxByValAlign(ATy->getElementType(), EltAlign);
1758 if (EltAlign > MaxAlign)
1759 MaxAlign = EltAlign;
1760 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1761 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1762 unsigned EltAlign = 0;
1763 getMaxByValAlign(STy->getElementType(i), EltAlign);
1764 if (EltAlign > MaxAlign)
1765 MaxAlign = EltAlign;
1772 /// Return the desired alignment for ByVal aggregate
1773 /// function arguments in the caller parameter area. For X86, aggregates
1774 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1775 /// are at 4-byte boundaries.
1776 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1777 if (Subtarget->is64Bit()) {
1778 // Max of 8 and alignment of type.
1779 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1786 if (Subtarget->hasSSE1())
1787 getMaxByValAlign(Ty, Align);
1791 /// Returns the target specific optimal type for load
1792 /// and store operations as a result of memset, memcpy, and memmove
1793 /// lowering. If DstAlign is zero that means it's safe to destination
1794 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1795 /// means there isn't a need to check it against alignment requirement,
1796 /// probably because the source does not need to be loaded. If 'IsMemset' is
1797 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1798 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1799 /// source is constant so it does not need to be loaded.
1800 /// It returns EVT::Other if the type should be determined using generic
1801 /// target-independent logic.
1803 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1804 unsigned DstAlign, unsigned SrcAlign,
1805 bool IsMemset, bool ZeroMemset,
1807 MachineFunction &MF) const {
1808 const Function *F = MF.getFunction();
1809 if ((!IsMemset || ZeroMemset) &&
1810 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1812 (Subtarget->isUnalignedMemAccessFast() ||
1813 ((DstAlign == 0 || DstAlign >= 16) &&
1814 (SrcAlign == 0 || SrcAlign >= 16)))) {
1816 if (Subtarget->hasInt256())
1818 if (Subtarget->hasFp256())
1821 if (Subtarget->hasSSE2())
1823 if (Subtarget->hasSSE1())
1825 } else if (!MemcpyStrSrc && Size >= 8 &&
1826 !Subtarget->is64Bit() &&
1827 Subtarget->hasSSE2()) {
1828 // Do not use f64 to lower memcpy if source is string constant. It's
1829 // better to use i32 to avoid the loads.
1833 if (Subtarget->is64Bit() && Size >= 8)
1838 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1840 return X86ScalarSSEf32;
1841 else if (VT == MVT::f64)
1842 return X86ScalarSSEf64;
1847 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1852 *Fast = Subtarget->isUnalignedMemAccessFast();
1856 /// Return the entry encoding for a jump table in the
1857 /// current function. The returned value is a member of the
1858 /// MachineJumpTableInfo::JTEntryKind enum.
1859 unsigned X86TargetLowering::getJumpTableEncoding() const {
1860 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1862 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1863 Subtarget->isPICStyleGOT())
1864 return MachineJumpTableInfo::EK_Custom32;
1866 // Otherwise, use the normal jump table encoding heuristics.
1867 return TargetLowering::getJumpTableEncoding();
1871 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1872 const MachineBasicBlock *MBB,
1873 unsigned uid,MCContext &Ctx) const{
1874 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1875 Subtarget->isPICStyleGOT());
1876 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1878 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1879 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1882 /// Returns relocation base for the given PIC jumptable.
1883 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1884 SelectionDAG &DAG) const {
1885 if (!Subtarget->is64Bit())
1886 // This doesn't have SDLoc associated with it, but is not really the
1887 // same as a Register.
1888 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1892 /// This returns the relocation base for the given PIC jumptable,
1893 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1894 const MCExpr *X86TargetLowering::
1895 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1896 MCContext &Ctx) const {
1897 // X86-64 uses RIP relative addressing based on the jump table label.
1898 if (Subtarget->isPICStyleRIPRel())
1899 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1901 // Otherwise, the reference is relative to the PIC base.
1902 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1905 std::pair<const TargetRegisterClass *, uint8_t>
1906 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1908 const TargetRegisterClass *RRC = nullptr;
1910 switch (VT.SimpleTy) {
1912 return TargetLowering::findRepresentativeClass(TRI, VT);
1913 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1914 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1917 RRC = &X86::VR64RegClass;
1919 case MVT::f32: case MVT::f64:
1920 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1921 case MVT::v4f32: case MVT::v2f64:
1922 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1924 RRC = &X86::VR128RegClass;
1927 return std::make_pair(RRC, Cost);
1930 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1931 unsigned &Offset) const {
1932 if (!Subtarget->isTargetLinux())
1935 if (Subtarget->is64Bit()) {
1936 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1938 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1950 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1951 unsigned DestAS) const {
1952 assert(SrcAS != DestAS && "Expected different address spaces!");
1954 return SrcAS < 256 && DestAS < 256;
1957 //===----------------------------------------------------------------------===//
1958 // Return Value Calling Convention Implementation
1959 //===----------------------------------------------------------------------===//
1961 #include "X86GenCallingConv.inc"
1964 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1965 MachineFunction &MF, bool isVarArg,
1966 const SmallVectorImpl<ISD::OutputArg> &Outs,
1967 LLVMContext &Context) const {
1968 SmallVector<CCValAssign, 16> RVLocs;
1969 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1970 return CCInfo.CheckReturn(Outs, RetCC_X86);
1973 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1974 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1979 X86TargetLowering::LowerReturn(SDValue Chain,
1980 CallingConv::ID CallConv, bool isVarArg,
1981 const SmallVectorImpl<ISD::OutputArg> &Outs,
1982 const SmallVectorImpl<SDValue> &OutVals,
1983 SDLoc dl, SelectionDAG &DAG) const {
1984 MachineFunction &MF = DAG.getMachineFunction();
1985 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1987 SmallVector<CCValAssign, 16> RVLocs;
1988 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1989 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1992 SmallVector<SDValue, 6> RetOps;
1993 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1994 // Operand #1 = Bytes To Pop
1995 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1998 // Copy the result values into the output registers.
1999 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2000 CCValAssign &VA = RVLocs[i];
2001 assert(VA.isRegLoc() && "Can only return in registers!");
2002 SDValue ValToCopy = OutVals[i];
2003 EVT ValVT = ValToCopy.getValueType();
2005 // Promote values to the appropriate types.
2006 if (VA.getLocInfo() == CCValAssign::SExt)
2007 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2008 else if (VA.getLocInfo() == CCValAssign::ZExt)
2009 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2010 else if (VA.getLocInfo() == CCValAssign::AExt)
2011 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2012 else if (VA.getLocInfo() == CCValAssign::BCvt)
2013 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2015 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2016 "Unexpected FP-extend for return value.");
2018 // If this is x86-64, and we disabled SSE, we can't return FP values,
2019 // or SSE or MMX vectors.
2020 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2021 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2022 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2023 report_fatal_error("SSE register return with SSE disabled");
2025 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2026 // llvm-gcc has never done it right and no one has noticed, so this
2027 // should be OK for now.
2028 if (ValVT == MVT::f64 &&
2029 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2030 report_fatal_error("SSE2 register return with SSE2 disabled");
2032 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2033 // the RET instruction and handled by the FP Stackifier.
2034 if (VA.getLocReg() == X86::FP0 ||
2035 VA.getLocReg() == X86::FP1) {
2036 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2037 // change the value to the FP stack register class.
2038 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2039 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2040 RetOps.push_back(ValToCopy);
2041 // Don't emit a copytoreg.
2045 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2046 // which is returned in RAX / RDX.
2047 if (Subtarget->is64Bit()) {
2048 if (ValVT == MVT::x86mmx) {
2049 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2050 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2051 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2053 // If we don't have SSE2 available, convert to v4f32 so the generated
2054 // register is legal.
2055 if (!Subtarget->hasSSE2())
2056 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2061 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2062 Flag = Chain.getValue(1);
2063 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2066 // The x86-64 ABIs require that for returning structs by value we copy
2067 // the sret argument into %rax/%eax (depending on ABI) for the return.
2068 // Win32 requires us to put the sret argument to %eax as well.
2069 // We saved the argument into a virtual register in the entry block,
2070 // so now we copy the value out and into %rax/%eax.
2072 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2073 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2074 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2075 // either case FuncInfo->setSRetReturnReg() will have been called.
2076 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2077 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2078 "No need for an sret register");
2079 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2082 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2083 X86::RAX : X86::EAX;
2084 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2085 Flag = Chain.getValue(1);
2087 // RAX/EAX now acts like a return value.
2088 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2091 RetOps[0] = Chain; // Update chain.
2093 // Add the flag if we have it.
2095 RetOps.push_back(Flag);
2097 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2100 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2101 if (N->getNumValues() != 1)
2103 if (!N->hasNUsesOfValue(1, 0))
2106 SDValue TCChain = Chain;
2107 SDNode *Copy = *N->use_begin();
2108 if (Copy->getOpcode() == ISD::CopyToReg) {
2109 // If the copy has a glue operand, we conservatively assume it isn't safe to
2110 // perform a tail call.
2111 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2113 TCChain = Copy->getOperand(0);
2114 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2117 bool HasRet = false;
2118 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2120 if (UI->getOpcode() != X86ISD::RET_FLAG)
2122 // If we are returning more than one value, we can definitely
2123 // not make a tail call see PR19530
2124 if (UI->getNumOperands() > 4)
2126 if (UI->getNumOperands() == 4 &&
2127 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2140 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2141 ISD::NodeType ExtendKind) const {
2143 // TODO: Is this also valid on 32-bit?
2144 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2145 ReturnMVT = MVT::i8;
2147 ReturnMVT = MVT::i32;
2149 EVT MinVT = getRegisterType(Context, ReturnMVT);
2150 return VT.bitsLT(MinVT) ? MinVT : VT;
2153 /// Lower the result values of a call into the
2154 /// appropriate copies out of appropriate physical registers.
2157 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2158 CallingConv::ID CallConv, bool isVarArg,
2159 const SmallVectorImpl<ISD::InputArg> &Ins,
2160 SDLoc dl, SelectionDAG &DAG,
2161 SmallVectorImpl<SDValue> &InVals) const {
2163 // Assign locations to each value returned by this call.
2164 SmallVector<CCValAssign, 16> RVLocs;
2165 bool Is64Bit = Subtarget->is64Bit();
2166 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2168 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2170 // Copy all of the result registers out of their specified physreg.
2171 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2172 CCValAssign &VA = RVLocs[i];
2173 EVT CopyVT = VA.getValVT();
2175 // If this is x86-64, and we disabled SSE, we can't return FP values
2176 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2177 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2178 report_fatal_error("SSE register return with SSE disabled");
2181 // If we prefer to use the value in xmm registers, copy it out as f80 and
2182 // use a truncate to move it from fp stack reg to xmm reg.
2183 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2184 isScalarFPTypeInSSEReg(VA.getValVT()))
2187 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2188 CopyVT, InFlag).getValue(1);
2189 SDValue Val = Chain.getValue(0);
2191 if (CopyVT != VA.getValVT())
2192 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2193 // This truncation won't change the value.
2194 DAG.getIntPtrConstant(1));
2196 InFlag = Chain.getValue(2);
2197 InVals.push_back(Val);
2203 //===----------------------------------------------------------------------===//
2204 // C & StdCall & Fast Calling Convention implementation
2205 //===----------------------------------------------------------------------===//
2206 // StdCall calling convention seems to be standard for many Windows' API
2207 // routines and around. It differs from C calling convention just a little:
2208 // callee should clean up the stack, not caller. Symbols should be also
2209 // decorated in some fancy way :) It doesn't support any vector arguments.
2210 // For info on fast calling convention see Fast Calling Convention (tail call)
2211 // implementation LowerX86_32FastCCCallTo.
2213 /// CallIsStructReturn - Determines whether a call uses struct return
2215 enum StructReturnType {
2220 static StructReturnType
2221 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2223 return NotStructReturn;
2225 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2226 if (!Flags.isSRet())
2227 return NotStructReturn;
2228 if (Flags.isInReg())
2229 return RegStructReturn;
2230 return StackStructReturn;
2233 /// Determines whether a function uses struct return semantics.
2234 static StructReturnType
2235 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2237 return NotStructReturn;
2239 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2240 if (!Flags.isSRet())
2241 return NotStructReturn;
2242 if (Flags.isInReg())
2243 return RegStructReturn;
2244 return StackStructReturn;
2247 /// Make a copy of an aggregate at address specified by "Src" to address
2248 /// "Dst" with size and alignment information specified by the specific
2249 /// parameter attribute. The copy will be passed as a byval function parameter.
2251 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2252 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2254 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2256 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2257 /*isVolatile*/false, /*AlwaysInline=*/true,
2258 MachinePointerInfo(), MachinePointerInfo());
2261 /// Return true if the calling convention is one that
2262 /// supports tail call optimization.
2263 static bool IsTailCallConvention(CallingConv::ID CC) {
2264 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2265 CC == CallingConv::HiPE);
2268 /// \brief Return true if the calling convention is a C calling convention.
2269 static bool IsCCallConvention(CallingConv::ID CC) {
2270 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2271 CC == CallingConv::X86_64_SysV);
2274 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2275 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2279 CallingConv::ID CalleeCC = CS.getCallingConv();
2280 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2286 /// Return true if the function is being made into
2287 /// a tailcall target by changing its ABI.
2288 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2289 bool GuaranteedTailCallOpt) {
2290 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2294 X86TargetLowering::LowerMemArgument(SDValue Chain,
2295 CallingConv::ID CallConv,
2296 const SmallVectorImpl<ISD::InputArg> &Ins,
2297 SDLoc dl, SelectionDAG &DAG,
2298 const CCValAssign &VA,
2299 MachineFrameInfo *MFI,
2301 // Create the nodes corresponding to a load from this parameter slot.
2302 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2303 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2304 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2305 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2308 // If value is passed by pointer we have address passed instead of the value
2310 if (VA.getLocInfo() == CCValAssign::Indirect)
2311 ValVT = VA.getLocVT();
2313 ValVT = VA.getValVT();
2315 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2316 // changed with more analysis.
2317 // In case of tail call optimization mark all arguments mutable. Since they
2318 // could be overwritten by lowering of arguments in case of a tail call.
2319 if (Flags.isByVal()) {
2320 unsigned Bytes = Flags.getByValSize();
2321 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2322 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2323 return DAG.getFrameIndex(FI, getPointerTy());
2325 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2326 VA.getLocMemOffset(), isImmutable);
2327 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2328 return DAG.getLoad(ValVT, dl, Chain, FIN,
2329 MachinePointerInfo::getFixedStack(FI),
2330 false, false, false, 0);
2334 // FIXME: Get this from tablegen.
2335 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2336 const X86Subtarget *Subtarget) {
2337 assert(Subtarget->is64Bit());
2339 if (Subtarget->isCallingConvWin64(CallConv)) {
2340 static const MCPhysReg GPR64ArgRegsWin64[] = {
2341 X86::RCX, X86::RDX, X86::R8, X86::R9
2343 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2346 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2347 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2349 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2352 // FIXME: Get this from tablegen.
2353 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2354 CallingConv::ID CallConv,
2355 const X86Subtarget *Subtarget) {
2356 assert(Subtarget->is64Bit());
2357 if (Subtarget->isCallingConvWin64(CallConv)) {
2358 // The XMM registers which might contain var arg parameters are shadowed
2359 // in their paired GPR. So we only need to save the GPR to their home
2361 // TODO: __vectorcall will change this.
2365 const Function *Fn = MF.getFunction();
2366 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2367 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2368 "SSE register cannot be used when SSE is disabled!");
2369 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2370 !Subtarget->hasSSE1())
2371 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2375 static const MCPhysReg XMMArgRegs64Bit[] = {
2376 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2377 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2379 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2383 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2384 CallingConv::ID CallConv,
2386 const SmallVectorImpl<ISD::InputArg> &Ins,
2389 SmallVectorImpl<SDValue> &InVals)
2391 MachineFunction &MF = DAG.getMachineFunction();
2392 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2394 const Function* Fn = MF.getFunction();
2395 if (Fn->hasExternalLinkage() &&
2396 Subtarget->isTargetCygMing() &&
2397 Fn->getName() == "main")
2398 FuncInfo->setForceFramePointer(true);
2400 MachineFrameInfo *MFI = MF.getFrameInfo();
2401 bool Is64Bit = Subtarget->is64Bit();
2402 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2404 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2405 "Var args not supported with calling convention fastcc, ghc or hipe");
2407 // Assign locations to all of the incoming arguments.
2408 SmallVector<CCValAssign, 16> ArgLocs;
2409 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2411 // Allocate shadow area for Win64
2413 CCInfo.AllocateStack(32, 8);
2415 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2417 unsigned LastVal = ~0U;
2419 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2420 CCValAssign &VA = ArgLocs[i];
2421 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2423 assert(VA.getValNo() != LastVal &&
2424 "Don't support value assigned to multiple locs yet");
2426 LastVal = VA.getValNo();
2428 if (VA.isRegLoc()) {
2429 EVT RegVT = VA.getLocVT();
2430 const TargetRegisterClass *RC;
2431 if (RegVT == MVT::i32)
2432 RC = &X86::GR32RegClass;
2433 else if (Is64Bit && RegVT == MVT::i64)
2434 RC = &X86::GR64RegClass;
2435 else if (RegVT == MVT::f32)
2436 RC = &X86::FR32RegClass;
2437 else if (RegVT == MVT::f64)
2438 RC = &X86::FR64RegClass;
2439 else if (RegVT.is512BitVector())
2440 RC = &X86::VR512RegClass;
2441 else if (RegVT.is256BitVector())
2442 RC = &X86::VR256RegClass;
2443 else if (RegVT.is128BitVector())
2444 RC = &X86::VR128RegClass;
2445 else if (RegVT == MVT::x86mmx)
2446 RC = &X86::VR64RegClass;
2447 else if (RegVT == MVT::i1)
2448 RC = &X86::VK1RegClass;
2449 else if (RegVT == MVT::v8i1)
2450 RC = &X86::VK8RegClass;
2451 else if (RegVT == MVT::v16i1)
2452 RC = &X86::VK16RegClass;
2453 else if (RegVT == MVT::v32i1)
2454 RC = &X86::VK32RegClass;
2455 else if (RegVT == MVT::v64i1)
2456 RC = &X86::VK64RegClass;
2458 llvm_unreachable("Unknown argument type!");
2460 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2461 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2463 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2464 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2466 if (VA.getLocInfo() == CCValAssign::SExt)
2467 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2468 DAG.getValueType(VA.getValVT()));
2469 else if (VA.getLocInfo() == CCValAssign::ZExt)
2470 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2471 DAG.getValueType(VA.getValVT()));
2472 else if (VA.getLocInfo() == CCValAssign::BCvt)
2473 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2475 if (VA.isExtInLoc()) {
2476 // Handle MMX values passed in XMM regs.
2477 if (RegVT.isVector())
2478 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2480 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2483 assert(VA.isMemLoc());
2484 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2487 // If value is passed via pointer - do a load.
2488 if (VA.getLocInfo() == CCValAssign::Indirect)
2489 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2490 MachinePointerInfo(), false, false, false, 0);
2492 InVals.push_back(ArgValue);
2495 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2497 // The x86-64 ABIs require that for returning structs by value we copy
2498 // the sret argument into %rax/%eax (depending on ABI) for the return.
2499 // Win32 requires us to put the sret argument to %eax as well.
2500 // Save the argument into a virtual register so that we can access it
2501 // from the return points.
2502 if (Ins[i].Flags.isSRet()) {
2503 unsigned Reg = FuncInfo->getSRetReturnReg();
2505 MVT PtrTy = getPointerTy();
2506 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2507 FuncInfo->setSRetReturnReg(Reg);
2509 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2510 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2516 unsigned StackSize = CCInfo.getNextStackOffset();
2517 // Align stack specially for tail calls.
2518 if (FuncIsMadeTailCallSafe(CallConv,
2519 MF.getTarget().Options.GuaranteedTailCallOpt))
2520 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2522 // If the function takes variable number of arguments, make a frame index for
2523 // the start of the first vararg value... for expansion of llvm.va_start. We
2524 // can skip this if there are no va_start calls.
2525 if (MFI->hasVAStart() &&
2526 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2527 CallConv != CallingConv::X86_ThisCall))) {
2528 FuncInfo->setVarArgsFrameIndex(
2529 MFI->CreateFixedObject(1, StackSize, true));
2532 // Figure out if XMM registers are in use.
2533 assert(!(MF.getTarget().Options.UseSoftFloat &&
2534 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2535 "SSE register cannot be used when SSE is disabled!");
2537 // 64-bit calling conventions support varargs and register parameters, so we
2538 // have to do extra work to spill them in the prologue.
2539 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2540 // Find the first unallocated argument registers.
2541 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2542 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2543 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2544 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2545 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2546 "SSE register cannot be used when SSE is disabled!");
2548 // Gather all the live in physical registers.
2549 SmallVector<SDValue, 6> LiveGPRs;
2550 SmallVector<SDValue, 8> LiveXMMRegs;
2552 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2553 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2555 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2557 if (!ArgXMMs.empty()) {
2558 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2559 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2560 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2561 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2562 LiveXMMRegs.push_back(
2563 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2568 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2569 // Get to the caller-allocated home save location. Add 8 to account
2570 // for the return address.
2571 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2572 FuncInfo->setRegSaveFrameIndex(
2573 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2574 // Fixup to set vararg frame on shadow area (4 x i64).
2576 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2578 // For X86-64, if there are vararg parameters that are passed via
2579 // registers, then we must store them to their spots on the stack so
2580 // they may be loaded by deferencing the result of va_next.
2581 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2582 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2583 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2584 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2587 // Store the integer parameter registers.
2588 SmallVector<SDValue, 8> MemOps;
2589 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2591 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2592 for (SDValue Val : LiveGPRs) {
2593 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2594 DAG.getIntPtrConstant(Offset));
2596 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2597 MachinePointerInfo::getFixedStack(
2598 FuncInfo->getRegSaveFrameIndex(), Offset),
2600 MemOps.push_back(Store);
2604 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2605 // Now store the XMM (fp + vector) parameter registers.
2606 SmallVector<SDValue, 12> SaveXMMOps;
2607 SaveXMMOps.push_back(Chain);
2608 SaveXMMOps.push_back(ALVal);
2609 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2610 FuncInfo->getRegSaveFrameIndex()));
2611 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2612 FuncInfo->getVarArgsFPOffset()));
2613 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2615 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2616 MVT::Other, SaveXMMOps));
2619 if (!MemOps.empty())
2620 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2623 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2624 // Find the largest legal vector type.
2625 MVT VecVT = MVT::Other;
2626 // FIXME: Only some x86_32 calling conventions support AVX512.
2627 if (Subtarget->hasAVX512() &&
2628 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2629 CallConv == CallingConv::Intel_OCL_BI)))
2630 VecVT = MVT::v16f32;
2631 else if (Subtarget->hasAVX())
2633 else if (Subtarget->hasSSE2())
2636 // We forward some GPRs and some vector types.
2637 SmallVector<MVT, 2> RegParmTypes;
2638 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2639 RegParmTypes.push_back(IntVT);
2640 if (VecVT != MVT::Other)
2641 RegParmTypes.push_back(VecVT);
2643 // Compute the set of forwarded registers. The rest are scratch.
2644 SmallVectorImpl<ForwardedRegister> &Forwards =
2645 FuncInfo->getForwardedMustTailRegParms();
2646 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2648 // Conservatively forward AL on x86_64, since it might be used for varargs.
2649 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2650 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2651 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2654 // Copy all forwards from physical to virtual registers.
2655 for (ForwardedRegister &F : Forwards) {
2656 // FIXME: Can we use a less constrained schedule?
2657 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2658 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2659 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2663 // Some CCs need callee pop.
2664 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2665 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2666 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2668 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2669 // If this is an sret function, the return should pop the hidden pointer.
2670 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2671 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2672 argsAreStructReturn(Ins) == StackStructReturn)
2673 FuncInfo->setBytesToPopOnReturn(4);
2677 // RegSaveFrameIndex is X86-64 only.
2678 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2679 if (CallConv == CallingConv::X86_FastCall ||
2680 CallConv == CallingConv::X86_ThisCall)
2681 // fastcc functions can't have varargs.
2682 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2685 FuncInfo->setArgumentStackSize(StackSize);
2691 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2692 SDValue StackPtr, SDValue Arg,
2693 SDLoc dl, SelectionDAG &DAG,
2694 const CCValAssign &VA,
2695 ISD::ArgFlagsTy Flags) const {
2696 unsigned LocMemOffset = VA.getLocMemOffset();
2697 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2698 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2699 if (Flags.isByVal())
2700 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2702 return DAG.getStore(Chain, dl, Arg, PtrOff,
2703 MachinePointerInfo::getStack(LocMemOffset),
2707 /// Emit a load of return address if tail call
2708 /// optimization is performed and it is required.
2710 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2711 SDValue &OutRetAddr, SDValue Chain,
2712 bool IsTailCall, bool Is64Bit,
2713 int FPDiff, SDLoc dl) const {
2714 // Adjust the Return address stack slot.
2715 EVT VT = getPointerTy();
2716 OutRetAddr = getReturnAddressFrameIndex(DAG);
2718 // Load the "old" Return address.
2719 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2720 false, false, false, 0);
2721 return SDValue(OutRetAddr.getNode(), 1);
2724 /// Emit a store of the return address if tail call
2725 /// optimization is performed and it is required (FPDiff!=0).
2726 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2727 SDValue Chain, SDValue RetAddrFrIdx,
2728 EVT PtrVT, unsigned SlotSize,
2729 int FPDiff, SDLoc dl) {
2730 // Store the return address to the appropriate stack slot.
2731 if (!FPDiff) return Chain;
2732 // Calculate the new stack slot for the return address.
2733 int NewReturnAddrFI =
2734 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2736 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2737 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2738 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2744 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2745 SmallVectorImpl<SDValue> &InVals) const {
2746 SelectionDAG &DAG = CLI.DAG;
2748 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2749 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2750 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2751 SDValue Chain = CLI.Chain;
2752 SDValue Callee = CLI.Callee;
2753 CallingConv::ID CallConv = CLI.CallConv;
2754 bool &isTailCall = CLI.IsTailCall;
2755 bool isVarArg = CLI.IsVarArg;
2757 MachineFunction &MF = DAG.getMachineFunction();
2758 bool Is64Bit = Subtarget->is64Bit();
2759 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2760 StructReturnType SR = callIsStructReturn(Outs);
2761 bool IsSibcall = false;
2762 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2764 if (MF.getTarget().Options.DisableTailCalls)
2767 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2769 // Force this to be a tail call. The verifier rules are enough to ensure
2770 // that we can lower this successfully without moving the return address
2773 } else if (isTailCall) {
2774 // Check if it's really possible to do a tail call.
2775 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2776 isVarArg, SR != NotStructReturn,
2777 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2778 Outs, OutVals, Ins, DAG);
2780 // Sibcalls are automatically detected tailcalls which do not require
2782 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2789 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2790 "Var args not supported with calling convention fastcc, ghc or hipe");
2792 // Analyze operands of the call, assigning locations to each operand.
2793 SmallVector<CCValAssign, 16> ArgLocs;
2794 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2796 // Allocate shadow area for Win64
2798 CCInfo.AllocateStack(32, 8);
2800 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2802 // Get a count of how many bytes are to be pushed on the stack.
2803 unsigned NumBytes = CCInfo.getNextStackOffset();
2805 // This is a sibcall. The memory operands are available in caller's
2806 // own caller's stack.
2808 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2809 IsTailCallConvention(CallConv))
2810 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2813 if (isTailCall && !IsSibcall && !IsMustTail) {
2814 // Lower arguments at fp - stackoffset + fpdiff.
2815 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2817 FPDiff = NumBytesCallerPushed - NumBytes;
2819 // Set the delta of movement of the returnaddr stackslot.
2820 // But only set if delta is greater than previous delta.
2821 if (FPDiff < X86Info->getTCReturnAddrDelta())
2822 X86Info->setTCReturnAddrDelta(FPDiff);
2825 unsigned NumBytesToPush = NumBytes;
2826 unsigned NumBytesToPop = NumBytes;
2828 // If we have an inalloca argument, all stack space has already been allocated
2829 // for us and be right at the top of the stack. We don't support multiple
2830 // arguments passed in memory when using inalloca.
2831 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2833 if (!ArgLocs.back().isMemLoc())
2834 report_fatal_error("cannot use inalloca attribute on a register "
2836 if (ArgLocs.back().getLocMemOffset() != 0)
2837 report_fatal_error("any parameter with the inalloca attribute must be "
2838 "the only memory argument");
2842 Chain = DAG.getCALLSEQ_START(
2843 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2845 SDValue RetAddrFrIdx;
2846 // Load return address for tail calls.
2847 if (isTailCall && FPDiff)
2848 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2849 Is64Bit, FPDiff, dl);
2851 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2852 SmallVector<SDValue, 8> MemOpChains;
2855 // Walk the register/memloc assignments, inserting copies/loads. In the case
2856 // of tail call optimization arguments are handle later.
2857 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2858 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2859 // Skip inalloca arguments, they have already been written.
2860 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2861 if (Flags.isInAlloca())
2864 CCValAssign &VA = ArgLocs[i];
2865 EVT RegVT = VA.getLocVT();
2866 SDValue Arg = OutVals[i];
2867 bool isByVal = Flags.isByVal();
2869 // Promote the value if needed.
2870 switch (VA.getLocInfo()) {
2871 default: llvm_unreachable("Unknown loc info!");
2872 case CCValAssign::Full: break;
2873 case CCValAssign::SExt:
2874 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2876 case CCValAssign::ZExt:
2877 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2879 case CCValAssign::AExt:
2880 if (RegVT.is128BitVector()) {
2881 // Special case: passing MMX values in XMM registers.
2882 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2883 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2884 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2886 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2888 case CCValAssign::BCvt:
2889 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2891 case CCValAssign::Indirect: {
2892 // Store the argument.
2893 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2894 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2895 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2896 MachinePointerInfo::getFixedStack(FI),
2903 if (VA.isRegLoc()) {
2904 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2905 if (isVarArg && IsWin64) {
2906 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2907 // shadow reg if callee is a varargs function.
2908 unsigned ShadowReg = 0;
2909 switch (VA.getLocReg()) {
2910 case X86::XMM0: ShadowReg = X86::RCX; break;
2911 case X86::XMM1: ShadowReg = X86::RDX; break;
2912 case X86::XMM2: ShadowReg = X86::R8; break;
2913 case X86::XMM3: ShadowReg = X86::R9; break;
2916 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2918 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2919 assert(VA.isMemLoc());
2920 if (!StackPtr.getNode())
2921 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2923 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2924 dl, DAG, VA, Flags));
2928 if (!MemOpChains.empty())
2929 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2931 if (Subtarget->isPICStyleGOT()) {
2932 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2935 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2936 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2938 // If we are tail calling and generating PIC/GOT style code load the
2939 // address of the callee into ECX. The value in ecx is used as target of
2940 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2941 // for tail calls on PIC/GOT architectures. Normally we would just put the
2942 // address of GOT into ebx and then call target@PLT. But for tail calls
2943 // ebx would be restored (since ebx is callee saved) before jumping to the
2946 // Note: The actual moving to ECX is done further down.
2947 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2948 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2949 !G->getGlobal()->hasProtectedVisibility())
2950 Callee = LowerGlobalAddress(Callee, DAG);
2951 else if (isa<ExternalSymbolSDNode>(Callee))
2952 Callee = LowerExternalSymbol(Callee, DAG);
2956 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2957 // From AMD64 ABI document:
2958 // For calls that may call functions that use varargs or stdargs
2959 // (prototype-less calls or calls to functions containing ellipsis (...) in
2960 // the declaration) %al is used as hidden argument to specify the number
2961 // of SSE registers used. The contents of %al do not need to match exactly
2962 // the number of registers, but must be an ubound on the number of SSE
2963 // registers used and is in the range 0 - 8 inclusive.
2965 // Count the number of XMM registers allocated.
2966 static const MCPhysReg XMMArgRegs[] = {
2967 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2968 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2970 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2971 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2972 && "SSE registers cannot be used when SSE is disabled");
2974 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2975 DAG.getConstant(NumXMMRegs, MVT::i8)));
2978 if (isVarArg && IsMustTail) {
2979 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2980 for (const auto &F : Forwards) {
2981 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2982 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2986 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2987 // don't need this because the eligibility check rejects calls that require
2988 // shuffling arguments passed in memory.
2989 if (!IsSibcall && isTailCall) {
2990 // Force all the incoming stack arguments to be loaded from the stack
2991 // before any new outgoing arguments are stored to the stack, because the
2992 // outgoing stack slots may alias the incoming argument stack slots, and
2993 // the alias isn't otherwise explicit. This is slightly more conservative
2994 // than necessary, because it means that each store effectively depends
2995 // on every argument instead of just those arguments it would clobber.
2996 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2998 SmallVector<SDValue, 8> MemOpChains2;
3001 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3002 CCValAssign &VA = ArgLocs[i];
3005 assert(VA.isMemLoc());
3006 SDValue Arg = OutVals[i];
3007 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3008 // Skip inalloca arguments. They don't require any work.
3009 if (Flags.isInAlloca())
3011 // Create frame index.
3012 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3013 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3014 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3015 FIN = DAG.getFrameIndex(FI, getPointerTy());
3017 if (Flags.isByVal()) {
3018 // Copy relative to framepointer.
3019 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3020 if (!StackPtr.getNode())
3021 StackPtr = DAG.getCopyFromReg(Chain, dl,
3022 RegInfo->getStackRegister(),
3024 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3026 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3030 // Store relative to framepointer.
3031 MemOpChains2.push_back(
3032 DAG.getStore(ArgChain, dl, Arg, FIN,
3033 MachinePointerInfo::getFixedStack(FI),
3038 if (!MemOpChains2.empty())
3039 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3041 // Store the return address to the appropriate stack slot.
3042 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3043 getPointerTy(), RegInfo->getSlotSize(),
3047 // Build a sequence of copy-to-reg nodes chained together with token chain
3048 // and flag operands which copy the outgoing args into registers.
3050 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3051 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3052 RegsToPass[i].second, InFlag);
3053 InFlag = Chain.getValue(1);
3056 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3057 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3058 // In the 64-bit large code model, we have to make all calls
3059 // through a register, since the call instruction's 32-bit
3060 // pc-relative offset may not be large enough to hold the whole
3062 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3063 // If the callee is a GlobalAddress node (quite common, every direct call
3064 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3066 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3068 // We should use extra load for direct calls to dllimported functions in
3070 const GlobalValue *GV = G->getGlobal();
3071 if (!GV->hasDLLImportStorageClass()) {
3072 unsigned char OpFlags = 0;
3073 bool ExtraLoad = false;
3074 unsigned WrapperKind = ISD::DELETED_NODE;
3076 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3077 // external symbols most go through the PLT in PIC mode. If the symbol
3078 // has hidden or protected visibility, or if it is static or local, then
3079 // we don't need to use the PLT - we can directly call it.
3080 if (Subtarget->isTargetELF() &&
3081 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3082 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3083 OpFlags = X86II::MO_PLT;
3084 } else if (Subtarget->isPICStyleStubAny() &&
3085 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3086 (!Subtarget->getTargetTriple().isMacOSX() ||
3087 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3088 // PC-relative references to external symbols should go through $stub,
3089 // unless we're building with the leopard linker or later, which
3090 // automatically synthesizes these stubs.
3091 OpFlags = X86II::MO_DARWIN_STUB;
3092 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3093 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3094 // If the function is marked as non-lazy, generate an indirect call
3095 // which loads from the GOT directly. This avoids runtime overhead
3096 // at the cost of eager binding (and one extra byte of encoding).
3097 OpFlags = X86II::MO_GOTPCREL;
3098 WrapperKind = X86ISD::WrapperRIP;
3102 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3103 G->getOffset(), OpFlags);
3105 // Add a wrapper if needed.
3106 if (WrapperKind != ISD::DELETED_NODE)
3107 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3108 // Add extra indirection if needed.
3110 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3111 MachinePointerInfo::getGOT(),
3112 false, false, false, 0);
3114 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3115 unsigned char OpFlags = 0;
3117 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3118 // external symbols should go through the PLT.
3119 if (Subtarget->isTargetELF() &&
3120 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3121 OpFlags = X86II::MO_PLT;
3122 } else if (Subtarget->isPICStyleStubAny() &&
3123 (!Subtarget->getTargetTriple().isMacOSX() ||
3124 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3125 // PC-relative references to external symbols should go through $stub,
3126 // unless we're building with the leopard linker or later, which
3127 // automatically synthesizes these stubs.
3128 OpFlags = X86II::MO_DARWIN_STUB;
3131 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3133 } else if (Subtarget->isTarget64BitILP32() &&
3134 Callee->getValueType(0) == MVT::i32) {
3135 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3136 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3139 // Returns a chain & a flag for retval copy to use.
3140 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3141 SmallVector<SDValue, 8> Ops;
3143 if (!IsSibcall && isTailCall) {
3144 Chain = DAG.getCALLSEQ_END(Chain,
3145 DAG.getIntPtrConstant(NumBytesToPop, true),
3146 DAG.getIntPtrConstant(0, true), InFlag, dl);
3147 InFlag = Chain.getValue(1);
3150 Ops.push_back(Chain);
3151 Ops.push_back(Callee);
3154 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3156 // Add argument registers to the end of the list so that they are known live
3158 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3159 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3160 RegsToPass[i].second.getValueType()));
3162 // Add a register mask operand representing the call-preserved registers.
3163 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3164 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3165 assert(Mask && "Missing call preserved mask for calling convention");
3166 Ops.push_back(DAG.getRegisterMask(Mask));
3168 if (InFlag.getNode())
3169 Ops.push_back(InFlag);
3173 //// If this is the first return lowered for this function, add the regs
3174 //// to the liveout set for the function.
3175 // This isn't right, although it's probably harmless on x86; liveouts
3176 // should be computed from returns not tail calls. Consider a void
3177 // function making a tail call to a function returning int.
3178 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3181 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3182 InFlag = Chain.getValue(1);
3184 // Create the CALLSEQ_END node.
3185 unsigned NumBytesForCalleeToPop;
3186 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3187 DAG.getTarget().Options.GuaranteedTailCallOpt))
3188 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3189 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3190 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3191 SR == StackStructReturn)
3192 // If this is a call to a struct-return function, the callee
3193 // pops the hidden struct pointer, so we have to push it back.
3194 // This is common for Darwin/X86, Linux & Mingw32 targets.
3195 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3196 NumBytesForCalleeToPop = 4;
3198 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3200 // Returns a flag for retval copy to use.
3202 Chain = DAG.getCALLSEQ_END(Chain,
3203 DAG.getIntPtrConstant(NumBytesToPop, true),
3204 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3207 InFlag = Chain.getValue(1);
3210 // Handle result values, copying them out of physregs into vregs that we
3212 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3213 Ins, dl, DAG, InVals);
3216 //===----------------------------------------------------------------------===//
3217 // Fast Calling Convention (tail call) implementation
3218 //===----------------------------------------------------------------------===//
3220 // Like std call, callee cleans arguments, convention except that ECX is
3221 // reserved for storing the tail called function address. Only 2 registers are
3222 // free for argument passing (inreg). Tail call optimization is performed
3224 // * tailcallopt is enabled
3225 // * caller/callee are fastcc
3226 // On X86_64 architecture with GOT-style position independent code only local
3227 // (within module) calls are supported at the moment.
3228 // To keep the stack aligned according to platform abi the function
3229 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3230 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3231 // If a tail called function callee has more arguments than the caller the
3232 // caller needs to make sure that there is room to move the RETADDR to. This is
3233 // achieved by reserving an area the size of the argument delta right after the
3234 // original RETADDR, but before the saved framepointer or the spilled registers
3235 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3247 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3248 /// for a 16 byte align requirement.
3250 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3251 SelectionDAG& DAG) const {
3252 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3253 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3254 unsigned StackAlignment = TFI.getStackAlignment();
3255 uint64_t AlignMask = StackAlignment - 1;
3256 int64_t Offset = StackSize;
3257 unsigned SlotSize = RegInfo->getSlotSize();
3258 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3259 // Number smaller than 12 so just add the difference.
3260 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3262 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3263 Offset = ((~AlignMask) & Offset) + StackAlignment +
3264 (StackAlignment-SlotSize);
3269 /// MatchingStackOffset - Return true if the given stack call argument is
3270 /// already available in the same position (relatively) of the caller's
3271 /// incoming argument stack.
3273 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3274 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3275 const X86InstrInfo *TII) {
3276 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3278 if (Arg.getOpcode() == ISD::CopyFromReg) {
3279 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3280 if (!TargetRegisterInfo::isVirtualRegister(VR))
3282 MachineInstr *Def = MRI->getVRegDef(VR);
3285 if (!Flags.isByVal()) {
3286 if (!TII->isLoadFromStackSlot(Def, FI))
3289 unsigned Opcode = Def->getOpcode();
3290 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3291 Opcode == X86::LEA64_32r) &&
3292 Def->getOperand(1).isFI()) {
3293 FI = Def->getOperand(1).getIndex();
3294 Bytes = Flags.getByValSize();
3298 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3299 if (Flags.isByVal())
3300 // ByVal argument is passed in as a pointer but it's now being
3301 // dereferenced. e.g.
3302 // define @foo(%struct.X* %A) {
3303 // tail call @bar(%struct.X* byval %A)
3306 SDValue Ptr = Ld->getBasePtr();
3307 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3310 FI = FINode->getIndex();
3311 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3312 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3313 FI = FINode->getIndex();
3314 Bytes = Flags.getByValSize();
3318 assert(FI != INT_MAX);
3319 if (!MFI->isFixedObjectIndex(FI))
3321 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3324 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3325 /// for tail call optimization. Targets which want to do tail call
3326 /// optimization should implement this function.
3328 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3329 CallingConv::ID CalleeCC,
3331 bool isCalleeStructRet,
3332 bool isCallerStructRet,
3334 const SmallVectorImpl<ISD::OutputArg> &Outs,
3335 const SmallVectorImpl<SDValue> &OutVals,
3336 const SmallVectorImpl<ISD::InputArg> &Ins,
3337 SelectionDAG &DAG) const {
3338 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3341 // If -tailcallopt is specified, make fastcc functions tail-callable.
3342 const MachineFunction &MF = DAG.getMachineFunction();
3343 const Function *CallerF = MF.getFunction();
3345 // If the function return type is x86_fp80 and the callee return type is not,
3346 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3347 // perform a tailcall optimization here.
3348 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3351 CallingConv::ID CallerCC = CallerF->getCallingConv();
3352 bool CCMatch = CallerCC == CalleeCC;
3353 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3354 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3356 // Win64 functions have extra shadow space for argument homing. Don't do the
3357 // sibcall if the caller and callee have mismatched expectations for this
3359 if (IsCalleeWin64 != IsCallerWin64)
3362 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3363 if (IsTailCallConvention(CalleeCC) && CCMatch)
3368 // Look for obvious safe cases to perform tail call optimization that do not
3369 // require ABI changes. This is what gcc calls sibcall.
3371 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3372 // emit a special epilogue.
3373 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3374 if (RegInfo->needsStackRealignment(MF))
3377 // Also avoid sibcall optimization if either caller or callee uses struct
3378 // return semantics.
3379 if (isCalleeStructRet || isCallerStructRet)
3382 // An stdcall/thiscall caller is expected to clean up its arguments; the
3383 // callee isn't going to do that.
3384 // FIXME: this is more restrictive than needed. We could produce a tailcall
3385 // when the stack adjustment matches. For example, with a thiscall that takes
3386 // only one argument.
3387 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3388 CallerCC == CallingConv::X86_ThisCall))
3391 // Do not sibcall optimize vararg calls unless all arguments are passed via
3393 if (isVarArg && !Outs.empty()) {
3395 // Optimizing for varargs on Win64 is unlikely to be safe without
3396 // additional testing.
3397 if (IsCalleeWin64 || IsCallerWin64)
3400 SmallVector<CCValAssign, 16> ArgLocs;
3401 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3404 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3405 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3406 if (!ArgLocs[i].isRegLoc())
3410 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3411 // stack. Therefore, if it's not used by the call it is not safe to optimize
3412 // this into a sibcall.
3413 bool Unused = false;
3414 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3421 SmallVector<CCValAssign, 16> RVLocs;
3422 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3424 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3425 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3426 CCValAssign &VA = RVLocs[i];
3427 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3432 // If the calling conventions do not match, then we'd better make sure the
3433 // results are returned in the same way as what the caller expects.
3435 SmallVector<CCValAssign, 16> RVLocs1;
3436 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3438 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3440 SmallVector<CCValAssign, 16> RVLocs2;
3441 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3443 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3445 if (RVLocs1.size() != RVLocs2.size())
3447 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3448 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3450 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3452 if (RVLocs1[i].isRegLoc()) {
3453 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3456 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3462 // If the callee takes no arguments then go on to check the results of the
3464 if (!Outs.empty()) {
3465 // Check if stack adjustment is needed. For now, do not do this if any
3466 // argument is passed on the stack.
3467 SmallVector<CCValAssign, 16> ArgLocs;
3468 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3471 // Allocate shadow area for Win64
3473 CCInfo.AllocateStack(32, 8);
3475 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3476 if (CCInfo.getNextStackOffset()) {
3477 MachineFunction &MF = DAG.getMachineFunction();
3478 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3481 // Check if the arguments are already laid out in the right way as
3482 // the caller's fixed stack objects.
3483 MachineFrameInfo *MFI = MF.getFrameInfo();
3484 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3485 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3486 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3487 CCValAssign &VA = ArgLocs[i];
3488 SDValue Arg = OutVals[i];
3489 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3490 if (VA.getLocInfo() == CCValAssign::Indirect)
3492 if (!VA.isRegLoc()) {
3493 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3500 // If the tailcall address may be in a register, then make sure it's
3501 // possible to register allocate for it. In 32-bit, the call address can
3502 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3503 // callee-saved registers are restored. These happen to be the same
3504 // registers used to pass 'inreg' arguments so watch out for those.
3505 if (!Subtarget->is64Bit() &&
3506 ((!isa<GlobalAddressSDNode>(Callee) &&
3507 !isa<ExternalSymbolSDNode>(Callee)) ||
3508 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3509 unsigned NumInRegs = 0;
3510 // In PIC we need an extra register to formulate the address computation
3512 unsigned MaxInRegs =
3513 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3515 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3516 CCValAssign &VA = ArgLocs[i];
3519 unsigned Reg = VA.getLocReg();
3522 case X86::EAX: case X86::EDX: case X86::ECX:
3523 if (++NumInRegs == MaxInRegs)
3535 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3536 const TargetLibraryInfo *libInfo) const {
3537 return X86::createFastISel(funcInfo, libInfo);
3540 //===----------------------------------------------------------------------===//
3541 // Other Lowering Hooks
3542 //===----------------------------------------------------------------------===//
3544 static bool MayFoldLoad(SDValue Op) {
3545 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3548 static bool MayFoldIntoStore(SDValue Op) {
3549 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3552 static bool isTargetShuffle(unsigned Opcode) {
3554 default: return false;
3555 case X86ISD::BLENDI:
3556 case X86ISD::PSHUFB:
3557 case X86ISD::PSHUFD:
3558 case X86ISD::PSHUFHW:
3559 case X86ISD::PSHUFLW:
3561 case X86ISD::PALIGNR:
3562 case X86ISD::MOVLHPS:
3563 case X86ISD::MOVLHPD:
3564 case X86ISD::MOVHLPS:
3565 case X86ISD::MOVLPS:
3566 case X86ISD::MOVLPD:
3567 case X86ISD::MOVSHDUP:
3568 case X86ISD::MOVSLDUP:
3569 case X86ISD::MOVDDUP:
3572 case X86ISD::UNPCKL:
3573 case X86ISD::UNPCKH:
3574 case X86ISD::VPERMILPI:
3575 case X86ISD::VPERM2X128:
3576 case X86ISD::VPERMI:
3581 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3582 SDValue V1, unsigned TargetMask,
3583 SelectionDAG &DAG) {
3585 default: llvm_unreachable("Unknown x86 shuffle node");
3586 case X86ISD::PSHUFD:
3587 case X86ISD::PSHUFHW:
3588 case X86ISD::PSHUFLW:
3589 case X86ISD::VPERMILPI:
3590 case X86ISD::VPERMI:
3591 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3595 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3596 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3598 default: llvm_unreachable("Unknown x86 shuffle node");
3599 case X86ISD::MOVLHPS:
3600 case X86ISD::MOVLHPD:
3601 case X86ISD::MOVHLPS:
3602 case X86ISD::MOVLPS:
3603 case X86ISD::MOVLPD:
3606 case X86ISD::UNPCKL:
3607 case X86ISD::UNPCKH:
3608 return DAG.getNode(Opc, dl, VT, V1, V2);
3612 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3613 MachineFunction &MF = DAG.getMachineFunction();
3614 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3615 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3616 int ReturnAddrIndex = FuncInfo->getRAIndex();
3618 if (ReturnAddrIndex == 0) {
3619 // Set up a frame object for the return address.
3620 unsigned SlotSize = RegInfo->getSlotSize();
3621 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3624 FuncInfo->setRAIndex(ReturnAddrIndex);
3627 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3630 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3631 bool hasSymbolicDisplacement) {
3632 // Offset should fit into 32 bit immediate field.
3633 if (!isInt<32>(Offset))
3636 // If we don't have a symbolic displacement - we don't have any extra
3638 if (!hasSymbolicDisplacement)
3641 // FIXME: Some tweaks might be needed for medium code model.
3642 if (M != CodeModel::Small && M != CodeModel::Kernel)
3645 // For small code model we assume that latest object is 16MB before end of 31
3646 // bits boundary. We may also accept pretty large negative constants knowing
3647 // that all objects are in the positive half of address space.
3648 if (M == CodeModel::Small && Offset < 16*1024*1024)
3651 // For kernel code model we know that all object resist in the negative half
3652 // of 32bits address space. We may not accept negative offsets, since they may
3653 // be just off and we may accept pretty large positive ones.
3654 if (M == CodeModel::Kernel && Offset >= 0)
3660 /// isCalleePop - Determines whether the callee is required to pop its
3661 /// own arguments. Callee pop is necessary to support tail calls.
3662 bool X86::isCalleePop(CallingConv::ID CallingConv,
3663 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3664 switch (CallingConv) {
3667 case CallingConv::X86_StdCall:
3668 case CallingConv::X86_FastCall:
3669 case CallingConv::X86_ThisCall:
3671 case CallingConv::Fast:
3672 case CallingConv::GHC:
3673 case CallingConv::HiPE:
3680 /// \brief Return true if the condition is an unsigned comparison operation.
3681 static bool isX86CCUnsigned(unsigned X86CC) {
3683 default: llvm_unreachable("Invalid integer condition!");
3684 case X86::COND_E: return true;
3685 case X86::COND_G: return false;
3686 case X86::COND_GE: return false;
3687 case X86::COND_L: return false;
3688 case X86::COND_LE: return false;
3689 case X86::COND_NE: return true;
3690 case X86::COND_B: return true;
3691 case X86::COND_A: return true;
3692 case X86::COND_BE: return true;
3693 case X86::COND_AE: return true;
3695 llvm_unreachable("covered switch fell through?!");
3698 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3699 /// specific condition code, returning the condition code and the LHS/RHS of the
3700 /// comparison to make.
3701 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3702 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3704 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3705 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3706 // X > -1 -> X == 0, jump !sign.
3707 RHS = DAG.getConstant(0, RHS.getValueType());
3708 return X86::COND_NS;
3710 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3711 // X < 0 -> X == 0, jump on sign.
3714 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3716 RHS = DAG.getConstant(0, RHS.getValueType());
3717 return X86::COND_LE;
3721 switch (SetCCOpcode) {
3722 default: llvm_unreachable("Invalid integer condition!");
3723 case ISD::SETEQ: return X86::COND_E;
3724 case ISD::SETGT: return X86::COND_G;
3725 case ISD::SETGE: return X86::COND_GE;
3726 case ISD::SETLT: return X86::COND_L;
3727 case ISD::SETLE: return X86::COND_LE;
3728 case ISD::SETNE: return X86::COND_NE;
3729 case ISD::SETULT: return X86::COND_B;
3730 case ISD::SETUGT: return X86::COND_A;
3731 case ISD::SETULE: return X86::COND_BE;
3732 case ISD::SETUGE: return X86::COND_AE;
3736 // First determine if it is required or is profitable to flip the operands.
3738 // If LHS is a foldable load, but RHS is not, flip the condition.
3739 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3740 !ISD::isNON_EXTLoad(RHS.getNode())) {
3741 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3742 std::swap(LHS, RHS);
3745 switch (SetCCOpcode) {
3751 std::swap(LHS, RHS);
3755 // On a floating point condition, the flags are set as follows:
3757 // 0 | 0 | 0 | X > Y
3758 // 0 | 0 | 1 | X < Y
3759 // 1 | 0 | 0 | X == Y
3760 // 1 | 1 | 1 | unordered
3761 switch (SetCCOpcode) {
3762 default: llvm_unreachable("Condcode should be pre-legalized away");
3764 case ISD::SETEQ: return X86::COND_E;
3765 case ISD::SETOLT: // flipped
3767 case ISD::SETGT: return X86::COND_A;
3768 case ISD::SETOLE: // flipped
3770 case ISD::SETGE: return X86::COND_AE;
3771 case ISD::SETUGT: // flipped
3773 case ISD::SETLT: return X86::COND_B;
3774 case ISD::SETUGE: // flipped
3776 case ISD::SETLE: return X86::COND_BE;
3778 case ISD::SETNE: return X86::COND_NE;
3779 case ISD::SETUO: return X86::COND_P;
3780 case ISD::SETO: return X86::COND_NP;
3782 case ISD::SETUNE: return X86::COND_INVALID;
3786 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3787 /// code. Current x86 isa includes the following FP cmov instructions:
3788 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3789 static bool hasFPCMov(unsigned X86CC) {
3805 /// isFPImmLegal - Returns true if the target can instruction select the
3806 /// specified FP immediate natively. If false, the legalizer will
3807 /// materialize the FP immediate as a load from a constant pool.
3808 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3809 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3810 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3816 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3817 ISD::LoadExtType ExtTy,
3819 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3820 // relocation target a movq or addq instruction: don't let the load shrink.
3821 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3822 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3823 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3824 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3828 /// \brief Returns true if it is beneficial to convert a load of a constant
3829 /// to just the constant itself.
3830 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3832 assert(Ty->isIntegerTy());
3834 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3835 if (BitSize == 0 || BitSize > 64)
3840 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3841 unsigned Index) const {
3842 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3845 return (Index == 0 || Index == ResVT.getVectorNumElements());
3848 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3849 // Speculate cttz only if we can directly use TZCNT.
3850 return Subtarget->hasBMI();
3853 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3854 // Speculate ctlz only if we can directly use LZCNT.
3855 return Subtarget->hasLZCNT();
3858 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3859 /// the specified range (L, H].
3860 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3861 return (Val < 0) || (Val >= Low && Val < Hi);
3864 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3865 /// specified value.
3866 static bool isUndefOrEqual(int Val, int CmpVal) {
3867 return (Val < 0 || Val == CmpVal);
3870 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3871 /// from position Pos and ending in Pos+Size, falls within the specified
3872 /// sequential range (Low, Low+Size]. or is undef.
3873 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3874 unsigned Pos, unsigned Size, int Low) {
3875 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3876 if (!isUndefOrEqual(Mask[i], Low))
3881 /// isVEXTRACTIndex - Return true if the specified
3882 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3883 /// suitable for instruction that extract 128 or 256 bit vectors
3884 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3885 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3886 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3889 // The index should be aligned on a vecWidth-bit boundary.
3891 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3893 MVT VT = N->getSimpleValueType(0);
3894 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3895 bool Result = (Index * ElSize) % vecWidth == 0;
3900 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3901 /// operand specifies a subvector insert that is suitable for input to
3902 /// insertion of 128 or 256-bit subvectors
3903 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3904 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3905 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3907 // The index should be aligned on a vecWidth-bit boundary.
3909 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3911 MVT VT = N->getSimpleValueType(0);
3912 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3913 bool Result = (Index * ElSize) % vecWidth == 0;
3918 bool X86::isVINSERT128Index(SDNode *N) {
3919 return isVINSERTIndex(N, 128);
3922 bool X86::isVINSERT256Index(SDNode *N) {
3923 return isVINSERTIndex(N, 256);
3926 bool X86::isVEXTRACT128Index(SDNode *N) {
3927 return isVEXTRACTIndex(N, 128);
3930 bool X86::isVEXTRACT256Index(SDNode *N) {
3931 return isVEXTRACTIndex(N, 256);
3934 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3935 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3936 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3937 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3940 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3942 MVT VecVT = N->getOperand(0).getSimpleValueType();
3943 MVT ElVT = VecVT.getVectorElementType();
3945 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3946 return Index / NumElemsPerChunk;
3949 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3950 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3951 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3952 llvm_unreachable("Illegal insert subvector for VINSERT");
3955 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3957 MVT VecVT = N->getSimpleValueType(0);
3958 MVT ElVT = VecVT.getVectorElementType();
3960 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3961 return Index / NumElemsPerChunk;
3964 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3965 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3966 /// and VINSERTI128 instructions.
3967 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3968 return getExtractVEXTRACTImmediate(N, 128);
3971 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3972 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3973 /// and VINSERTI64x4 instructions.
3974 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3975 return getExtractVEXTRACTImmediate(N, 256);
3978 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3979 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3980 /// and VINSERTI128 instructions.
3981 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3982 return getInsertVINSERTImmediate(N, 128);
3985 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3986 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3987 /// and VINSERTI64x4 instructions.
3988 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3989 return getInsertVINSERTImmediate(N, 256);
3992 /// isZero - Returns true if Elt is a constant integer zero
3993 static bool isZero(SDValue V) {
3994 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3995 return C && C->isNullValue();
3998 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4000 bool X86::isZeroNode(SDValue Elt) {
4003 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4004 return CFP->getValueAPF().isPosZero();
4008 /// getZeroVector - Returns a vector of specified type with all zero elements.
4010 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4011 SelectionDAG &DAG, SDLoc dl) {
4012 assert(VT.isVector() && "Expected a vector type");
4014 // Always build SSE zero vectors as <4 x i32> bitcasted
4015 // to their dest type. This ensures they get CSE'd.
4017 if (VT.is128BitVector()) { // SSE
4018 if (Subtarget->hasSSE2()) { // SSE2
4019 SDValue Cst = DAG.getConstant(0, MVT::i32);
4020 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4022 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4023 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4025 } else if (VT.is256BitVector()) { // AVX
4026 if (Subtarget->hasInt256()) { // AVX2
4027 SDValue Cst = DAG.getConstant(0, MVT::i32);
4028 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4029 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4031 // 256-bit logic and arithmetic instructions in AVX are all
4032 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4033 SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
4034 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4035 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4037 } else if (VT.is512BitVector()) { // AVX-512
4038 SDValue Cst = DAG.getConstant(0, MVT::i32);
4039 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4040 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4041 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4042 } else if (VT.getScalarType() == MVT::i1) {
4044 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4045 && "Unexpected vector type");
4046 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4047 && "Unexpected vector type");
4048 SDValue Cst = DAG.getConstant(0, MVT::i1);
4049 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4050 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4052 llvm_unreachable("Unexpected vector type");
4054 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4057 /// getOnesVector - Returns a vector of specified type with all bits set.
4058 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4059 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4060 /// Then bitcast to their original type, ensuring they get CSE'd.
4061 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4063 assert(VT.isVector() && "Expected a vector type");
4065 SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4067 if (VT.is256BitVector()) {
4068 if (HasInt256) { // AVX2
4069 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4070 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4072 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4073 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4075 } else if (VT.is128BitVector()) {
4076 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4078 llvm_unreachable("Unexpected vector type");
4080 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4083 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4084 /// operation of specified width.
4085 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4087 unsigned NumElems = VT.getVectorNumElements();
4088 SmallVector<int, 8> Mask;
4089 Mask.push_back(NumElems);
4090 for (unsigned i = 1; i != NumElems; ++i)
4092 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4095 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4096 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4098 unsigned NumElems = VT.getVectorNumElements();
4099 SmallVector<int, 8> Mask;
4100 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4102 Mask.push_back(i + NumElems);
4104 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4107 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4108 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4110 unsigned NumElems = VT.getVectorNumElements();
4111 SmallVector<int, 8> Mask;
4112 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4113 Mask.push_back(i + Half);
4114 Mask.push_back(i + NumElems + Half);
4116 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4119 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4120 /// vector of zero or undef vector. This produces a shuffle where the low
4121 /// element of V2 is swizzled into the zero/undef vector, landing at element
4122 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4123 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4125 const X86Subtarget *Subtarget,
4126 SelectionDAG &DAG) {
4127 MVT VT = V2.getSimpleValueType();
4129 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4130 unsigned NumElems = VT.getVectorNumElements();
4131 SmallVector<int, 16> MaskVec;
4132 for (unsigned i = 0; i != NumElems; ++i)
4133 // If this is the insertion idx, put the low elt of V2 here.
4134 MaskVec.push_back(i == Idx ? NumElems : i);
4135 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4138 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4139 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4140 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4141 /// shuffles which use a single input multiple times, and in those cases it will
4142 /// adjust the mask to only have indices within that single input.
4143 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4144 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4145 unsigned NumElems = VT.getVectorNumElements();
4149 bool IsFakeUnary = false;
4150 switch(N->getOpcode()) {
4151 case X86ISD::BLENDI:
4152 ImmN = N->getOperand(N->getNumOperands()-1);
4153 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4156 ImmN = N->getOperand(N->getNumOperands()-1);
4157 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4158 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4160 case X86ISD::UNPCKH:
4161 DecodeUNPCKHMask(VT, Mask);
4162 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4164 case X86ISD::UNPCKL:
4165 DecodeUNPCKLMask(VT, Mask);
4166 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4168 case X86ISD::MOVHLPS:
4169 DecodeMOVHLPSMask(NumElems, Mask);
4170 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4172 case X86ISD::MOVLHPS:
4173 DecodeMOVLHPSMask(NumElems, Mask);
4174 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4176 case X86ISD::PALIGNR:
4177 ImmN = N->getOperand(N->getNumOperands()-1);
4178 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4180 case X86ISD::PSHUFD:
4181 case X86ISD::VPERMILPI:
4182 ImmN = N->getOperand(N->getNumOperands()-1);
4183 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4186 case X86ISD::PSHUFHW:
4187 ImmN = N->getOperand(N->getNumOperands()-1);
4188 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4191 case X86ISD::PSHUFLW:
4192 ImmN = N->getOperand(N->getNumOperands()-1);
4193 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4196 case X86ISD::PSHUFB: {
4198 SDValue MaskNode = N->getOperand(1);
4199 while (MaskNode->getOpcode() == ISD::BITCAST)
4200 MaskNode = MaskNode->getOperand(0);
4202 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4203 // If we have a build-vector, then things are easy.
4204 EVT VT = MaskNode.getValueType();
4205 assert(VT.isVector() &&
4206 "Can't produce a non-vector with a build_vector!");
4207 if (!VT.isInteger())
4210 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4212 SmallVector<uint64_t, 32> RawMask;
4213 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4214 SDValue Op = MaskNode->getOperand(i);
4215 if (Op->getOpcode() == ISD::UNDEF) {
4216 RawMask.push_back((uint64_t)SM_SentinelUndef);
4219 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4222 APInt MaskElement = CN->getAPIntValue();
4224 // We now have to decode the element which could be any integer size and
4225 // extract each byte of it.
4226 for (int j = 0; j < NumBytesPerElement; ++j) {
4227 // Note that this is x86 and so always little endian: the low byte is
4228 // the first byte of the mask.
4229 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4230 MaskElement = MaskElement.lshr(8);
4233 DecodePSHUFBMask(RawMask, Mask);
4237 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4241 SDValue Ptr = MaskLoad->getBasePtr();
4242 if (Ptr->getOpcode() == X86ISD::Wrapper)
4243 Ptr = Ptr->getOperand(0);
4245 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4246 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4249 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4250 DecodePSHUFBMask(C, Mask);
4258 case X86ISD::VPERMI:
4259 ImmN = N->getOperand(N->getNumOperands()-1);
4260 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4265 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4267 case X86ISD::VPERM2X128:
4268 ImmN = N->getOperand(N->getNumOperands()-1);
4269 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4270 if (Mask.empty()) return false;
4272 case X86ISD::MOVSLDUP:
4273 DecodeMOVSLDUPMask(VT, Mask);
4276 case X86ISD::MOVSHDUP:
4277 DecodeMOVSHDUPMask(VT, Mask);
4280 case X86ISD::MOVDDUP:
4281 DecodeMOVDDUPMask(VT, Mask);
4284 case X86ISD::MOVLHPD:
4285 case X86ISD::MOVLPD:
4286 case X86ISD::MOVLPS:
4287 // Not yet implemented
4289 default: llvm_unreachable("unknown target shuffle node");
4292 // If we have a fake unary shuffle, the shuffle mask is spread across two
4293 // inputs that are actually the same node. Re-map the mask to always point
4294 // into the first input.
4297 if (M >= (int)Mask.size())
4303 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4304 /// element of the result of the vector shuffle.
4305 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4308 return SDValue(); // Limit search depth.
4310 SDValue V = SDValue(N, 0);
4311 EVT VT = V.getValueType();
4312 unsigned Opcode = V.getOpcode();
4314 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4315 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4316 int Elt = SV->getMaskElt(Index);
4319 return DAG.getUNDEF(VT.getVectorElementType());
4321 unsigned NumElems = VT.getVectorNumElements();
4322 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4323 : SV->getOperand(1);
4324 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4327 // Recurse into target specific vector shuffles to find scalars.
4328 if (isTargetShuffle(Opcode)) {
4329 MVT ShufVT = V.getSimpleValueType();
4330 unsigned NumElems = ShufVT.getVectorNumElements();
4331 SmallVector<int, 16> ShuffleMask;
4334 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4337 int Elt = ShuffleMask[Index];
4339 return DAG.getUNDEF(ShufVT.getVectorElementType());
4341 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4343 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4347 // Actual nodes that may contain scalar elements
4348 if (Opcode == ISD::BITCAST) {
4349 V = V.getOperand(0);
4350 EVT SrcVT = V.getValueType();
4351 unsigned NumElems = VT.getVectorNumElements();
4353 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4357 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4358 return (Index == 0) ? V.getOperand(0)
4359 : DAG.getUNDEF(VT.getVectorElementType());
4361 if (V.getOpcode() == ISD::BUILD_VECTOR)
4362 return V.getOperand(Index);
4367 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4369 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4370 unsigned NumNonZero, unsigned NumZero,
4372 const X86Subtarget* Subtarget,
4373 const TargetLowering &TLI) {
4380 for (unsigned i = 0; i < 16; ++i) {
4381 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4382 if (ThisIsNonZero && First) {
4384 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4386 V = DAG.getUNDEF(MVT::v8i16);
4391 SDValue ThisElt, LastElt;
4392 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4393 if (LastIsNonZero) {
4394 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4395 MVT::i16, Op.getOperand(i-1));
4397 if (ThisIsNonZero) {
4398 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4399 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4400 ThisElt, DAG.getConstant(8, MVT::i8));
4402 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4406 if (ThisElt.getNode())
4407 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4408 DAG.getIntPtrConstant(i/2));
4412 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4415 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4417 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4418 unsigned NumNonZero, unsigned NumZero,
4420 const X86Subtarget* Subtarget,
4421 const TargetLowering &TLI) {
4428 for (unsigned i = 0; i < 8; ++i) {
4429 bool isNonZero = (NonZeros & (1 << i)) != 0;
4433 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4435 V = DAG.getUNDEF(MVT::v8i16);
4438 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4439 MVT::v8i16, V, Op.getOperand(i),
4440 DAG.getIntPtrConstant(i));
4447 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4448 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4449 const X86Subtarget *Subtarget,
4450 const TargetLowering &TLI) {
4451 // Find all zeroable elements.
4452 std::bitset<4> Zeroable;
4453 for (int i=0; i < 4; ++i) {
4454 SDValue Elt = Op->getOperand(i);
4455 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4457 assert(Zeroable.size() - Zeroable.count() > 1 &&
4458 "We expect at least two non-zero elements!");
4460 // We only know how to deal with build_vector nodes where elements are either
4461 // zeroable or extract_vector_elt with constant index.
4462 SDValue FirstNonZero;
4463 unsigned FirstNonZeroIdx;
4464 for (unsigned i=0; i < 4; ++i) {
4467 SDValue Elt = Op->getOperand(i);
4468 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4469 !isa<ConstantSDNode>(Elt.getOperand(1)))
4471 // Make sure that this node is extracting from a 128-bit vector.
4472 MVT VT = Elt.getOperand(0).getSimpleValueType();
4473 if (!VT.is128BitVector())
4475 if (!FirstNonZero.getNode()) {
4477 FirstNonZeroIdx = i;
4481 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4482 SDValue V1 = FirstNonZero.getOperand(0);
4483 MVT VT = V1.getSimpleValueType();
4485 // See if this build_vector can be lowered as a blend with zero.
4487 unsigned EltMaskIdx, EltIdx;
4489 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4490 if (Zeroable[EltIdx]) {
4491 // The zero vector will be on the right hand side.
4492 Mask[EltIdx] = EltIdx+4;
4496 Elt = Op->getOperand(EltIdx);
4497 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4498 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4499 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4501 Mask[EltIdx] = EltIdx;
4505 // Let the shuffle legalizer deal with blend operations.
4506 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4507 if (V1.getSimpleValueType() != VT)
4508 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4509 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4512 // See if we can lower this build_vector to a INSERTPS.
4513 if (!Subtarget->hasSSE41())
4516 SDValue V2 = Elt.getOperand(0);
4517 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4520 bool CanFold = true;
4521 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4525 SDValue Current = Op->getOperand(i);
4526 SDValue SrcVector = Current->getOperand(0);
4529 CanFold = SrcVector == V1 &&
4530 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4536 assert(V1.getNode() && "Expected at least two non-zero elements!");
4537 if (V1.getSimpleValueType() != MVT::v4f32)
4538 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4539 if (V2.getSimpleValueType() != MVT::v4f32)
4540 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4542 // Ok, we can emit an INSERTPS instruction.
4543 unsigned ZMask = Zeroable.to_ulong();
4545 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4546 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4547 SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4548 DAG.getIntPtrConstant(InsertPSMask));
4549 return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4552 /// Return a vector logical shift node.
4553 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4554 unsigned NumBits, SelectionDAG &DAG,
4555 const TargetLowering &TLI, SDLoc dl) {
4556 assert(VT.is128BitVector() && "Unknown type for VShift");
4557 MVT ShVT = MVT::v2i64;
4558 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4559 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4560 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4561 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4562 SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4563 return DAG.getNode(ISD::BITCAST, dl, VT,
4564 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4568 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4570 // Check if the scalar load can be widened into a vector load. And if
4571 // the address is "base + cst" see if the cst can be "absorbed" into
4572 // the shuffle mask.
4573 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4574 SDValue Ptr = LD->getBasePtr();
4575 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4577 EVT PVT = LD->getValueType(0);
4578 if (PVT != MVT::i32 && PVT != MVT::f32)
4583 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4584 FI = FINode->getIndex();
4586 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4587 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4588 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4589 Offset = Ptr.getConstantOperandVal(1);
4590 Ptr = Ptr.getOperand(0);
4595 // FIXME: 256-bit vector instructions don't require a strict alignment,
4596 // improve this code to support it better.
4597 unsigned RequiredAlign = VT.getSizeInBits()/8;
4598 SDValue Chain = LD->getChain();
4599 // Make sure the stack object alignment is at least 16 or 32.
4600 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4601 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4602 if (MFI->isFixedObjectIndex(FI)) {
4603 // Can't change the alignment. FIXME: It's possible to compute
4604 // the exact stack offset and reference FI + adjust offset instead.
4605 // If someone *really* cares about this. That's the way to implement it.
4608 MFI->setObjectAlignment(FI, RequiredAlign);
4612 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4613 // Ptr + (Offset & ~15).
4616 if ((Offset % RequiredAlign) & 3)
4618 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4620 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4621 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4623 int EltNo = (Offset - StartOffset) >> 2;
4624 unsigned NumElems = VT.getVectorNumElements();
4626 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4627 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4628 LD->getPointerInfo().getWithOffset(StartOffset),
4629 false, false, false, 0);
4631 SmallVector<int, 8> Mask(NumElems, EltNo);
4633 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4639 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4640 /// elements can be replaced by a single large load which has the same value as
4641 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4643 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4645 /// FIXME: we'd also like to handle the case where the last elements are zero
4646 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4647 /// There's even a handy isZeroNode for that purpose.
4648 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4649 SDLoc &DL, SelectionDAG &DAG,
4650 bool isAfterLegalize) {
4651 unsigned NumElems = Elts.size();
4653 LoadSDNode *LDBase = nullptr;
4654 unsigned LastLoadedElt = -1U;
4656 // For each element in the initializer, see if we've found a load or an undef.
4657 // If we don't find an initial load element, or later load elements are
4658 // non-consecutive, bail out.
4659 for (unsigned i = 0; i < NumElems; ++i) {
4660 SDValue Elt = Elts[i];
4661 // Look through a bitcast.
4662 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4663 Elt = Elt.getOperand(0);
4664 if (!Elt.getNode() ||
4665 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4668 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4670 LDBase = cast<LoadSDNode>(Elt.getNode());
4674 if (Elt.getOpcode() == ISD::UNDEF)
4677 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4678 EVT LdVT = Elt.getValueType();
4679 // Each loaded element must be the correct fractional portion of the
4680 // requested vector load.
4681 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4683 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4688 // If we have found an entire vector of loads and undefs, then return a large
4689 // load of the entire vector width starting at the base pointer. If we found
4690 // consecutive loads for the low half, generate a vzext_load node.
4691 if (LastLoadedElt == NumElems - 1) {
4692 assert(LDBase && "Did not find base load for merging consecutive loads");
4693 EVT EltVT = LDBase->getValueType(0);
4694 // Ensure that the input vector size for the merged loads matches the
4695 // cumulative size of the input elements.
4696 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4699 if (isAfterLegalize &&
4700 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4703 SDValue NewLd = SDValue();
4705 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4706 LDBase->getPointerInfo(), LDBase->isVolatile(),
4707 LDBase->isNonTemporal(), LDBase->isInvariant(),
4708 LDBase->getAlignment());
4710 if (LDBase->hasAnyUseOfValue(1)) {
4711 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4713 SDValue(NewLd.getNode(), 1));
4714 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4715 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4716 SDValue(NewLd.getNode(), 1));
4722 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4723 //of a v4i32 / v4f32. It's probably worth generalizing.
4724 EVT EltVT = VT.getVectorElementType();
4725 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4726 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4727 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4728 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4730 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4731 LDBase->getPointerInfo(),
4732 LDBase->getAlignment(),
4733 false/*isVolatile*/, true/*ReadMem*/,
4736 // Make sure the newly-created LOAD is in the same position as LDBase in
4737 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4738 // update uses of LDBase's output chain to use the TokenFactor.
4739 if (LDBase->hasAnyUseOfValue(1)) {
4740 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4741 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4742 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4743 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4744 SDValue(ResNode.getNode(), 1));
4747 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4752 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4753 /// to generate a splat value for the following cases:
4754 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4755 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4756 /// a scalar load, or a constant.
4757 /// The VBROADCAST node is returned when a pattern is found,
4758 /// or SDValue() otherwise.
4759 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4760 SelectionDAG &DAG) {
4761 // VBROADCAST requires AVX.
4762 // TODO: Splats could be generated for non-AVX CPUs using SSE
4763 // instructions, but there's less potential gain for only 128-bit vectors.
4764 if (!Subtarget->hasAVX())
4767 MVT VT = Op.getSimpleValueType();
4770 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4771 "Unsupported vector type for broadcast.");
4776 switch (Op.getOpcode()) {
4778 // Unknown pattern found.
4781 case ISD::BUILD_VECTOR: {
4782 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4783 BitVector UndefElements;
4784 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4786 // We need a splat of a single value to use broadcast, and it doesn't
4787 // make any sense if the value is only in one element of the vector.
4788 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4792 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4793 Ld.getOpcode() == ISD::ConstantFP);
4795 // Make sure that all of the users of a non-constant load are from the
4796 // BUILD_VECTOR node.
4797 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4802 case ISD::VECTOR_SHUFFLE: {
4803 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4805 // Shuffles must have a splat mask where the first element is
4807 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4810 SDValue Sc = Op.getOperand(0);
4811 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4812 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4814 if (!Subtarget->hasInt256())
4817 // Use the register form of the broadcast instruction available on AVX2.
4818 if (VT.getSizeInBits() >= 256)
4819 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4820 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4823 Ld = Sc.getOperand(0);
4824 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4825 Ld.getOpcode() == ISD::ConstantFP);
4827 // The scalar_to_vector node and the suspected
4828 // load node must have exactly one user.
4829 // Constants may have multiple users.
4831 // AVX-512 has register version of the broadcast
4832 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4833 Ld.getValueType().getSizeInBits() >= 32;
4834 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4841 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4842 bool IsGE256 = (VT.getSizeInBits() >= 256);
4844 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4845 // instruction to save 8 or more bytes of constant pool data.
4846 // TODO: If multiple splats are generated to load the same constant,
4847 // it may be detrimental to overall size. There needs to be a way to detect
4848 // that condition to know if this is truly a size win.
4849 const Function *F = DAG.getMachineFunction().getFunction();
4850 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4852 // Handle broadcasting a single constant scalar from the constant pool
4854 // On Sandybridge (no AVX2), it is still better to load a constant vector
4855 // from the constant pool and not to broadcast it from a scalar.
4856 // But override that restriction when optimizing for size.
4857 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4858 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4859 EVT CVT = Ld.getValueType();
4860 assert(!CVT.isVector() && "Must not broadcast a vector type");
4862 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4863 // For size optimization, also splat v2f64 and v2i64, and for size opt
4864 // with AVX2, also splat i8 and i16.
4865 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4866 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4867 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4868 const Constant *C = nullptr;
4869 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4870 C = CI->getConstantIntValue();
4871 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4872 C = CF->getConstantFPValue();
4874 assert(C && "Invalid constant type");
4876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4877 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4878 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4879 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4880 MachinePointerInfo::getConstantPool(),
4881 false, false, false, Alignment);
4883 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4887 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
4889 // Handle AVX2 in-register broadcasts.
4890 if (!IsLoad && Subtarget->hasInt256() &&
4891 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
4892 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4894 // The scalar source must be a normal load.
4898 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4899 (Subtarget->hasVLX() && ScalarSize == 64))
4900 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4902 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4903 // double since there is no vbroadcastsd xmm
4904 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
4905 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
4906 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4909 // Unsupported broadcast.
4913 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
4914 /// underlying vector and index.
4916 /// Modifies \p ExtractedFromVec to the real vector and returns the real
4918 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
4920 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
4921 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
4924 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
4926 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
4928 // (extract_vector_elt (vector_shuffle<2,u,u,u>
4929 // (extract_subvector (v8f32 %vreg0), Constant<4>),
4932 // In this case the vector is the extract_subvector expression and the index
4933 // is 2, as specified by the shuffle.
4934 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
4935 SDValue ShuffleVec = SVOp->getOperand(0);
4936 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
4937 assert(ShuffleVecVT.getVectorElementType() ==
4938 ExtractedFromVec.getSimpleValueType().getVectorElementType());
4940 int ShuffleIdx = SVOp->getMaskElt(Idx);
4941 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
4942 ExtractedFromVec = ShuffleVec;
4948 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
4949 MVT VT = Op.getSimpleValueType();
4951 // Skip if insert_vec_elt is not supported.
4952 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4953 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
4957 unsigned NumElems = Op.getNumOperands();
4961 SmallVector<unsigned, 4> InsertIndices;
4962 SmallVector<int, 8> Mask(NumElems, -1);
4964 for (unsigned i = 0; i != NumElems; ++i) {
4965 unsigned Opc = Op.getOperand(i).getOpcode();
4967 if (Opc == ISD::UNDEF)
4970 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
4971 // Quit if more than 1 elements need inserting.
4972 if (InsertIndices.size() > 1)
4975 InsertIndices.push_back(i);
4979 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
4980 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
4981 // Quit if non-constant index.
4982 if (!isa<ConstantSDNode>(ExtIdx))
4984 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
4986 // Quit if extracted from vector of different type.
4987 if (ExtractedFromVec.getValueType() != VT)
4990 if (!VecIn1.getNode())
4991 VecIn1 = ExtractedFromVec;
4992 else if (VecIn1 != ExtractedFromVec) {
4993 if (!VecIn2.getNode())
4994 VecIn2 = ExtractedFromVec;
4995 else if (VecIn2 != ExtractedFromVec)
4996 // Quit if more than 2 vectors to shuffle
5000 if (ExtractedFromVec == VecIn1)
5002 else if (ExtractedFromVec == VecIn2)
5003 Mask[i] = Idx + NumElems;
5006 if (!VecIn1.getNode())
5009 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5010 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5011 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5012 unsigned Idx = InsertIndices[i];
5013 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5014 DAG.getIntPtrConstant(Idx));
5020 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5022 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5024 MVT VT = Op.getSimpleValueType();
5025 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5026 "Unexpected type in LowerBUILD_VECTORvXi1!");
5029 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5030 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5031 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5032 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5035 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5036 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5037 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5038 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5041 bool AllContants = true;
5042 uint64_t Immediate = 0;
5043 int NonConstIdx = -1;
5044 bool IsSplat = true;
5045 unsigned NumNonConsts = 0;
5046 unsigned NumConsts = 0;
5047 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5048 SDValue In = Op.getOperand(idx);
5049 if (In.getOpcode() == ISD::UNDEF)
5051 if (!isa<ConstantSDNode>(In)) {
5052 AllContants = false;
5057 if (cast<ConstantSDNode>(In)->getZExtValue())
5058 Immediate |= (1ULL << idx);
5060 if (In != Op.getOperand(0))
5065 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5066 DAG.getConstant(Immediate, MVT::i16));
5067 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5068 DAG.getIntPtrConstant(0));
5071 if (NumNonConsts == 1 && NonConstIdx != 0) {
5074 SDValue VecAsImm = DAG.getConstant(Immediate,
5075 MVT::getIntegerVT(VT.getSizeInBits()));
5076 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5079 DstVec = DAG.getUNDEF(VT);
5080 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5081 Op.getOperand(NonConstIdx),
5082 DAG.getIntPtrConstant(NonConstIdx));
5084 if (!IsSplat && (NonConstIdx != 0))
5085 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5086 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5089 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5090 DAG.getConstant(-1, SelectVT),
5091 DAG.getConstant(0, SelectVT));
5093 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5094 DAG.getConstant((Immediate | 1), SelectVT),
5095 DAG.getConstant(Immediate, SelectVT));
5096 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5099 /// \brief Return true if \p N implements a horizontal binop and return the
5100 /// operands for the horizontal binop into V0 and V1.
5102 /// This is a helper function of PerformBUILD_VECTORCombine.
5103 /// This function checks that the build_vector \p N in input implements a
5104 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5105 /// operation to match.
5106 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5107 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5108 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5111 /// This function only analyzes elements of \p N whose indices are
5112 /// in range [BaseIdx, LastIdx).
5113 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5115 unsigned BaseIdx, unsigned LastIdx,
5116 SDValue &V0, SDValue &V1) {
5117 EVT VT = N->getValueType(0);
5119 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5120 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5121 "Invalid Vector in input!");
5123 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5124 bool CanFold = true;
5125 unsigned ExpectedVExtractIdx = BaseIdx;
5126 unsigned NumElts = LastIdx - BaseIdx;
5127 V0 = DAG.getUNDEF(VT);
5128 V1 = DAG.getUNDEF(VT);
5130 // Check if N implements a horizontal binop.
5131 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5132 SDValue Op = N->getOperand(i + BaseIdx);
5135 if (Op->getOpcode() == ISD::UNDEF) {
5136 // Update the expected vector extract index.
5137 if (i * 2 == NumElts)
5138 ExpectedVExtractIdx = BaseIdx;
5139 ExpectedVExtractIdx += 2;
5143 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5148 SDValue Op0 = Op.getOperand(0);
5149 SDValue Op1 = Op.getOperand(1);
5151 // Try to match the following pattern:
5152 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5153 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5154 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5155 Op0.getOperand(0) == Op1.getOperand(0) &&
5156 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5157 isa<ConstantSDNode>(Op1.getOperand(1)));
5161 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5162 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5164 if (i * 2 < NumElts) {
5165 if (V0.getOpcode() == ISD::UNDEF)
5166 V0 = Op0.getOperand(0);
5168 if (V1.getOpcode() == ISD::UNDEF)
5169 V1 = Op0.getOperand(0);
5170 if (i * 2 == NumElts)
5171 ExpectedVExtractIdx = BaseIdx;
5174 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5175 if (I0 == ExpectedVExtractIdx)
5176 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5177 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5178 // Try to match the following dag sequence:
5179 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5180 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5184 ExpectedVExtractIdx += 2;
5190 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5191 /// a concat_vector.
5193 /// This is a helper function of PerformBUILD_VECTORCombine.
5194 /// This function expects two 256-bit vectors called V0 and V1.
5195 /// At first, each vector is split into two separate 128-bit vectors.
5196 /// Then, the resulting 128-bit vectors are used to implement two
5197 /// horizontal binary operations.
5199 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5201 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5202 /// the two new horizontal binop.
5203 /// When Mode is set, the first horizontal binop dag node would take as input
5204 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5205 /// horizontal binop dag node would take as input the lower 128-bit of V1
5206 /// and the upper 128-bit of V1.
5208 /// HADD V0_LO, V0_HI
5209 /// HADD V1_LO, V1_HI
5211 /// Otherwise, the first horizontal binop dag node takes as input the lower
5212 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5213 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5215 /// HADD V0_LO, V1_LO
5216 /// HADD V0_HI, V1_HI
5218 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5219 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5220 /// the upper 128-bits of the result.
5221 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5222 SDLoc DL, SelectionDAG &DAG,
5223 unsigned X86Opcode, bool Mode,
5224 bool isUndefLO, bool isUndefHI) {
5225 EVT VT = V0.getValueType();
5226 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5227 "Invalid nodes in input!");
5229 unsigned NumElts = VT.getVectorNumElements();
5230 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5231 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5232 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5233 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5234 EVT NewVT = V0_LO.getValueType();
5236 SDValue LO = DAG.getUNDEF(NewVT);
5237 SDValue HI = DAG.getUNDEF(NewVT);
5240 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5241 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5242 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5243 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5244 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5246 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5247 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5248 V1_LO->getOpcode() != ISD::UNDEF))
5249 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5251 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5252 V1_HI->getOpcode() != ISD::UNDEF))
5253 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5256 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5259 /// \brief Try to fold a build_vector that performs an 'addsub' into the
5260 /// sequence of 'vadd + vsub + blendi'.
5261 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
5262 const X86Subtarget *Subtarget) {
5264 EVT VT = BV->getValueType(0);
5265 unsigned NumElts = VT.getVectorNumElements();
5266 SDValue InVec0 = DAG.getUNDEF(VT);
5267 SDValue InVec1 = DAG.getUNDEF(VT);
5269 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5270 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5272 // Odd-numbered elements in the input build vector are obtained from
5273 // adding two integer/float elements.
5274 // Even-numbered elements in the input build vector are obtained from
5275 // subtracting two integer/float elements.
5276 unsigned ExpectedOpcode = ISD::FSUB;
5277 unsigned NextExpectedOpcode = ISD::FADD;
5278 bool AddFound = false;
5279 bool SubFound = false;
5281 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5282 SDValue Op = BV->getOperand(i);
5284 // Skip 'undef' values.
5285 unsigned Opcode = Op.getOpcode();
5286 if (Opcode == ISD::UNDEF) {
5287 std::swap(ExpectedOpcode, NextExpectedOpcode);
5291 // Early exit if we found an unexpected opcode.
5292 if (Opcode != ExpectedOpcode)
5295 SDValue Op0 = Op.getOperand(0);
5296 SDValue Op1 = Op.getOperand(1);
5298 // Try to match the following pattern:
5299 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5300 // Early exit if we cannot match that sequence.
5301 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5302 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5303 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5304 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5305 Op0.getOperand(1) != Op1.getOperand(1))
5308 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5312 // We found a valid add/sub node. Update the information accordingly.
5318 // Update InVec0 and InVec1.
5319 if (InVec0.getOpcode() == ISD::UNDEF)
5320 InVec0 = Op0.getOperand(0);
5321 if (InVec1.getOpcode() == ISD::UNDEF)
5322 InVec1 = Op1.getOperand(0);
5324 // Make sure that operands in input to each add/sub node always
5325 // come from a same pair of vectors.
5326 if (InVec0 != Op0.getOperand(0)) {
5327 if (ExpectedOpcode == ISD::FSUB)
5330 // FADD is commutable. Try to commute the operands
5331 // and then test again.
5332 std::swap(Op0, Op1);
5333 if (InVec0 != Op0.getOperand(0))
5337 if (InVec1 != Op1.getOperand(0))
5340 // Update the pair of expected opcodes.
5341 std::swap(ExpectedOpcode, NextExpectedOpcode);
5344 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5345 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5346 InVec1.getOpcode() != ISD::UNDEF)
5347 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
5353 const X86Subtarget *Subtarget) {
5355 EVT VT = N->getValueType(0);
5356 unsigned NumElts = VT.getVectorNumElements();
5357 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
5358 SDValue InVec0, InVec1;
5360 // Try to match an ADDSUB.
5361 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
5362 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
5363 SDValue Value = matchAddSub(BV, DAG, Subtarget);
5364 if (Value.getNode())
5368 // Try to match horizontal ADD/SUB.
5369 unsigned NumUndefsLO = 0;
5370 unsigned NumUndefsHI = 0;
5371 unsigned Half = NumElts/2;
5373 // Count the number of UNDEF operands in the build_vector in input.
5374 for (unsigned i = 0, e = Half; i != e; ++i)
5375 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5378 for (unsigned i = Half, e = NumElts; i != e; ++i)
5379 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5382 // Early exit if this is either a build_vector of all UNDEFs or all the
5383 // operands but one are UNDEF.
5384 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5387 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5388 // Try to match an SSE3 float HADD/HSUB.
5389 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5390 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5392 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5393 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5394 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5395 // Try to match an SSSE3 integer HADD/HSUB.
5396 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5397 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5399 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5400 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5403 if (!Subtarget->hasAVX())
5406 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5407 // Try to match an AVX horizontal add/sub of packed single/double
5408 // precision floating point values from 256-bit vectors.
5409 SDValue InVec2, InVec3;
5410 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5411 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5412 ((InVec0.getOpcode() == ISD::UNDEF ||
5413 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5414 ((InVec1.getOpcode() == ISD::UNDEF ||
5415 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5416 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5418 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5419 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5420 ((InVec0.getOpcode() == ISD::UNDEF ||
5421 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5422 ((InVec1.getOpcode() == ISD::UNDEF ||
5423 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5424 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5425 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5426 // Try to match an AVX2 horizontal add/sub of signed integers.
5427 SDValue InVec2, InVec3;
5429 bool CanFold = true;
5431 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5432 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5433 ((InVec0.getOpcode() == ISD::UNDEF ||
5434 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5435 ((InVec1.getOpcode() == ISD::UNDEF ||
5436 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5437 X86Opcode = X86ISD::HADD;
5438 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5439 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5440 ((InVec0.getOpcode() == ISD::UNDEF ||
5441 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5442 ((InVec1.getOpcode() == ISD::UNDEF ||
5443 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5444 X86Opcode = X86ISD::HSUB;
5449 // Fold this build_vector into a single horizontal add/sub.
5450 // Do this only if the target has AVX2.
5451 if (Subtarget->hasAVX2())
5452 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5454 // Do not try to expand this build_vector into a pair of horizontal
5455 // add/sub if we can emit a pair of scalar add/sub.
5456 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5459 // Convert this build_vector into a pair of horizontal binop followed by
5461 bool isUndefLO = NumUndefsLO == Half;
5462 bool isUndefHI = NumUndefsHI == Half;
5463 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5464 isUndefLO, isUndefHI);
5468 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5469 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5471 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5472 X86Opcode = X86ISD::HADD;
5473 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5474 X86Opcode = X86ISD::HSUB;
5475 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5476 X86Opcode = X86ISD::FHADD;
5477 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5478 X86Opcode = X86ISD::FHSUB;
5482 // Don't try to expand this build_vector into a pair of horizontal add/sub
5483 // if we can simply emit a pair of scalar add/sub.
5484 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5487 // Convert this build_vector into two horizontal add/sub followed by
5489 bool isUndefLO = NumUndefsLO == Half;
5490 bool isUndefHI = NumUndefsHI == Half;
5491 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5492 isUndefLO, isUndefHI);
5499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5502 MVT VT = Op.getSimpleValueType();
5503 MVT ExtVT = VT.getVectorElementType();
5504 unsigned NumElems = Op.getNumOperands();
5506 // Generate vectors for predicate vectors.
5507 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5508 return LowerBUILD_VECTORvXi1(Op, DAG);
5510 // Vectors containing all zeros can be matched by pxor and xorps later
5511 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5512 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5513 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5514 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5517 return getZeroVector(VT, Subtarget, DAG, dl);
5520 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5521 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5522 // vpcmpeqd on 256-bit vectors.
5523 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5524 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5527 if (!VT.is512BitVector())
5528 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5531 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5532 if (Broadcast.getNode())
5535 unsigned EVTBits = ExtVT.getSizeInBits();
5537 unsigned NumZero = 0;
5538 unsigned NumNonZero = 0;
5539 unsigned NonZeros = 0;
5540 bool IsAllConstants = true;
5541 SmallSet<SDValue, 8> Values;
5542 for (unsigned i = 0; i < NumElems; ++i) {
5543 SDValue Elt = Op.getOperand(i);
5544 if (Elt.getOpcode() == ISD::UNDEF)
5547 if (Elt.getOpcode() != ISD::Constant &&
5548 Elt.getOpcode() != ISD::ConstantFP)
5549 IsAllConstants = false;
5550 if (X86::isZeroNode(Elt))
5553 NonZeros |= (1 << i);
5558 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5559 if (NumNonZero == 0)
5560 return DAG.getUNDEF(VT);
5562 // Special case for single non-zero, non-undef, element.
5563 if (NumNonZero == 1) {
5564 unsigned Idx = countTrailingZeros(NonZeros);
5565 SDValue Item = Op.getOperand(Idx);
5567 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5568 // the value are obviously zero, truncate the value to i32 and do the
5569 // insertion that way. Only do this if the value is non-constant or if the
5570 // value is a constant being inserted into element 0. It is cheaper to do
5571 // a constant pool load than it is to do a movd + shuffle.
5572 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5573 (!IsAllConstants || Idx == 0)) {
5574 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5576 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5577 EVT VecVT = MVT::v4i32;
5579 // Truncate the value (which may itself be a constant) to i32, and
5580 // convert it to a vector with movd (S2V+shuffle to zero extend).
5581 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5582 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5584 ISD::BITCAST, dl, VT,
5585 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5589 // If we have a constant or non-constant insertion into the low element of
5590 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5591 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5592 // depending on what the source datatype is.
5595 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5597 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5598 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5599 if (VT.is512BitVector()) {
5600 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5601 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5602 Item, DAG.getIntPtrConstant(0));
5604 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5605 "Expected an SSE value type!");
5606 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5607 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5608 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5611 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5612 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5613 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5614 if (VT.is256BitVector()) {
5615 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5616 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5618 assert(VT.is128BitVector() && "Expected an SSE value type!");
5619 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5621 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5625 // Is it a vector logical left shift?
5626 if (NumElems == 2 && Idx == 1 &&
5627 X86::isZeroNode(Op.getOperand(0)) &&
5628 !X86::isZeroNode(Op.getOperand(1))) {
5629 unsigned NumBits = VT.getSizeInBits();
5630 return getVShift(true, VT,
5631 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5632 VT, Op.getOperand(1)),
5633 NumBits/2, DAG, *this, dl);
5636 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5639 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5640 // is a non-constant being inserted into an element other than the low one,
5641 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5642 // movd/movss) to move this into the low element, then shuffle it into
5644 if (EVTBits == 32) {
5645 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5646 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5650 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5651 if (Values.size() == 1) {
5652 if (EVTBits == 32) {
5653 // Instead of a shuffle like this:
5654 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5655 // Check if it's possible to issue this instead.
5656 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5657 unsigned Idx = countTrailingZeros(NonZeros);
5658 SDValue Item = Op.getOperand(Idx);
5659 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5660 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5665 // A vector full of immediates; various special cases are already
5666 // handled, so this is best done with a single constant-pool load.
5670 // For AVX-length vectors, see if we can use a vector load to get all of the
5671 // elements, otherwise build the individual 128-bit pieces and use
5672 // shuffles to put them in place.
5673 if (VT.is256BitVector() || VT.is512BitVector()) {
5674 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5676 // Check for a build vector of consecutive loads.
5677 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5680 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5682 // Build both the lower and upper subvector.
5683 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5684 makeArrayRef(&V[0], NumElems/2));
5685 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5686 makeArrayRef(&V[NumElems / 2], NumElems/2));
5688 // Recreate the wider vector with the lower and upper part.
5689 if (VT.is256BitVector())
5690 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5691 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5694 // Let legalizer expand 2-wide build_vectors.
5695 if (EVTBits == 64) {
5696 if (NumNonZero == 1) {
5697 // One half is zero or undef.
5698 unsigned Idx = countTrailingZeros(NonZeros);
5699 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5700 Op.getOperand(Idx));
5701 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5706 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5707 if (EVTBits == 8 && NumElems == 16) {
5708 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5710 if (V.getNode()) return V;
5713 if (EVTBits == 16 && NumElems == 8) {
5714 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5716 if (V.getNode()) return V;
5719 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5720 if (EVTBits == 32 && NumElems == 4) {
5721 SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
5726 // If element VT is == 32 bits, turn it into a number of shuffles.
5727 SmallVector<SDValue, 8> V(NumElems);
5728 if (NumElems == 4 && NumZero > 0) {
5729 for (unsigned i = 0; i < 4; ++i) {
5730 bool isZero = !(NonZeros & (1 << i));
5732 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5734 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5737 for (unsigned i = 0; i < 2; ++i) {
5738 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5741 V[i] = V[i*2]; // Must be a zero vector.
5744 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5747 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5750 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5755 bool Reverse1 = (NonZeros & 0x3) == 2;
5756 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5760 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5761 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5763 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5766 if (Values.size() > 1 && VT.is128BitVector()) {
5767 // Check for a build vector of consecutive loads.
5768 for (unsigned i = 0; i < NumElems; ++i)
5769 V[i] = Op.getOperand(i);
5771 // Check for elements which are consecutive loads.
5772 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
5776 // Check for a build vector from mostly shuffle plus few inserting.
5777 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5781 // For SSE 4.1, use insertps to put the high elements into the low element.
5782 if (Subtarget->hasSSE41()) {
5784 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5785 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5787 Result = DAG.getUNDEF(VT);
5789 for (unsigned i = 1; i < NumElems; ++i) {
5790 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5791 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5792 Op.getOperand(i), DAG.getIntPtrConstant(i));
5797 // Otherwise, expand into a number of unpckl*, start by extending each of
5798 // our (non-undef) elements to the full vector width with the element in the
5799 // bottom slot of the vector (which generates no code for SSE).
5800 for (unsigned i = 0; i < NumElems; ++i) {
5801 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5802 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5804 V[i] = DAG.getUNDEF(VT);
5807 // Next, we iteratively mix elements, e.g. for v4f32:
5808 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5809 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5810 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5811 unsigned EltStride = NumElems >> 1;
5812 while (EltStride != 0) {
5813 for (unsigned i = 0; i < EltStride; ++i) {
5814 // If V[i+EltStride] is undef and this is the first round of mixing,
5815 // then it is safe to just drop this shuffle: V[i] is already in the
5816 // right place, the one element (since it's the first round) being
5817 // inserted as undef can be dropped. This isn't safe for successive
5818 // rounds because they will permute elements within both vectors.
5819 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5820 EltStride == NumElems/2)
5823 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5832 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5833 // to create 256-bit vectors from two other 128-bit ones.
5834 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5836 MVT ResVT = Op.getSimpleValueType();
5838 assert((ResVT.is256BitVector() ||
5839 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5841 SDValue V1 = Op.getOperand(0);
5842 SDValue V2 = Op.getOperand(1);
5843 unsigned NumElems = ResVT.getVectorNumElements();
5844 if(ResVT.is256BitVector())
5845 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5847 if (Op.getNumOperands() == 4) {
5848 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5849 ResVT.getVectorNumElements()/2);
5850 SDValue V3 = Op.getOperand(2);
5851 SDValue V4 = Op.getOperand(3);
5852 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5853 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5855 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5858 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5859 const X86Subtarget *Subtarget,
5860 SelectionDAG & DAG) {
5862 MVT ResVT = Op.getSimpleValueType();
5863 unsigned NumOfOperands = Op.getNumOperands();
5865 assert(isPowerOf2_32(NumOfOperands) &&
5866 "Unexpected number of operands in CONCAT_VECTORS");
5868 if (NumOfOperands > 2) {
5869 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5870 ResVT.getVectorNumElements()/2);
5871 SmallVector<SDValue, 2> Ops;
5872 for (unsigned i = 0; i < NumOfOperands/2; i++)
5873 Ops.push_back(Op.getOperand(i));
5874 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5876 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
5877 Ops.push_back(Op.getOperand(i));
5878 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
5879 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
5882 SDValue V1 = Op.getOperand(0);
5883 SDValue V2 = Op.getOperand(1);
5884 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
5885 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
5887 if (IsZeroV1 && IsZeroV2)
5888 return getZeroVector(ResVT, Subtarget, DAG, dl);
5890 SDValue ZeroIdx = DAG.getIntPtrConstant(0);
5891 SDValue Undef = DAG.getUNDEF(ResVT);
5892 unsigned NumElems = ResVT.getVectorNumElements();
5893 SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
5895 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
5896 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
5900 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
5901 // Zero the upper bits of V1
5902 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
5903 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
5906 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
5909 static SDValue LowerCONCAT_VECTORS(SDValue Op,
5910 const X86Subtarget *Subtarget,
5911 SelectionDAG &DAG) {
5912 MVT VT = Op.getSimpleValueType();
5913 if (VT.getVectorElementType() == MVT::i1)
5914 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
5916 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
5917 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
5918 Op.getNumOperands() == 4)));
5920 // AVX can use the vinsertf128 instruction to create 256-bit vectors
5921 // from two other 128-bit ones.
5923 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
5924 return LowerAVXCONCAT_VECTORS(Op, DAG);
5928 //===----------------------------------------------------------------------===//
5929 // Vector shuffle lowering
5931 // This is an experimental code path for lowering vector shuffles on x86. It is
5932 // designed to handle arbitrary vector shuffles and blends, gracefully
5933 // degrading performance as necessary. It works hard to recognize idiomatic
5934 // shuffles and lower them to optimal instruction patterns without leaving
5935 // a framework that allows reasonably efficient handling of all vector shuffle
5937 //===----------------------------------------------------------------------===//
5939 /// \brief Tiny helper function to identify a no-op mask.
5941 /// This is a somewhat boring predicate function. It checks whether the mask
5942 /// array input, which is assumed to be a single-input shuffle mask of the kind
5943 /// used by the X86 shuffle instructions (not a fully general
5944 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
5945 /// in-place shuffle are 'no-op's.
5946 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
5947 for (int i = 0, Size = Mask.size(); i < Size; ++i)
5948 if (Mask[i] != -1 && Mask[i] != i)
5953 /// \brief Helper function to classify a mask as a single-input mask.
5955 /// This isn't a generic single-input test because in the vector shuffle
5956 /// lowering we canonicalize single inputs to be the first input operand. This
5957 /// means we can more quickly test for a single input by only checking whether
5958 /// an input from the second operand exists. We also assume that the size of
5959 /// mask corresponds to the size of the input vectors which isn't true in the
5960 /// fully general case.
5961 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
5963 if (M >= (int)Mask.size())
5968 /// \brief Test whether there are elements crossing 128-bit lanes in this
5971 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
5972 /// and we routinely test for these.
5973 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
5974 int LaneSize = 128 / VT.getScalarSizeInBits();
5975 int Size = Mask.size();
5976 for (int i = 0; i < Size; ++i)
5977 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
5982 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
5984 /// This checks a shuffle mask to see if it is performing the same
5985 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
5986 /// that it is also not lane-crossing. It may however involve a blend from the
5987 /// same lane of a second vector.
5989 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
5990 /// non-trivial to compute in the face of undef lanes. The representation is
5991 /// *not* suitable for use with existing 128-bit shuffles as it will contain
5992 /// entries from both V1 and V2 inputs to the wider mask.
5994 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
5995 SmallVectorImpl<int> &RepeatedMask) {
5996 int LaneSize = 128 / VT.getScalarSizeInBits();
5997 RepeatedMask.resize(LaneSize, -1);
5998 int Size = Mask.size();
5999 for (int i = 0; i < Size; ++i) {
6002 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6003 // This entry crosses lanes, so there is no way to model this shuffle.
6006 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6007 if (RepeatedMask[i % LaneSize] == -1)
6008 // This is the first non-undef entry in this slot of a 128-bit lane.
6009 RepeatedMask[i % LaneSize] =
6010 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6011 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6012 // Found a mismatch with the repeated mask.
6018 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6021 /// This is a fast way to test a shuffle mask against a fixed pattern:
6023 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6025 /// It returns true if the mask is exactly as wide as the argument list, and
6026 /// each element of the mask is either -1 (signifying undef) or the value given
6027 /// in the argument.
6028 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6029 ArrayRef<int> ExpectedMask) {
6030 if (Mask.size() != ExpectedMask.size())
6033 int Size = Mask.size();
6035 // If the values are build vectors, we can look through them to find
6036 // equivalent inputs that make the shuffles equivalent.
6037 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6038 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6040 for (int i = 0; i < Size; ++i)
6041 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6042 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6043 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6044 if (!MaskBV || !ExpectedBV ||
6045 MaskBV->getOperand(Mask[i] % Size) !=
6046 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6053 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6055 /// This helper function produces an 8-bit shuffle immediate corresponding to
6056 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6057 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6060 /// NB: We rely heavily on "undef" masks preserving the input lane.
6061 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6062 SelectionDAG &DAG) {
6063 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6064 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6065 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6066 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6067 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6070 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6071 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6072 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6073 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6074 return DAG.getConstant(Imm, MVT::i8);
6077 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6079 /// This is used as a fallback approach when first class blend instructions are
6080 /// unavailable. Currently it is only suitable for integer vectors, but could
6081 /// be generalized for floating point vectors if desirable.
6082 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6083 SDValue V2, ArrayRef<int> Mask,
6084 SelectionDAG &DAG) {
6085 assert(VT.isInteger() && "Only supports integer vector types!");
6086 MVT EltVT = VT.getScalarType();
6087 int NumEltBits = EltVT.getSizeInBits();
6088 SDValue Zero = DAG.getConstant(0, EltVT);
6089 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6090 SmallVector<SDValue, 16> MaskOps;
6091 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6092 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6093 return SDValue(); // Shuffled input!
6094 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6097 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6098 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6099 // We have to cast V2 around.
6100 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6101 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6102 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6103 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6104 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6105 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6108 /// \brief Try to emit a blend instruction for a shuffle.
6110 /// This doesn't do any checks for the availability of instructions for blending
6111 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6112 /// be matched in the backend with the type given. What it does check for is
6113 /// that the shuffle mask is in fact a blend.
6114 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6115 SDValue V2, ArrayRef<int> Mask,
6116 const X86Subtarget *Subtarget,
6117 SelectionDAG &DAG) {
6118 unsigned BlendMask = 0;
6119 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6120 if (Mask[i] >= Size) {
6121 if (Mask[i] != i + Size)
6122 return SDValue(); // Shuffled V2 input!
6123 BlendMask |= 1u << i;
6126 if (Mask[i] >= 0 && Mask[i] != i)
6127 return SDValue(); // Shuffled V1 input!
6129 switch (VT.SimpleTy) {
6134 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6135 DAG.getConstant(BlendMask, MVT::i8));
6139 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6143 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6144 // that instruction.
6145 if (Subtarget->hasAVX2()) {
6146 // Scale the blend by the number of 32-bit dwords per element.
6147 int Scale = VT.getScalarSizeInBits() / 32;
6149 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6150 if (Mask[i] >= Size)
6151 for (int j = 0; j < Scale; ++j)
6152 BlendMask |= 1u << (i * Scale + j);
6154 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6155 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6156 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6157 return DAG.getNode(ISD::BITCAST, DL, VT,
6158 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6159 DAG.getConstant(BlendMask, MVT::i8)));
6163 // For integer shuffles we need to expand the mask and cast the inputs to
6164 // v8i16s prior to blending.
6165 int Scale = 8 / VT.getVectorNumElements();
6167 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6168 if (Mask[i] >= Size)
6169 for (int j = 0; j < Scale; ++j)
6170 BlendMask |= 1u << (i * Scale + j);
6172 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6173 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6174 return DAG.getNode(ISD::BITCAST, DL, VT,
6175 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6176 DAG.getConstant(BlendMask, MVT::i8)));
6180 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6181 SmallVector<int, 8> RepeatedMask;
6182 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6183 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6184 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6186 for (int i = 0; i < 8; ++i)
6187 if (RepeatedMask[i] >= 16)
6188 BlendMask |= 1u << i;
6189 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6190 DAG.getConstant(BlendMask, MVT::i8));
6196 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6197 "256-bit byte-blends require AVX2 support!");
6199 // Scale the blend by the number of bytes per element.
6200 int Scale = VT.getScalarSizeInBits() / 8;
6202 // This form of blend is always done on bytes. Compute the byte vector
6204 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6206 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6207 // mix of LLVM's code generator and the x86 backend. We tell the code
6208 // generator that boolean values in the elements of an x86 vector register
6209 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6210 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6211 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6212 // of the element (the remaining are ignored) and 0 in that high bit would
6213 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6214 // the LLVM model for boolean values in vector elements gets the relevant
6215 // bit set, it is set backwards and over constrained relative to x86's
6217 SmallVector<SDValue, 32> VSELECTMask;
6218 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6219 for (int j = 0; j < Scale; ++j)
6220 VSELECTMask.push_back(
6221 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6222 : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6224 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6225 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6227 ISD::BITCAST, DL, VT,
6228 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6229 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6234 llvm_unreachable("Not a supported integer vector type!");
6238 /// \brief Try to lower as a blend of elements from two inputs followed by
6239 /// a single-input permutation.
6241 /// This matches the pattern where we can blend elements from two inputs and
6242 /// then reduce the shuffle to a single-input permutation.
6243 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6246 SelectionDAG &DAG) {
6247 // We build up the blend mask while checking whether a blend is a viable way
6248 // to reduce the shuffle.
6249 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6250 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6252 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6256 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6258 if (BlendMask[Mask[i] % Size] == -1)
6259 BlendMask[Mask[i] % Size] = Mask[i];
6260 else if (BlendMask[Mask[i] % Size] != Mask[i])
6261 return SDValue(); // Can't blend in the needed input!
6263 PermuteMask[i] = Mask[i] % Size;
6266 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6267 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6270 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6271 /// blends and permutes.
6273 /// This matches the extremely common pattern for handling combined
6274 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6275 /// operations. It will try to pick the best arrangement of shuffles and
6277 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6281 SelectionDAG &DAG) {
6282 // Shuffle the input elements into the desired positions in V1 and V2 and
6283 // blend them together.
6284 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6285 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6286 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6287 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6288 if (Mask[i] >= 0 && Mask[i] < Size) {
6289 V1Mask[i] = Mask[i];
6291 } else if (Mask[i] >= Size) {
6292 V2Mask[i] = Mask[i] - Size;
6293 BlendMask[i] = i + Size;
6296 // Try to lower with the simpler initial blend strategy unless one of the
6297 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6298 // shuffle may be able to fold with a load or other benefit. However, when
6299 // we'll have to do 2x as many shuffles in order to achieve this, blending
6300 // first is a better strategy.
6301 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6302 if (SDValue BlendPerm =
6303 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6306 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6307 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6308 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6311 /// \brief Try to lower a vector shuffle as a byte rotation.
6313 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6314 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6315 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6316 /// try to generically lower a vector shuffle through such an pattern. It
6317 /// does not check for the profitability of lowering either as PALIGNR or
6318 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6319 /// This matches shuffle vectors that look like:
6321 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6323 /// Essentially it concatenates V1 and V2, shifts right by some number of
6324 /// elements, and takes the low elements as the result. Note that while this is
6325 /// specified as a *right shift* because x86 is little-endian, it is a *left
6326 /// rotate* of the vector lanes.
6327 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6330 const X86Subtarget *Subtarget,
6331 SelectionDAG &DAG) {
6332 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6334 int NumElts = Mask.size();
6335 int NumLanes = VT.getSizeInBits() / 128;
6336 int NumLaneElts = NumElts / NumLanes;
6338 // We need to detect various ways of spelling a rotation:
6339 // [11, 12, 13, 14, 15, 0, 1, 2]
6340 // [-1, 12, 13, 14, -1, -1, 1, -1]
6341 // [-1, -1, -1, -1, -1, -1, 1, 2]
6342 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6343 // [-1, 4, 5, 6, -1, -1, 9, -1]
6344 // [-1, 4, 5, 6, -1, -1, -1, -1]
6347 for (int l = 0; l < NumElts; l += NumLaneElts) {
6348 for (int i = 0; i < NumLaneElts; ++i) {
6349 if (Mask[l + i] == -1)
6351 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6353 // Get the mod-Size index and lane correct it.
6354 int LaneIdx = (Mask[l + i] % NumElts) - l;
6355 // Make sure it was in this lane.
6356 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6359 // Determine where a rotated vector would have started.
6360 int StartIdx = i - LaneIdx;
6362 // The identity rotation isn't interesting, stop.
6365 // If we found the tail of a vector the rotation must be the missing
6366 // front. If we found the head of a vector, it must be how much of the
6368 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6371 Rotation = CandidateRotation;
6372 else if (Rotation != CandidateRotation)
6373 // The rotations don't match, so we can't match this mask.
6376 // Compute which value this mask is pointing at.
6377 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6379 // Compute which of the two target values this index should be assigned
6380 // to. This reflects whether the high elements are remaining or the low
6381 // elements are remaining.
6382 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6384 // Either set up this value if we've not encountered it before, or check
6385 // that it remains consistent.
6388 else if (TargetV != MaskV)
6389 // This may be a rotation, but it pulls from the inputs in some
6390 // unsupported interleaving.
6395 // Check that we successfully analyzed the mask, and normalize the results.
6396 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6397 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6403 // The actual rotate instruction rotates bytes, so we need to scale the
6404 // rotation based on how many bytes are in the vector lane.
6405 int Scale = 16 / NumLaneElts;
6407 // SSSE3 targets can use the palignr instruction.
6408 if (Subtarget->hasSSSE3()) {
6409 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6410 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6411 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6412 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6414 return DAG.getNode(ISD::BITCAST, DL, VT,
6415 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6416 DAG.getConstant(Rotation * Scale, MVT::i8)));
6419 assert(VT.getSizeInBits() == 128 &&
6420 "Rotate-based lowering only supports 128-bit lowering!");
6421 assert(Mask.size() <= 16 &&
6422 "Can shuffle at most 16 bytes in a 128-bit vector!");
6424 // Default SSE2 implementation
6425 int LoByteShift = 16 - Rotation * Scale;
6426 int HiByteShift = Rotation * Scale;
6428 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6429 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6430 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6432 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6433 DAG.getConstant(LoByteShift, MVT::i8));
6434 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6435 DAG.getConstant(HiByteShift, MVT::i8));
6436 return DAG.getNode(ISD::BITCAST, DL, VT,
6437 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6440 /// \brief Compute whether each element of a shuffle is zeroable.
6442 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6443 /// Either it is an undef element in the shuffle mask, the element of the input
6444 /// referenced is undef, or the element of the input referenced is known to be
6445 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6446 /// as many lanes with this technique as possible to simplify the remaining
6448 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6449 SDValue V1, SDValue V2) {
6450 SmallBitVector Zeroable(Mask.size(), false);
6452 while (V1.getOpcode() == ISD::BITCAST)
6453 V1 = V1->getOperand(0);
6454 while (V2.getOpcode() == ISD::BITCAST)
6455 V2 = V2->getOperand(0);
6457 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6458 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6460 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6462 // Handle the easy cases.
6463 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6468 // If this is an index into a build_vector node (which has the same number
6469 // of elements), dig out the input value and use it.
6470 SDValue V = M < Size ? V1 : V2;
6471 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6474 SDValue Input = V.getOperand(M % Size);
6475 // The UNDEF opcode check really should be dead code here, but not quite
6476 // worth asserting on (it isn't invalid, just unexpected).
6477 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6484 /// \brief Try to emit a bitmask instruction for a shuffle.
6486 /// This handles cases where we can model a blend exactly as a bitmask due to
6487 /// one of the inputs being zeroable.
6488 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6489 SDValue V2, ArrayRef<int> Mask,
6490 SelectionDAG &DAG) {
6491 MVT EltVT = VT.getScalarType();
6492 int NumEltBits = EltVT.getSizeInBits();
6493 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6494 SDValue Zero = DAG.getConstant(0, IntEltVT);
6495 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6496 if (EltVT.isFloatingPoint()) {
6497 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6498 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6500 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6501 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6503 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6506 if (Mask[i] % Size != i)
6507 return SDValue(); // Not a blend.
6509 V = Mask[i] < Size ? V1 : V2;
6510 else if (V != (Mask[i] < Size ? V1 : V2))
6511 return SDValue(); // Can only let one input through the mask.
6513 VMaskOps[i] = AllOnes;
6516 return SDValue(); // No non-zeroable elements!
6518 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6519 V = DAG.getNode(VT.isFloatingPoint()
6520 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6525 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6527 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6528 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6529 /// matches elements from one of the input vectors shuffled to the left or
6530 /// right with zeroable elements 'shifted in'. It handles both the strictly
6531 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6534 /// PSHL : (little-endian) left bit shift.
6535 /// [ zz, 0, zz, 2 ]
6536 /// [ -1, 4, zz, -1 ]
6537 /// PSRL : (little-endian) right bit shift.
6539 /// [ -1, -1, 7, zz]
6540 /// PSLLDQ : (little-endian) left byte shift
6541 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6542 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6543 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6544 /// PSRLDQ : (little-endian) right byte shift
6545 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6546 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6547 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6548 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6549 SDValue V2, ArrayRef<int> Mask,
6550 SelectionDAG &DAG) {
6551 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6553 int Size = Mask.size();
6554 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6556 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6557 for (int i = 0; i < Size; i += Scale)
6558 for (int j = 0; j < Shift; ++j)
6559 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6565 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6566 for (int i = 0; i != Size; i += Scale) {
6567 unsigned Pos = Left ? i + Shift : i;
6568 unsigned Low = Left ? i : i + Shift;
6569 unsigned Len = Scale - Shift;
6570 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6571 Low + (V == V1 ? 0 : Size)))
6575 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6576 bool ByteShift = ShiftEltBits > 64;
6577 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6578 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6579 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6581 // Normalize the scale for byte shifts to still produce an i64 element
6583 Scale = ByteShift ? Scale / 2 : Scale;
6585 // We need to round trip through the appropriate type for the shift.
6586 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6587 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6588 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6589 "Illegal integer vector type");
6590 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6592 V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6593 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6596 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6597 // keep doubling the size of the integer elements up to that. We can
6598 // then shift the elements of the integer vector by whole multiples of
6599 // their width within the elements of the larger integer vector. Test each
6600 // multiple to see if we can find a match with the moved element indices
6601 // and that the shifted in elements are all zeroable.
6602 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6603 for (int Shift = 1; Shift != Scale; ++Shift)
6604 for (bool Left : {true, false})
6605 if (CheckZeros(Shift, Scale, Left))
6606 for (SDValue V : {V1, V2})
6607 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6614 /// \brief Lower a vector shuffle as a zero or any extension.
6616 /// Given a specific number of elements, element bit width, and extension
6617 /// stride, produce either a zero or any extension based on the available
6618 /// features of the subtarget.
6619 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6620 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6621 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6622 assert(Scale > 1 && "Need a scale to extend.");
6623 int NumElements = VT.getVectorNumElements();
6624 int EltBits = VT.getScalarSizeInBits();
6625 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6626 "Only 8, 16, and 32 bit elements can be extended.");
6627 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6629 // Found a valid zext mask! Try various lowering strategies based on the
6630 // input type and available ISA extensions.
6631 if (Subtarget->hasSSE41()) {
6632 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6633 NumElements / Scale);
6634 return DAG.getNode(ISD::BITCAST, DL, VT,
6635 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6638 // For any extends we can cheat for larger element sizes and use shuffle
6639 // instructions that can fold with a load and/or copy.
6640 if (AnyExt && EltBits == 32) {
6641 int PSHUFDMask[4] = {0, -1, 1, -1};
6643 ISD::BITCAST, DL, VT,
6644 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6645 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6646 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6648 if (AnyExt && EltBits == 16 && Scale > 2) {
6649 int PSHUFDMask[4] = {0, -1, 0, -1};
6650 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6651 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6652 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6653 int PSHUFHWMask[4] = {1, -1, -1, -1};
6655 ISD::BITCAST, DL, VT,
6656 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6657 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6658 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6661 // If this would require more than 2 unpack instructions to expand, use
6662 // pshufb when available. We can only use more than 2 unpack instructions
6663 // when zero extending i8 elements which also makes it easier to use pshufb.
6664 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6665 assert(NumElements == 16 && "Unexpected byte vector width!");
6666 SDValue PSHUFBMask[16];
6667 for (int i = 0; i < 16; ++i)
6669 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6670 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6671 return DAG.getNode(ISD::BITCAST, DL, VT,
6672 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6673 DAG.getNode(ISD::BUILD_VECTOR, DL,
6674 MVT::v16i8, PSHUFBMask)));
6677 // Otherwise emit a sequence of unpacks.
6679 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6680 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6681 : getZeroVector(InputVT, Subtarget, DAG, DL);
6682 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6683 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6687 } while (Scale > 1);
6688 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6691 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6693 /// This routine will try to do everything in its power to cleverly lower
6694 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6695 /// check for the profitability of this lowering, it tries to aggressively
6696 /// match this pattern. It will use all of the micro-architectural details it
6697 /// can to emit an efficient lowering. It handles both blends with all-zero
6698 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6699 /// masking out later).
6701 /// The reason we have dedicated lowering for zext-style shuffles is that they
6702 /// are both incredibly common and often quite performance sensitive.
6703 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6704 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6705 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6706 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6708 int Bits = VT.getSizeInBits();
6709 int NumElements = VT.getVectorNumElements();
6710 assert(VT.getScalarSizeInBits() <= 32 &&
6711 "Exceeds 32-bit integer zero extension limit");
6712 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6714 // Define a helper function to check a particular ext-scale and lower to it if
6716 auto Lower = [&](int Scale) -> SDValue {
6719 for (int i = 0; i < NumElements; ++i) {
6721 continue; // Valid anywhere but doesn't tell us anything.
6722 if (i % Scale != 0) {
6723 // Each of the extended elements need to be zeroable.
6727 // We no longer are in the anyext case.
6732 // Each of the base elements needs to be consecutive indices into the
6733 // same input vector.
6734 SDValue V = Mask[i] < NumElements ? V1 : V2;
6737 else if (InputV != V)
6738 return SDValue(); // Flip-flopping inputs.
6740 if (Mask[i] % NumElements != i / Scale)
6741 return SDValue(); // Non-consecutive strided elements.
6744 // If we fail to find an input, we have a zero-shuffle which should always
6745 // have already been handled.
6746 // FIXME: Maybe handle this here in case during blending we end up with one?
6750 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6751 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6754 // The widest scale possible for extending is to a 64-bit integer.
6755 assert(Bits % 64 == 0 &&
6756 "The number of bits in a vector must be divisible by 64 on x86!");
6757 int NumExtElements = Bits / 64;
6759 // Each iteration, try extending the elements half as much, but into twice as
6761 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6762 assert(NumElements % NumExtElements == 0 &&
6763 "The input vector size must be divisible by the extended size.");
6764 if (SDValue V = Lower(NumElements / NumExtElements))
6768 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6772 // Returns one of the source operands if the shuffle can be reduced to a
6773 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6774 auto CanZExtLowHalf = [&]() {
6775 for (int i = NumElements / 2; i != NumElements; ++i)
6778 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6780 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6785 if (SDValue V = CanZExtLowHalf()) {
6786 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6787 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6788 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6791 // No viable ext lowering found.
6795 /// \brief Try to get a scalar value for a specific element of a vector.
6797 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6798 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6799 SelectionDAG &DAG) {
6800 MVT VT = V.getSimpleValueType();
6801 MVT EltVT = VT.getVectorElementType();
6802 while (V.getOpcode() == ISD::BITCAST)
6803 V = V.getOperand(0);
6804 // If the bitcasts shift the element size, we can't extract an equivalent
6806 MVT NewVT = V.getSimpleValueType();
6807 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6810 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6811 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
6812 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
6817 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6819 /// This is particularly important because the set of instructions varies
6820 /// significantly based on whether the operand is a load or not.
6821 static bool isShuffleFoldableLoad(SDValue V) {
6822 while (V.getOpcode() == ISD::BITCAST)
6823 V = V.getOperand(0);
6825 return ISD::isNON_EXTLoad(V.getNode());
6828 /// \brief Try to lower insertion of a single element into a zero vector.
6830 /// This is a common pattern that we have especially efficient patterns to lower
6831 /// across all subtarget feature sets.
6832 static SDValue lowerVectorShuffleAsElementInsertion(
6833 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6834 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6835 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6837 MVT EltVT = VT.getVectorElementType();
6839 int V2Index = std::find_if(Mask.begin(), Mask.end(),
6840 [&Mask](int M) { return M >= (int)Mask.size(); }) -
6842 bool IsV1Zeroable = true;
6843 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6844 if (i != V2Index && !Zeroable[i]) {
6845 IsV1Zeroable = false;
6849 // Check for a single input from a SCALAR_TO_VECTOR node.
6850 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6851 // all the smarts here sunk into that routine. However, the current
6852 // lowering of BUILD_VECTOR makes that nearly impossible until the old
6853 // vector shuffle lowering is dead.
6854 if (SDValue V2S = getScalarValueForVectorElement(
6855 V2, Mask[V2Index] - Mask.size(), DAG)) {
6856 // We need to zext the scalar if it is smaller than an i32.
6857 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6858 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6859 // Using zext to expand a narrow element won't work for non-zero
6864 // Zero-extend directly to i32.
6866 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
6868 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
6869 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
6870 EltVT == MVT::i16) {
6871 // Either not inserting from the low element of the input or the input
6872 // element size is too small to use VZEXT_MOVL to clear the high bits.
6876 if (!IsV1Zeroable) {
6877 // If V1 can't be treated as a zero vector we have fewer options to lower
6878 // this. We can't support integer vectors or non-zero targets cheaply, and
6879 // the V1 elements can't be permuted in any way.
6880 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
6881 if (!VT.isFloatingPoint() || V2Index != 0)
6883 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
6884 V1Mask[V2Index] = -1;
6885 if (!isNoopShuffleMask(V1Mask))
6887 // This is essentially a special case blend operation, but if we have
6888 // general purpose blend operations, they are always faster. Bail and let
6889 // the rest of the lowering handle these as blends.
6890 if (Subtarget->hasSSE41())
6893 // Otherwise, use MOVSD or MOVSS.
6894 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
6895 "Only two types of floating point element types to handle!");
6896 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
6900 // This lowering only works for the low element with floating point vectors.
6901 if (VT.isFloatingPoint() && V2Index != 0)
6904 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
6906 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6909 // If we have 4 or fewer lanes we can cheaply shuffle the element into
6910 // the desired position. Otherwise it is more efficient to do a vector
6911 // shift left. We know that we can do a vector shift left because all
6912 // the inputs are zero.
6913 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
6914 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
6915 V2Shuffle[V2Index] = 0;
6916 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
6918 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
6920 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
6922 V2Index * EltVT.getSizeInBits()/8,
6923 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
6924 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
6930 /// \brief Try to lower broadcast of a single element.
6932 /// For convenience, this code also bundles all of the subtarget feature set
6933 /// filtering. While a little annoying to re-dispatch on type here, there isn't
6934 /// a convenient way to factor it out.
6935 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
6937 const X86Subtarget *Subtarget,
6938 SelectionDAG &DAG) {
6939 if (!Subtarget->hasAVX())
6941 if (VT.isInteger() && !Subtarget->hasAVX2())
6944 // Check that the mask is a broadcast.
6945 int BroadcastIdx = -1;
6947 if (M >= 0 && BroadcastIdx == -1)
6949 else if (M >= 0 && M != BroadcastIdx)
6952 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
6953 "a sorted mask where the broadcast "
6956 // Go up the chain of (vector) values to try and find a scalar load that
6957 // we can combine with the broadcast.
6959 switch (V.getOpcode()) {
6960 case ISD::CONCAT_VECTORS: {
6961 int OperandSize = Mask.size() / V.getNumOperands();
6962 V = V.getOperand(BroadcastIdx / OperandSize);
6963 BroadcastIdx %= OperandSize;
6967 case ISD::INSERT_SUBVECTOR: {
6968 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
6969 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
6973 int BeginIdx = (int)ConstantIdx->getZExtValue();
6975 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
6976 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
6977 BroadcastIdx -= BeginIdx;
6988 // Check if this is a broadcast of a scalar. We special case lowering
6989 // for scalars so that we can more effectively fold with loads.
6990 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6991 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
6992 V = V.getOperand(BroadcastIdx);
6994 // If the scalar isn't a load we can't broadcast from it in AVX1, only with
6996 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
6998 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
6999 // We can't broadcast from a vector register w/o AVX2, and we can only
7000 // broadcast from the zero-element of a vector register.
7004 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7007 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7008 // INSERTPS when the V1 elements are already in the correct locations
7009 // because otherwise we can just always use two SHUFPS instructions which
7010 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7011 // perform INSERTPS if a single V1 element is out of place and all V2
7012 // elements are zeroable.
7013 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7015 SelectionDAG &DAG) {
7016 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7017 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7018 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7019 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7021 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7024 int V1DstIndex = -1;
7025 int V2DstIndex = -1;
7026 bool V1UsedInPlace = false;
7028 for (int i = 0; i < 4; ++i) {
7029 // Synthesize a zero mask from the zeroable elements (includes undefs).
7035 // Flag if we use any V1 inputs in place.
7037 V1UsedInPlace = true;
7041 // We can only insert a single non-zeroable element.
7042 if (V1DstIndex != -1 || V2DstIndex != -1)
7046 // V1 input out of place for insertion.
7049 // V2 input for insertion.
7054 // Don't bother if we have no (non-zeroable) element for insertion.
7055 if (V1DstIndex == -1 && V2DstIndex == -1)
7058 // Determine element insertion src/dst indices. The src index is from the
7059 // start of the inserted vector, not the start of the concatenated vector.
7060 unsigned V2SrcIndex = 0;
7061 if (V1DstIndex != -1) {
7062 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7063 // and don't use the original V2 at all.
7064 V2SrcIndex = Mask[V1DstIndex];
7065 V2DstIndex = V1DstIndex;
7068 V2SrcIndex = Mask[V2DstIndex] - 4;
7071 // If no V1 inputs are used in place, then the result is created only from
7072 // the zero mask and the V2 insertion - so remove V1 dependency.
7074 V1 = DAG.getUNDEF(MVT::v4f32);
7076 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7077 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7079 // Insert the V2 element into the desired position.
7081 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7082 DAG.getConstant(InsertPSMask, MVT::i8));
7085 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7086 /// UNPCK instruction.
7088 /// This specifically targets cases where we end up with alternating between
7089 /// the two inputs, and so can permute them into something that feeds a single
7090 /// UNPCK instruction. Note that this routine only targets integer vectors
7091 /// because for floating point vectors we have a generalized SHUFPS lowering
7092 /// strategy that handles everything that doesn't *exactly* match an unpack,
7093 /// making this clever lowering unnecessary.
7094 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7095 SDValue V2, ArrayRef<int> Mask,
7096 SelectionDAG &DAG) {
7097 assert(!VT.isFloatingPoint() &&
7098 "This routine only supports integer vectors.");
7099 assert(!isSingleInputShuffleMask(Mask) &&
7100 "This routine should only be used when blending two inputs.");
7101 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7103 int Size = Mask.size();
7105 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7106 return M >= 0 && M % Size < Size / 2;
7108 int NumHiInputs = std::count_if(
7109 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7111 bool UnpackLo = NumLoInputs >= NumHiInputs;
7113 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7114 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7115 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7117 for (int i = 0; i < Size; ++i) {
7121 // Each element of the unpack contains Scale elements from this mask.
7122 int UnpackIdx = i / Scale;
7124 // We only handle the case where V1 feeds the first slots of the unpack.
7125 // We rely on canonicalization to ensure this is the case.
7126 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7129 // Setup the mask for this input. The indexing is tricky as we have to
7130 // handle the unpack stride.
7131 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7132 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7136 // If we will have to shuffle both inputs to use the unpack, check whether
7137 // we can just unpack first and shuffle the result. If so, skip this unpack.
7138 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7139 !isNoopShuffleMask(V2Mask))
7142 // Shuffle the inputs into place.
7143 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7144 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7146 // Cast the inputs to the type we will use to unpack them.
7147 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7148 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7150 // Unpack the inputs and cast the result back to the desired type.
7151 return DAG.getNode(ISD::BITCAST, DL, VT,
7152 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7153 DL, UnpackVT, V1, V2));
7156 // We try each unpack from the largest to the smallest to try and find one
7157 // that fits this mask.
7158 int OrigNumElements = VT.getVectorNumElements();
7159 int OrigScalarSize = VT.getScalarSizeInBits();
7160 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7161 int Scale = ScalarSize / OrigScalarSize;
7162 int NumElements = OrigNumElements / Scale;
7163 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7164 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7168 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7170 if (NumLoInputs == 0 || NumHiInputs == 0) {
7171 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7172 "We have to have *some* inputs!");
7173 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7175 // FIXME: We could consider the total complexity of the permute of each
7176 // possible unpacking. Or at the least we should consider how many
7177 // half-crossings are created.
7178 // FIXME: We could consider commuting the unpacks.
7180 SmallVector<int, 32> PermMask;
7181 PermMask.assign(Size, -1);
7182 for (int i = 0; i < Size; ++i) {
7186 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7189 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7191 return DAG.getVectorShuffle(
7192 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7194 DAG.getUNDEF(VT), PermMask);
7200 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7202 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7203 /// support for floating point shuffles but not integer shuffles. These
7204 /// instructions will incur a domain crossing penalty on some chips though so
7205 /// it is better to avoid lowering through this for integer vectors where
7207 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7208 const X86Subtarget *Subtarget,
7209 SelectionDAG &DAG) {
7211 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7212 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7213 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7215 ArrayRef<int> Mask = SVOp->getMask();
7216 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7218 if (isSingleInputShuffleMask(Mask)) {
7219 // Use low duplicate instructions for masks that match their pattern.
7220 if (Subtarget->hasSSE3())
7221 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7222 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7224 // Straight shuffle of a single input vector. Simulate this by using the
7225 // single input as both of the "inputs" to this instruction..
7226 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7228 if (Subtarget->hasAVX()) {
7229 // If we have AVX, we can use VPERMILPS which will allow folding a load
7230 // into the shuffle.
7231 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7232 DAG.getConstant(SHUFPDMask, MVT::i8));
7235 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7236 DAG.getConstant(SHUFPDMask, MVT::i8));
7238 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7239 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7241 // If we have a single input, insert that into V1 if we can do so cheaply.
7242 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7243 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7244 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7246 // Try inverting the insertion since for v2 masks it is easy to do and we
7247 // can't reliably sort the mask one way or the other.
7248 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7249 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7250 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7251 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7255 // Try to use one of the special instruction patterns to handle two common
7256 // blend patterns if a zero-blend above didn't work.
7257 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7258 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7259 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7260 // We can either use a special instruction to load over the low double or
7261 // to move just the low double.
7263 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7265 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7267 if (Subtarget->hasSSE41())
7268 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7272 // Use dedicated unpack instructions for masks that match their pattern.
7273 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7274 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7275 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7276 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7278 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7279 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7280 DAG.getConstant(SHUFPDMask, MVT::i8));
7283 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7285 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7286 /// the integer unit to minimize domain crossing penalties. However, for blends
7287 /// it falls back to the floating point shuffle operation with appropriate bit
7289 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7290 const X86Subtarget *Subtarget,
7291 SelectionDAG &DAG) {
7293 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7294 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7295 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7296 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7297 ArrayRef<int> Mask = SVOp->getMask();
7298 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7300 if (isSingleInputShuffleMask(Mask)) {
7301 // Check for being able to broadcast a single element.
7302 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7303 Mask, Subtarget, DAG))
7306 // Straight shuffle of a single input vector. For everything from SSE2
7307 // onward this has a single fast instruction with no scary immediates.
7308 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7309 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7310 int WidenedMask[4] = {
7311 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7312 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7314 ISD::BITCAST, DL, MVT::v2i64,
7315 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7316 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7318 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7319 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7320 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7321 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7323 // If we have a blend of two PACKUS operations an the blend aligns with the
7324 // low and half halves, we can just merge the PACKUS operations. This is
7325 // particularly important as it lets us merge shuffles that this routine itself
7327 auto GetPackNode = [](SDValue V) {
7328 while (V.getOpcode() == ISD::BITCAST)
7329 V = V.getOperand(0);
7331 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7333 if (SDValue V1Pack = GetPackNode(V1))
7334 if (SDValue V2Pack = GetPackNode(V2))
7335 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7336 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7337 Mask[0] == 0 ? V1Pack.getOperand(0)
7338 : V1Pack.getOperand(1),
7339 Mask[1] == 2 ? V2Pack.getOperand(0)
7340 : V2Pack.getOperand(1)));
7342 // Try to use shift instructions.
7344 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7347 // When loading a scalar and then shuffling it into a vector we can often do
7348 // the insertion cheaply.
7349 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7350 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7352 // Try inverting the insertion since for v2 masks it is easy to do and we
7353 // can't reliably sort the mask one way or the other.
7354 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7355 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7356 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7359 // We have different paths for blend lowering, but they all must use the
7360 // *exact* same predicate.
7361 bool IsBlendSupported = Subtarget->hasSSE41();
7362 if (IsBlendSupported)
7363 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7367 // Use dedicated unpack instructions for masks that match their pattern.
7368 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7369 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7370 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7371 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7373 // Try to use byte rotation instructions.
7374 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7375 if (Subtarget->hasSSSE3())
7376 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7377 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7380 // If we have direct support for blends, we should lower by decomposing into
7381 // a permute. That will be faster than the domain cross.
7382 if (IsBlendSupported)
7383 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7386 // We implement this with SHUFPD which is pretty lame because it will likely
7387 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7388 // However, all the alternatives are still more cycles and newer chips don't
7389 // have this problem. It would be really nice if x86 had better shuffles here.
7390 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7391 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7392 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7393 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7396 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7398 /// This is used to disable more specialized lowerings when the shufps lowering
7399 /// will happen to be efficient.
7400 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7401 // This routine only handles 128-bit shufps.
7402 assert(Mask.size() == 4 && "Unsupported mask size!");
7404 // To lower with a single SHUFPS we need to have the low half and high half
7405 // each requiring a single input.
7406 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7408 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7414 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7416 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7417 /// It makes no assumptions about whether this is the *best* lowering, it simply
7419 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7420 ArrayRef<int> Mask, SDValue V1,
7421 SDValue V2, SelectionDAG &DAG) {
7422 SDValue LowV = V1, HighV = V2;
7423 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7426 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7428 if (NumV2Elements == 1) {
7430 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7433 // Compute the index adjacent to V2Index and in the same half by toggling
7435 int V2AdjIndex = V2Index ^ 1;
7437 if (Mask[V2AdjIndex] == -1) {
7438 // Handles all the cases where we have a single V2 element and an undef.
7439 // This will only ever happen in the high lanes because we commute the
7440 // vector otherwise.
7442 std::swap(LowV, HighV);
7443 NewMask[V2Index] -= 4;
7445 // Handle the case where the V2 element ends up adjacent to a V1 element.
7446 // To make this work, blend them together as the first step.
7447 int V1Index = V2AdjIndex;
7448 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7449 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7450 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7452 // Now proceed to reconstruct the final blend as we have the necessary
7453 // high or low half formed.
7460 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7461 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7463 } else if (NumV2Elements == 2) {
7464 if (Mask[0] < 4 && Mask[1] < 4) {
7465 // Handle the easy case where we have V1 in the low lanes and V2 in the
7469 } else if (Mask[2] < 4 && Mask[3] < 4) {
7470 // We also handle the reversed case because this utility may get called
7471 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7472 // arrange things in the right direction.
7478 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7479 // trying to place elements directly, just blend them and set up the final
7480 // shuffle to place them.
7482 // The first two blend mask elements are for V1, the second two are for
7484 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7485 Mask[2] < 4 ? Mask[2] : Mask[3],
7486 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7487 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7488 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7489 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7491 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7494 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7495 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7496 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7497 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7500 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7501 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7504 /// \brief Lower 4-lane 32-bit floating point shuffles.
7506 /// Uses instructions exclusively from the floating point unit to minimize
7507 /// domain crossing penalties, as these are sufficient to implement all v4f32
7509 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7510 const X86Subtarget *Subtarget,
7511 SelectionDAG &DAG) {
7513 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7514 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7515 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7516 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7517 ArrayRef<int> Mask = SVOp->getMask();
7518 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7521 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7523 if (NumV2Elements == 0) {
7524 // Check for being able to broadcast a single element.
7525 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7526 Mask, Subtarget, DAG))
7529 // Use even/odd duplicate instructions for masks that match their pattern.
7530 if (Subtarget->hasSSE3()) {
7531 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7532 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7533 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7534 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7537 if (Subtarget->hasAVX()) {
7538 // If we have AVX, we can use VPERMILPS which will allow folding a load
7539 // into the shuffle.
7540 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7541 getV4X86ShuffleImm8ForMask(Mask, DAG));
7544 // Otherwise, use a straight shuffle of a single input vector. We pass the
7545 // input vector to both operands to simulate this with a SHUFPS.
7546 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7547 getV4X86ShuffleImm8ForMask(Mask, DAG));
7550 // There are special ways we can lower some single-element blends. However, we
7551 // have custom ways we can lower more complex single-element blends below that
7552 // we defer to if both this and BLENDPS fail to match, so restrict this to
7553 // when the V2 input is targeting element 0 of the mask -- that is the fast
7555 if (NumV2Elements == 1 && Mask[0] >= 4)
7556 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7557 Mask, Subtarget, DAG))
7560 if (Subtarget->hasSSE41()) {
7561 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7565 // Use INSERTPS if we can complete the shuffle efficiently.
7566 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7569 if (!isSingleSHUFPSMask(Mask))
7570 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7571 DL, MVT::v4f32, V1, V2, Mask, DAG))
7575 // Use dedicated unpack instructions for masks that match their pattern.
7576 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7577 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7578 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7579 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7580 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7581 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7582 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7583 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7585 // Otherwise fall back to a SHUFPS lowering strategy.
7586 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7589 /// \brief Lower 4-lane i32 vector shuffles.
7591 /// We try to handle these with integer-domain shuffles where we can, but for
7592 /// blends we use the floating point domain blend instructions.
7593 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7594 const X86Subtarget *Subtarget,
7595 SelectionDAG &DAG) {
7597 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7598 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7599 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7600 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7601 ArrayRef<int> Mask = SVOp->getMask();
7602 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7604 // Whenever we can lower this as a zext, that instruction is strictly faster
7605 // than any alternative. It also allows us to fold memory operands into the
7606 // shuffle in many cases.
7607 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7608 Mask, Subtarget, DAG))
7612 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7614 if (NumV2Elements == 0) {
7615 // Check for being able to broadcast a single element.
7616 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7617 Mask, Subtarget, DAG))
7620 // Straight shuffle of a single input vector. For everything from SSE2
7621 // onward this has a single fast instruction with no scary immediates.
7622 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7623 // but we aren't actually going to use the UNPCK instruction because doing
7624 // so prevents folding a load into this instruction or making a copy.
7625 const int UnpackLoMask[] = {0, 0, 1, 1};
7626 const int UnpackHiMask[] = {2, 2, 3, 3};
7627 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7628 Mask = UnpackLoMask;
7629 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7630 Mask = UnpackHiMask;
7632 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7633 getV4X86ShuffleImm8ForMask(Mask, DAG));
7636 // Try to use shift instructions.
7638 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7641 // There are special ways we can lower some single-element blends.
7642 if (NumV2Elements == 1)
7643 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7644 Mask, Subtarget, DAG))
7647 // We have different paths for blend lowering, but they all must use the
7648 // *exact* same predicate.
7649 bool IsBlendSupported = Subtarget->hasSSE41();
7650 if (IsBlendSupported)
7651 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7655 if (SDValue Masked =
7656 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7659 // Use dedicated unpack instructions for masks that match their pattern.
7660 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7661 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7662 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7663 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7664 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7665 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7666 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7667 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7669 // Try to use byte rotation instructions.
7670 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7671 if (Subtarget->hasSSSE3())
7672 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7673 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7676 // If we have direct support for blends, we should lower by decomposing into
7677 // a permute. That will be faster than the domain cross.
7678 if (IsBlendSupported)
7679 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7682 // Try to lower by permuting the inputs into an unpack instruction.
7683 if (SDValue Unpack =
7684 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7687 // We implement this with SHUFPS because it can blend from two vectors.
7688 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7689 // up the inputs, bypassing domain shift penalties that we would encur if we
7690 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7692 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7693 DAG.getVectorShuffle(
7695 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7696 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7699 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7700 /// shuffle lowering, and the most complex part.
7702 /// The lowering strategy is to try to form pairs of input lanes which are
7703 /// targeted at the same half of the final vector, and then use a dword shuffle
7704 /// to place them onto the right half, and finally unpack the paired lanes into
7705 /// their final position.
7707 /// The exact breakdown of how to form these dword pairs and align them on the
7708 /// correct sides is really tricky. See the comments within the function for
7709 /// more of the details.
7711 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7712 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7713 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7714 /// vector, form the analogous 128-bit 8-element Mask.
7715 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7716 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7717 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7718 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7719 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7721 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7722 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7723 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7725 SmallVector<int, 4> LoInputs;
7726 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7727 [](int M) { return M >= 0; });
7728 std::sort(LoInputs.begin(), LoInputs.end());
7729 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7730 SmallVector<int, 4> HiInputs;
7731 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7732 [](int M) { return M >= 0; });
7733 std::sort(HiInputs.begin(), HiInputs.end());
7734 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7736 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7737 int NumHToL = LoInputs.size() - NumLToL;
7739 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7740 int NumHToH = HiInputs.size() - NumLToH;
7741 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7742 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7743 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7744 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7746 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7747 // such inputs we can swap two of the dwords across the half mark and end up
7748 // with <=2 inputs to each half in each half. Once there, we can fall through
7749 // to the generic code below. For example:
7751 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7752 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7754 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7755 // and an existing 2-into-2 on the other half. In this case we may have to
7756 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7757 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7758 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7759 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7760 // half than the one we target for fixing) will be fixed when we re-enter this
7761 // path. We will also combine away any sequence of PSHUFD instructions that
7762 // result into a single instruction. Here is an example of the tricky case:
7764 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7765 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7767 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7769 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7770 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7772 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7773 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7775 // The result is fine to be handled by the generic logic.
7776 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7777 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7778 int AOffset, int BOffset) {
7779 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7780 "Must call this with A having 3 or 1 inputs from the A half.");
7781 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7782 "Must call this with B having 1 or 3 inputs from the B half.");
7783 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7784 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7786 // Compute the index of dword with only one word among the three inputs in
7787 // a half by taking the sum of the half with three inputs and subtracting
7788 // the sum of the actual three inputs. The difference is the remaining
7791 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7792 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7793 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7794 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7795 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7796 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7797 int TripleNonInputIdx =
7798 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7799 TripleDWord = TripleNonInputIdx / 2;
7801 // We use xor with one to compute the adjacent DWord to whichever one the
7803 OneInputDWord = (OneInput / 2) ^ 1;
7805 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7806 // and BToA inputs. If there is also such a problem with the BToB and AToB
7807 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7808 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7809 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7810 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7811 // Compute how many inputs will be flipped by swapping these DWords. We
7813 // to balance this to ensure we don't form a 3-1 shuffle in the other
7815 int NumFlippedAToBInputs =
7816 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7817 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7818 int NumFlippedBToBInputs =
7819 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7820 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7821 if ((NumFlippedAToBInputs == 1 &&
7822 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7823 (NumFlippedBToBInputs == 1 &&
7824 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7825 // We choose whether to fix the A half or B half based on whether that
7826 // half has zero flipped inputs. At zero, we may not be able to fix it
7827 // with that half. We also bias towards fixing the B half because that
7828 // will more commonly be the high half, and we have to bias one way.
7829 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7830 ArrayRef<int> Inputs) {
7831 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7832 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7833 PinnedIdx ^ 1) != Inputs.end();
7834 // Determine whether the free index is in the flipped dword or the
7835 // unflipped dword based on where the pinned index is. We use this bit
7836 // in an xor to conditionally select the adjacent dword.
7837 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7838 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7839 FixFreeIdx) != Inputs.end();
7840 if (IsFixIdxInput == IsFixFreeIdxInput)
7842 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7843 FixFreeIdx) != Inputs.end();
7844 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7845 "We need to be changing the number of flipped inputs!");
7846 int PSHUFHalfMask[] = {0, 1, 2, 3};
7847 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7848 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7850 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7853 if (M != -1 && M == FixIdx)
7855 else if (M != -1 && M == FixFreeIdx)
7858 if (NumFlippedBToBInputs != 0) {
7860 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7861 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7863 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7865 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7866 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7871 int PSHUFDMask[] = {0, 1, 2, 3};
7872 PSHUFDMask[ADWord] = BDWord;
7873 PSHUFDMask[BDWord] = ADWord;
7874 V = DAG.getNode(ISD::BITCAST, DL, VT,
7875 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
7876 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
7877 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7879 // Adjust the mask to match the new locations of A and B.
7881 if (M != -1 && M/2 == ADWord)
7882 M = 2 * BDWord + M % 2;
7883 else if (M != -1 && M/2 == BDWord)
7884 M = 2 * ADWord + M % 2;
7886 // Recurse back into this routine to re-compute state now that this isn't
7887 // a 3 and 1 problem.
7888 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
7891 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7892 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7893 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7894 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7896 // At this point there are at most two inputs to the low and high halves from
7897 // each half. That means the inputs can always be grouped into dwords and
7898 // those dwords can then be moved to the correct half with a dword shuffle.
7899 // We use at most one low and one high word shuffle to collect these paired
7900 // inputs into dwords, and finally a dword shuffle to place them.
7901 int PSHUFLMask[4] = {-1, -1, -1, -1};
7902 int PSHUFHMask[4] = {-1, -1, -1, -1};
7903 int PSHUFDMask[4] = {-1, -1, -1, -1};
7905 // First fix the masks for all the inputs that are staying in their
7906 // original halves. This will then dictate the targets of the cross-half
7908 auto fixInPlaceInputs =
7909 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7910 MutableArrayRef<int> SourceHalfMask,
7911 MutableArrayRef<int> HalfMask, int HalfOffset) {
7912 if (InPlaceInputs.empty())
7914 if (InPlaceInputs.size() == 1) {
7915 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7916 InPlaceInputs[0] - HalfOffset;
7917 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7920 if (IncomingInputs.empty()) {
7921 // Just fix all of the in place inputs.
7922 for (int Input : InPlaceInputs) {
7923 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7924 PSHUFDMask[Input / 2] = Input / 2;
7929 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7930 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7931 InPlaceInputs[0] - HalfOffset;
7932 // Put the second input next to the first so that they are packed into
7933 // a dword. We find the adjacent index by toggling the low bit.
7934 int AdjIndex = InPlaceInputs[0] ^ 1;
7935 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7936 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7937 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7939 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7940 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7942 // Now gather the cross-half inputs and place them into a free dword of
7943 // their target half.
7944 // FIXME: This operation could almost certainly be simplified dramatically to
7945 // look more like the 3-1 fixing operation.
7946 auto moveInputsToRightHalf = [&PSHUFDMask](
7947 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7948 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7949 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7951 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7952 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7954 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7956 int LowWord = Word & ~1;
7957 int HighWord = Word | 1;
7958 return isWordClobbered(SourceHalfMask, LowWord) ||
7959 isWordClobbered(SourceHalfMask, HighWord);
7962 if (IncomingInputs.empty())
7965 if (ExistingInputs.empty()) {
7966 // Map any dwords with inputs from them into the right half.
7967 for (int Input : IncomingInputs) {
7968 // If the source half mask maps over the inputs, turn those into
7969 // swaps and use the swapped lane.
7970 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7971 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7972 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7973 Input - SourceOffset;
7974 // We have to swap the uses in our half mask in one sweep.
7975 for (int &M : HalfMask)
7976 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7978 else if (M == Input)
7979 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7981 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7982 Input - SourceOffset &&
7983 "Previous placement doesn't match!");
7985 // Note that this correctly re-maps both when we do a swap and when
7986 // we observe the other side of the swap above. We rely on that to
7987 // avoid swapping the members of the input list directly.
7988 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7991 // Map the input's dword into the correct half.
7992 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7993 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7995 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7997 "Previous placement doesn't match!");
8000 // And just directly shift any other-half mask elements to be same-half
8001 // as we will have mirrored the dword containing the element into the
8002 // same position within that half.
8003 for (int &M : HalfMask)
8004 if (M >= SourceOffset && M < SourceOffset + 4) {
8005 M = M - SourceOffset + DestOffset;
8006 assert(M >= 0 && "This should never wrap below zero!");
8011 // Ensure we have the input in a viable dword of its current half. This
8012 // is particularly tricky because the original position may be clobbered
8013 // by inputs being moved and *staying* in that half.
8014 if (IncomingInputs.size() == 1) {
8015 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8016 int InputFixed = std::find(std::begin(SourceHalfMask),
8017 std::end(SourceHalfMask), -1) -
8018 std::begin(SourceHalfMask) + SourceOffset;
8019 SourceHalfMask[InputFixed - SourceOffset] =
8020 IncomingInputs[0] - SourceOffset;
8021 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8023 IncomingInputs[0] = InputFixed;
8025 } else if (IncomingInputs.size() == 2) {
8026 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8027 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8028 // We have two non-adjacent or clobbered inputs we need to extract from
8029 // the source half. To do this, we need to map them into some adjacent
8030 // dword slot in the source mask.
8031 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8032 IncomingInputs[1] - SourceOffset};
8034 // If there is a free slot in the source half mask adjacent to one of
8035 // the inputs, place the other input in it. We use (Index XOR 1) to
8036 // compute an adjacent index.
8037 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8038 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8039 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8040 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8041 InputsFixed[1] = InputsFixed[0] ^ 1;
8042 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8043 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8044 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8045 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8046 InputsFixed[0] = InputsFixed[1] ^ 1;
8047 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8048 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8049 // The two inputs are in the same DWord but it is clobbered and the
8050 // adjacent DWord isn't used at all. Move both inputs to the free
8052 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8053 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8054 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8055 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8057 // The only way we hit this point is if there is no clobbering
8058 // (because there are no off-half inputs to this half) and there is no
8059 // free slot adjacent to one of the inputs. In this case, we have to
8060 // swap an input with a non-input.
8061 for (int i = 0; i < 4; ++i)
8062 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8063 "We can't handle any clobbers here!");
8064 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8065 "Cannot have adjacent inputs here!");
8067 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8068 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8070 // We also have to update the final source mask in this case because
8071 // it may need to undo the above swap.
8072 for (int &M : FinalSourceHalfMask)
8073 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8074 M = InputsFixed[1] + SourceOffset;
8075 else if (M == InputsFixed[1] + SourceOffset)
8076 M = (InputsFixed[0] ^ 1) + SourceOffset;
8078 InputsFixed[1] = InputsFixed[0] ^ 1;
8081 // Point everything at the fixed inputs.
8082 for (int &M : HalfMask)
8083 if (M == IncomingInputs[0])
8084 M = InputsFixed[0] + SourceOffset;
8085 else if (M == IncomingInputs[1])
8086 M = InputsFixed[1] + SourceOffset;
8088 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8089 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8092 llvm_unreachable("Unhandled input size!");
8095 // Now hoist the DWord down to the right half.
8096 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8097 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8098 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8099 for (int &M : HalfMask)
8100 for (int Input : IncomingInputs)
8102 M = FreeDWord * 2 + Input % 2;
8104 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8105 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8106 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8107 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8109 // Now enact all the shuffles we've computed to move the inputs into their
8111 if (!isNoopShuffleMask(PSHUFLMask))
8112 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8113 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8114 if (!isNoopShuffleMask(PSHUFHMask))
8115 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8116 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8117 if (!isNoopShuffleMask(PSHUFDMask))
8118 V = DAG.getNode(ISD::BITCAST, DL, VT,
8119 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8120 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8121 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8123 // At this point, each half should contain all its inputs, and we can then
8124 // just shuffle them into their final position.
8125 assert(std::count_if(LoMask.begin(), LoMask.end(),
8126 [](int M) { return M >= 4; }) == 0 &&
8127 "Failed to lift all the high half inputs to the low mask!");
8128 assert(std::count_if(HiMask.begin(), HiMask.end(),
8129 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8130 "Failed to lift all the low half inputs to the high mask!");
8132 // Do a half shuffle for the low mask.
8133 if (!isNoopShuffleMask(LoMask))
8134 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8135 getV4X86ShuffleImm8ForMask(LoMask, DAG));
8137 // Do a half shuffle with the high mask after shifting its values down.
8138 for (int &M : HiMask)
8141 if (!isNoopShuffleMask(HiMask))
8142 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8143 getV4X86ShuffleImm8ForMask(HiMask, DAG));
8148 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8149 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8150 SDValue V2, ArrayRef<int> Mask,
8151 SelectionDAG &DAG, bool &V1InUse,
8153 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8159 int Size = Mask.size();
8160 int Scale = 16 / Size;
8161 for (int i = 0; i < 16; ++i) {
8162 if (Mask[i / Scale] == -1) {
8163 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8165 const int ZeroMask = 0x80;
8166 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8168 int V2Idx = Mask[i / Scale] < Size
8170 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8171 if (Zeroable[i / Scale])
8172 V1Idx = V2Idx = ZeroMask;
8173 V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8174 V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8175 V1InUse |= (ZeroMask != V1Idx);
8176 V2InUse |= (ZeroMask != V2Idx);
8181 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8182 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8183 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8185 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8186 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8187 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8189 // If we need shuffled inputs from both, blend the two.
8191 if (V1InUse && V2InUse)
8192 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8194 V = V1InUse ? V1 : V2;
8196 // Cast the result back to the correct type.
8197 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8200 /// \brief Generic lowering of 8-lane i16 shuffles.
8202 /// This handles both single-input shuffles and combined shuffle/blends with
8203 /// two inputs. The single input shuffles are immediately delegated to
8204 /// a dedicated lowering routine.
8206 /// The blends are lowered in one of three fundamental ways. If there are few
8207 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8208 /// of the input is significantly cheaper when lowered as an interleaving of
8209 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8210 /// halves of the inputs separately (making them have relatively few inputs)
8211 /// and then concatenate them.
8212 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8213 const X86Subtarget *Subtarget,
8214 SelectionDAG &DAG) {
8216 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8217 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8218 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8219 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8220 ArrayRef<int> OrigMask = SVOp->getMask();
8221 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8222 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8223 MutableArrayRef<int> Mask(MaskStorage);
8225 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8227 // Whenever we can lower this as a zext, that instruction is strictly faster
8228 // than any alternative.
8229 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8230 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8233 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8235 auto isV2 = [](int M) { return M >= 8; };
8237 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8239 if (NumV2Inputs == 0) {
8240 // Check for being able to broadcast a single element.
8241 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8242 Mask, Subtarget, DAG))
8245 // Try to use shift instructions.
8247 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8250 // Use dedicated unpack instructions for masks that match their pattern.
8251 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8252 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8253 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8254 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8256 // Try to use byte rotation instructions.
8257 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8258 Mask, Subtarget, DAG))
8261 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8265 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8266 "All single-input shuffles should be canonicalized to be V1-input "
8269 // Try to use shift instructions.
8271 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8274 // There are special ways we can lower some single-element blends.
8275 if (NumV2Inputs == 1)
8276 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8277 Mask, Subtarget, DAG))
8280 // We have different paths for blend lowering, but they all must use the
8281 // *exact* same predicate.
8282 bool IsBlendSupported = Subtarget->hasSSE41();
8283 if (IsBlendSupported)
8284 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8288 if (SDValue Masked =
8289 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8292 // Use dedicated unpack instructions for masks that match their pattern.
8293 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8294 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8295 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8296 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8298 // Try to use byte rotation instructions.
8299 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8300 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8303 if (SDValue BitBlend =
8304 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8307 if (SDValue Unpack =
8308 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8311 // If we can't directly blend but can use PSHUFB, that will be better as it
8312 // can both shuffle and set up the inefficient blend.
8313 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8314 bool V1InUse, V2InUse;
8315 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8319 // We can always bit-blend if we have to so the fallback strategy is to
8320 // decompose into single-input permutes and blends.
8321 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8325 /// \brief Check whether a compaction lowering can be done by dropping even
8326 /// elements and compute how many times even elements must be dropped.
8328 /// This handles shuffles which take every Nth element where N is a power of
8329 /// two. Example shuffle masks:
8331 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8332 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8333 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8334 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8335 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8336 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8338 /// Any of these lanes can of course be undef.
8340 /// This routine only supports N <= 3.
8341 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8344 /// \returns N above, or the number of times even elements must be dropped if
8345 /// there is such a number. Otherwise returns zero.
8346 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8347 // Figure out whether we're looping over two inputs or just one.
8348 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8350 // The modulus for the shuffle vector entries is based on whether this is
8351 // a single input or not.
8352 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8353 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8354 "We should only be called with masks with a power-of-2 size!");
8356 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8358 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8359 // and 2^3 simultaneously. This is because we may have ambiguity with
8360 // partially undef inputs.
8361 bool ViableForN[3] = {true, true, true};
8363 for (int i = 0, e = Mask.size(); i < e; ++i) {
8364 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8369 bool IsAnyViable = false;
8370 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8371 if (ViableForN[j]) {
8374 // The shuffle mask must be equal to (i * 2^N) % M.
8375 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8378 ViableForN[j] = false;
8380 // Early exit if we exhaust the possible powers of two.
8385 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8389 // Return 0 as there is no viable power of two.
8393 /// \brief Generic lowering of v16i8 shuffles.
8395 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8396 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8397 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8398 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8400 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8401 const X86Subtarget *Subtarget,
8402 SelectionDAG &DAG) {
8404 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8405 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8406 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8407 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8408 ArrayRef<int> Mask = SVOp->getMask();
8409 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8411 // Try to use shift instructions.
8413 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8416 // Try to use byte rotation instructions.
8417 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8418 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8421 // Try to use a zext lowering.
8422 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8423 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8427 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8429 // For single-input shuffles, there are some nicer lowering tricks we can use.
8430 if (NumV2Elements == 0) {
8431 // Check for being able to broadcast a single element.
8432 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8433 Mask, Subtarget, DAG))
8436 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8437 // Notably, this handles splat and partial-splat shuffles more efficiently.
8438 // However, it only makes sense if the pre-duplication shuffle simplifies
8439 // things significantly. Currently, this means we need to be able to
8440 // express the pre-duplication shuffle as an i16 shuffle.
8442 // FIXME: We should check for other patterns which can be widened into an
8443 // i16 shuffle as well.
8444 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8445 for (int i = 0; i < 16; i += 2)
8446 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8451 auto tryToWidenViaDuplication = [&]() -> SDValue {
8452 if (!canWidenViaDuplication(Mask))
8454 SmallVector<int, 4> LoInputs;
8455 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8456 [](int M) { return M >= 0 && M < 8; });
8457 std::sort(LoInputs.begin(), LoInputs.end());
8458 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8460 SmallVector<int, 4> HiInputs;
8461 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8462 [](int M) { return M >= 8; });
8463 std::sort(HiInputs.begin(), HiInputs.end());
8464 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8467 bool TargetLo = LoInputs.size() >= HiInputs.size();
8468 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8469 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8471 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8472 SmallDenseMap<int, int, 8> LaneMap;
8473 for (int I : InPlaceInputs) {
8474 PreDupI16Shuffle[I/2] = I/2;
8477 int j = TargetLo ? 0 : 4, je = j + 4;
8478 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8479 // Check if j is already a shuffle of this input. This happens when
8480 // there are two adjacent bytes after we move the low one.
8481 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8482 // If we haven't yet mapped the input, search for a slot into which
8484 while (j < je && PreDupI16Shuffle[j] != -1)
8488 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8491 // Map this input with the i16 shuffle.
8492 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8495 // Update the lane map based on the mapping we ended up with.
8496 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8499 ISD::BITCAST, DL, MVT::v16i8,
8500 DAG.getVectorShuffle(MVT::v8i16, DL,
8501 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8502 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8504 // Unpack the bytes to form the i16s that will be shuffled into place.
8505 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8506 MVT::v16i8, V1, V1);
8508 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8509 for (int i = 0; i < 16; ++i)
8510 if (Mask[i] != -1) {
8511 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8512 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8513 if (PostDupI16Shuffle[i / 2] == -1)
8514 PostDupI16Shuffle[i / 2] = MappedMask;
8516 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8517 "Conflicting entrties in the original shuffle!");
8520 ISD::BITCAST, DL, MVT::v16i8,
8521 DAG.getVectorShuffle(MVT::v8i16, DL,
8522 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8523 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8525 if (SDValue V = tryToWidenViaDuplication())
8529 // Use dedicated unpack instructions for masks that match their pattern.
8530 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8531 0, 16, 1, 17, 2, 18, 3, 19,
8533 4, 20, 5, 21, 6, 22, 7, 23}))
8534 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8535 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8536 8, 24, 9, 25, 10, 26, 11, 27,
8538 12, 28, 13, 29, 14, 30, 15, 31}))
8539 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8541 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8542 // with PSHUFB. It is important to do this before we attempt to generate any
8543 // blends but after all of the single-input lowerings. If the single input
8544 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8545 // want to preserve that and we can DAG combine any longer sequences into
8546 // a PSHUFB in the end. But once we start blending from multiple inputs,
8547 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8548 // and there are *very* few patterns that would actually be faster than the
8549 // PSHUFB approach because of its ability to zero lanes.
8551 // FIXME: The only exceptions to the above are blends which are exact
8552 // interleavings with direct instructions supporting them. We currently don't
8553 // handle those well here.
8554 if (Subtarget->hasSSSE3()) {
8555 bool V1InUse = false;
8556 bool V2InUse = false;
8558 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8559 DAG, V1InUse, V2InUse);
8561 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8562 // do so. This avoids using them to handle blends-with-zero which is
8563 // important as a single pshufb is significantly faster for that.
8564 if (V1InUse && V2InUse) {
8565 if (Subtarget->hasSSE41())
8566 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8567 Mask, Subtarget, DAG))
8570 // We can use an unpack to do the blending rather than an or in some
8571 // cases. Even though the or may be (very minorly) more efficient, we
8572 // preference this lowering because there are common cases where part of
8573 // the complexity of the shuffles goes away when we do the final blend as
8575 // FIXME: It might be worth trying to detect if the unpack-feeding
8576 // shuffles will both be pshufb, in which case we shouldn't bother with
8578 if (SDValue Unpack =
8579 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8586 // There are special ways we can lower some single-element blends.
8587 if (NumV2Elements == 1)
8588 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8589 Mask, Subtarget, DAG))
8592 if (SDValue BitBlend =
8593 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8596 // Check whether a compaction lowering can be done. This handles shuffles
8597 // which take every Nth element for some even N. See the helper function for
8600 // We special case these as they can be particularly efficiently handled with
8601 // the PACKUSB instruction on x86 and they show up in common patterns of
8602 // rearranging bytes to truncate wide elements.
8603 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8604 // NumEvenDrops is the power of two stride of the elements. Another way of
8605 // thinking about it is that we need to drop the even elements this many
8606 // times to get the original input.
8607 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8609 // First we need to zero all the dropped bytes.
8610 assert(NumEvenDrops <= 3 &&
8611 "No support for dropping even elements more than 3 times.");
8612 // We use the mask type to pick which bytes are preserved based on how many
8613 // elements are dropped.
8614 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8615 SDValue ByteClearMask =
8616 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8617 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8618 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8620 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8622 // Now pack things back together.
8623 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8624 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8625 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8626 for (int i = 1; i < NumEvenDrops; ++i) {
8627 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8628 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8634 // Handle multi-input cases by blending single-input shuffles.
8635 if (NumV2Elements > 0)
8636 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8639 // The fallback path for single-input shuffles widens this into two v8i16
8640 // vectors with unpacks, shuffles those, and then pulls them back together
8644 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8645 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8646 for (int i = 0; i < 16; ++i)
8648 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8650 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8652 SDValue VLoHalf, VHiHalf;
8653 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8654 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8656 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8657 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8658 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8659 [](int M) { return M >= 0 && M % 2 == 1; })) {
8660 // Use a mask to drop the high bytes.
8661 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8662 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8663 DAG.getConstant(0x00FF, MVT::v8i16));
8665 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8666 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8668 // Squash the masks to point directly into VLoHalf.
8669 for (int &M : LoBlendMask)
8672 for (int &M : HiBlendMask)
8676 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8677 // VHiHalf so that we can blend them as i16s.
8678 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8679 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8680 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8681 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8684 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8685 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8687 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8690 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8692 /// This routine breaks down the specific type of 128-bit shuffle and
8693 /// dispatches to the lowering routines accordingly.
8694 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8695 MVT VT, const X86Subtarget *Subtarget,
8696 SelectionDAG &DAG) {
8697 switch (VT.SimpleTy) {
8699 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8701 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8703 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8705 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8707 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8709 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8712 llvm_unreachable("Unimplemented!");
8716 /// \brief Helper function to test whether a shuffle mask could be
8717 /// simplified by widening the elements being shuffled.
8719 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8720 /// leaves it in an unspecified state.
8722 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8723 /// shuffle masks. The latter have the special property of a '-2' representing
8724 /// a zero-ed lane of a vector.
8725 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8726 SmallVectorImpl<int> &WidenedMask) {
8727 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8728 // If both elements are undef, its trivial.
8729 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8730 WidenedMask.push_back(SM_SentinelUndef);
8734 // Check for an undef mask and a mask value properly aligned to fit with
8735 // a pair of values. If we find such a case, use the non-undef mask's value.
8736 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8737 WidenedMask.push_back(Mask[i + 1] / 2);
8740 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8741 WidenedMask.push_back(Mask[i] / 2);
8745 // When zeroing, we need to spread the zeroing across both lanes to widen.
8746 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8747 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8748 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8749 WidenedMask.push_back(SM_SentinelZero);
8755 // Finally check if the two mask values are adjacent and aligned with
8757 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8758 WidenedMask.push_back(Mask[i] / 2);
8762 // Otherwise we can't safely widen the elements used in this shuffle.
8765 assert(WidenedMask.size() == Mask.size() / 2 &&
8766 "Incorrect size of mask after widening the elements!");
8771 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8773 /// This routine just extracts two subvectors, shuffles them independently, and
8774 /// then concatenates them back together. This should work effectively with all
8775 /// AVX vector shuffle types.
8776 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8777 SDValue V2, ArrayRef<int> Mask,
8778 SelectionDAG &DAG) {
8779 assert(VT.getSizeInBits() >= 256 &&
8780 "Only for 256-bit or wider vector shuffles!");
8781 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8782 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8784 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8785 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8787 int NumElements = VT.getVectorNumElements();
8788 int SplitNumElements = NumElements / 2;
8789 MVT ScalarVT = VT.getScalarType();
8790 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8792 // Rather than splitting build-vectors, just build two narrower build
8793 // vectors. This helps shuffling with splats and zeros.
8794 auto SplitVector = [&](SDValue V) {
8795 while (V.getOpcode() == ISD::BITCAST)
8796 V = V->getOperand(0);
8798 MVT OrigVT = V.getSimpleValueType();
8799 int OrigNumElements = OrigVT.getVectorNumElements();
8800 int OrigSplitNumElements = OrigNumElements / 2;
8801 MVT OrigScalarVT = OrigVT.getScalarType();
8802 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8806 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8808 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8809 DAG.getIntPtrConstant(0));
8810 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8811 DAG.getIntPtrConstant(OrigSplitNumElements));
8814 SmallVector<SDValue, 16> LoOps, HiOps;
8815 for (int i = 0; i < OrigSplitNumElements; ++i) {
8816 LoOps.push_back(BV->getOperand(i));
8817 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8819 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8820 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8822 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8823 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8826 SDValue LoV1, HiV1, LoV2, HiV2;
8827 std::tie(LoV1, HiV1) = SplitVector(V1);
8828 std::tie(LoV2, HiV2) = SplitVector(V2);
8830 // Now create two 4-way blends of these half-width vectors.
8831 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8832 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8833 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8834 for (int i = 0; i < SplitNumElements; ++i) {
8835 int M = HalfMask[i];
8836 if (M >= NumElements) {
8837 if (M >= NumElements + SplitNumElements)
8841 V2BlendMask.push_back(M - NumElements);
8842 V1BlendMask.push_back(-1);
8843 BlendMask.push_back(SplitNumElements + i);
8844 } else if (M >= 0) {
8845 if (M >= SplitNumElements)
8849 V2BlendMask.push_back(-1);
8850 V1BlendMask.push_back(M);
8851 BlendMask.push_back(i);
8853 V2BlendMask.push_back(-1);
8854 V1BlendMask.push_back(-1);
8855 BlendMask.push_back(-1);
8859 // Because the lowering happens after all combining takes place, we need to
8860 // manually combine these blend masks as much as possible so that we create
8861 // a minimal number of high-level vector shuffle nodes.
8863 // First try just blending the halves of V1 or V2.
8864 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
8865 return DAG.getUNDEF(SplitVT);
8866 if (!UseLoV2 && !UseHiV2)
8867 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8868 if (!UseLoV1 && !UseHiV1)
8869 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8871 SDValue V1Blend, V2Blend;
8872 if (UseLoV1 && UseHiV1) {
8874 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8876 // We only use half of V1 so map the usage down into the final blend mask.
8877 V1Blend = UseLoV1 ? LoV1 : HiV1;
8878 for (int i = 0; i < SplitNumElements; ++i)
8879 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
8880 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
8882 if (UseLoV2 && UseHiV2) {
8884 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8886 // We only use half of V2 so map the usage down into the final blend mask.
8887 V2Blend = UseLoV2 ? LoV2 : HiV2;
8888 for (int i = 0; i < SplitNumElements; ++i)
8889 if (BlendMask[i] >= SplitNumElements)
8890 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
8892 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8894 SDValue Lo = HalfBlend(LoMask);
8895 SDValue Hi = HalfBlend(HiMask);
8896 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8899 /// \brief Either split a vector in halves or decompose the shuffles and the
8902 /// This is provided as a good fallback for many lowerings of non-single-input
8903 /// shuffles with more than one 128-bit lane. In those cases, we want to select
8904 /// between splitting the shuffle into 128-bit components and stitching those
8905 /// back together vs. extracting the single-input shuffles and blending those
8907 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
8908 SDValue V2, ArrayRef<int> Mask,
8909 SelectionDAG &DAG) {
8910 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
8911 "lower single-input shuffles as it "
8912 "could then recurse on itself.");
8913 int Size = Mask.size();
8915 // If this can be modeled as a broadcast of two elements followed by a blend,
8916 // prefer that lowering. This is especially important because broadcasts can
8917 // often fold with memory operands.
8918 auto DoBothBroadcast = [&] {
8919 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
8922 if (V2BroadcastIdx == -1)
8923 V2BroadcastIdx = M - Size;
8924 else if (M - Size != V2BroadcastIdx)
8926 } else if (M >= 0) {
8927 if (V1BroadcastIdx == -1)
8929 else if (M != V1BroadcastIdx)
8934 if (DoBothBroadcast())
8935 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
8938 // If the inputs all stem from a single 128-bit lane of each input, then we
8939 // split them rather than blending because the split will decompose to
8940 // unusually few instructions.
8941 int LaneCount = VT.getSizeInBits() / 128;
8942 int LaneSize = Size / LaneCount;
8943 SmallBitVector LaneInputs[2];
8944 LaneInputs[0].resize(LaneCount, false);
8945 LaneInputs[1].resize(LaneCount, false);
8946 for (int i = 0; i < Size; ++i)
8948 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
8949 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
8950 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8952 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
8953 // that the decomposed single-input shuffles don't end up here.
8954 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
8957 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
8958 /// a permutation and blend of those lanes.
8960 /// This essentially blends the out-of-lane inputs to each lane into the lane
8961 /// from a permuted copy of the vector. This lowering strategy results in four
8962 /// instructions in the worst case for a single-input cross lane shuffle which
8963 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
8964 /// of. Special cases for each particular shuffle pattern should be handled
8965 /// prior to trying this lowering.
8966 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
8967 SDValue V1, SDValue V2,
8969 SelectionDAG &DAG) {
8970 // FIXME: This should probably be generalized for 512-bit vectors as well.
8971 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8972 int LaneSize = Mask.size() / 2;
8974 // If there are only inputs from one 128-bit lane, splitting will in fact be
8975 // less expensive. The flags track whether the given lane contains an element
8976 // that crosses to another lane.
8977 bool LaneCrossing[2] = {false, false};
8978 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8979 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
8980 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
8981 if (!LaneCrossing[0] || !LaneCrossing[1])
8982 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
8984 if (isSingleInputShuffleMask(Mask)) {
8985 SmallVector<int, 32> FlippedBlendMask;
8986 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8987 FlippedBlendMask.push_back(
8988 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
8990 : Mask[i] % LaneSize +
8991 (i / LaneSize) * LaneSize + Size));
8993 // Flip the vector, and blend the results which should now be in-lane. The
8994 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
8995 // 5 for the high source. The value 3 selects the high half of source 2 and
8996 // the value 2 selects the low half of source 2. We only use source 2 to
8997 // allow folding it into a memory operand.
8998 unsigned PERMMask = 3 | 2 << 4;
8999 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9000 V1, DAG.getConstant(PERMMask, MVT::i8));
9001 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9004 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9005 // will be handled by the above logic and a blend of the results, much like
9006 // other patterns in AVX.
9007 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9010 /// \brief Handle lowering 2-lane 128-bit shuffles.
9011 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9012 SDValue V2, ArrayRef<int> Mask,
9013 const X86Subtarget *Subtarget,
9014 SelectionDAG &DAG) {
9015 // Blends are faster and handle all the non-lane-crossing cases.
9016 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9020 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9021 VT.getVectorNumElements() / 2);
9022 // Check for patterns which can be matched with a single insert of a 128-bit
9024 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}) ||
9025 isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9026 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9027 DAG.getIntPtrConstant(0));
9028 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9029 Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9030 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9032 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 6, 7})) {
9033 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9034 DAG.getIntPtrConstant(0));
9035 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9036 DAG.getIntPtrConstant(2));
9037 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9040 // Otherwise form a 128-bit permutation.
9041 // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9042 int MaskLO = Mask[0];
9043 if (MaskLO == SM_SentinelUndef)
9044 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9046 int MaskHI = Mask[2];
9047 if (MaskHI == SM_SentinelUndef)
9048 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9050 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9051 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9052 DAG.getConstant(PermMask, MVT::i8));
9055 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9056 /// shuffling each lane.
9058 /// This will only succeed when the result of fixing the 128-bit lanes results
9059 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9060 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9061 /// the lane crosses early and then use simpler shuffles within each lane.
9063 /// FIXME: It might be worthwhile at some point to support this without
9064 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9065 /// in x86 only floating point has interesting non-repeating shuffles, and even
9066 /// those are still *marginally* more expensive.
9067 static SDValue lowerVectorShuffleByMerging128BitLanes(
9068 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9069 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9070 assert(!isSingleInputShuffleMask(Mask) &&
9071 "This is only useful with multiple inputs.");
9073 int Size = Mask.size();
9074 int LaneSize = 128 / VT.getScalarSizeInBits();
9075 int NumLanes = Size / LaneSize;
9076 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9078 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9079 // check whether the in-128-bit lane shuffles share a repeating pattern.
9080 SmallVector<int, 4> Lanes;
9081 Lanes.resize(NumLanes, -1);
9082 SmallVector<int, 4> InLaneMask;
9083 InLaneMask.resize(LaneSize, -1);
9084 for (int i = 0; i < Size; ++i) {
9088 int j = i / LaneSize;
9091 // First entry we've seen for this lane.
9092 Lanes[j] = Mask[i] / LaneSize;
9093 } else if (Lanes[j] != Mask[i] / LaneSize) {
9094 // This doesn't match the lane selected previously!
9098 // Check that within each lane we have a consistent shuffle mask.
9099 int k = i % LaneSize;
9100 if (InLaneMask[k] < 0) {
9101 InLaneMask[k] = Mask[i] % LaneSize;
9102 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9103 // This doesn't fit a repeating in-lane mask.
9108 // First shuffle the lanes into place.
9109 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9110 VT.getSizeInBits() / 64);
9111 SmallVector<int, 8> LaneMask;
9112 LaneMask.resize(NumLanes * 2, -1);
9113 for (int i = 0; i < NumLanes; ++i)
9114 if (Lanes[i] >= 0) {
9115 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9116 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9119 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9120 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9121 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9123 // Cast it back to the type we actually want.
9124 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9126 // Now do a simple shuffle that isn't lane crossing.
9127 SmallVector<int, 8> NewMask;
9128 NewMask.resize(Size, -1);
9129 for (int i = 0; i < Size; ++i)
9131 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9132 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9133 "Must not introduce lane crosses at this point!");
9135 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9138 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9141 /// This returns true if the elements from a particular input are already in the
9142 /// slot required by the given mask and require no permutation.
9143 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9144 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9145 int Size = Mask.size();
9146 for (int i = 0; i < Size; ++i)
9147 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9153 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9155 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9156 /// isn't available.
9157 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9158 const X86Subtarget *Subtarget,
9159 SelectionDAG &DAG) {
9161 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9162 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9163 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9164 ArrayRef<int> Mask = SVOp->getMask();
9165 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9167 SmallVector<int, 4> WidenedMask;
9168 if (canWidenShuffleElements(Mask, WidenedMask))
9169 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9172 if (isSingleInputShuffleMask(Mask)) {
9173 // Check for being able to broadcast a single element.
9174 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9175 Mask, Subtarget, DAG))
9178 // Use low duplicate instructions for masks that match their pattern.
9179 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9180 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9182 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9183 // Non-half-crossing single input shuffles can be lowerid with an
9184 // interleaved permutation.
9185 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9186 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9187 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9188 DAG.getConstant(VPERMILPMask, MVT::i8));
9191 // With AVX2 we have direct support for this permutation.
9192 if (Subtarget->hasAVX2())
9193 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9194 getV4X86ShuffleImm8ForMask(Mask, DAG));
9196 // Otherwise, fall back.
9197 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9201 // X86 has dedicated unpack instructions that can handle specific blend
9202 // operations: UNPCKH and UNPCKL.
9203 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9204 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9205 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9206 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9207 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9208 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9209 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9210 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9212 // If we have a single input to the zero element, insert that into V1 if we
9213 // can do so cheaply.
9215 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9216 if (NumV2Elements == 1 && Mask[0] >= 4)
9217 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9218 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9221 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9225 // Check if the blend happens to exactly fit that of SHUFPD.
9226 if ((Mask[0] == -1 || Mask[0] < 2) &&
9227 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9228 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9229 (Mask[3] == -1 || Mask[3] >= 6)) {
9230 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9231 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9232 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9233 DAG.getConstant(SHUFPDMask, MVT::i8));
9235 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9236 (Mask[1] == -1 || Mask[1] < 2) &&
9237 (Mask[2] == -1 || Mask[2] >= 6) &&
9238 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9239 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9240 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9241 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9242 DAG.getConstant(SHUFPDMask, MVT::i8));
9245 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9246 // shuffle. However, if we have AVX2 and either inputs are already in place,
9247 // we will be able to shuffle even across lanes the other input in a single
9248 // instruction so skip this pattern.
9249 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9250 isShuffleMaskInputInPlace(1, Mask))))
9251 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9252 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9255 // If we have AVX2 then we always want to lower with a blend because an v4 we
9256 // can fully permute the elements.
9257 if (Subtarget->hasAVX2())
9258 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9261 // Otherwise fall back on generic lowering.
9262 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9265 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9267 /// This routine is only called when we have AVX2 and thus a reasonable
9268 /// instruction set for v4i64 shuffling..
9269 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9270 const X86Subtarget *Subtarget,
9271 SelectionDAG &DAG) {
9273 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9274 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9275 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9276 ArrayRef<int> Mask = SVOp->getMask();
9277 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9278 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9280 SmallVector<int, 4> WidenedMask;
9281 if (canWidenShuffleElements(Mask, WidenedMask))
9282 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9285 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9289 // Check for being able to broadcast a single element.
9290 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9291 Mask, Subtarget, DAG))
9294 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9295 // use lower latency instructions that will operate on both 128-bit lanes.
9296 SmallVector<int, 2> RepeatedMask;
9297 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9298 if (isSingleInputShuffleMask(Mask)) {
9299 int PSHUFDMask[] = {-1, -1, -1, -1};
9300 for (int i = 0; i < 2; ++i)
9301 if (RepeatedMask[i] >= 0) {
9302 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9303 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9306 ISD::BITCAST, DL, MVT::v4i64,
9307 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9308 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9309 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9313 // AVX2 provides a direct instruction for permuting a single input across
9315 if (isSingleInputShuffleMask(Mask))
9316 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9317 getV4X86ShuffleImm8ForMask(Mask, DAG));
9319 // Try to use shift instructions.
9321 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9324 // Use dedicated unpack instructions for masks that match their pattern.
9325 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9326 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9327 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9328 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9329 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9330 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9331 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9332 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9334 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9335 // shuffle. However, if we have AVX2 and either inputs are already in place,
9336 // we will be able to shuffle even across lanes the other input in a single
9337 // instruction so skip this pattern.
9338 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9339 isShuffleMaskInputInPlace(1, Mask))))
9340 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9341 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9344 // Otherwise fall back on generic blend lowering.
9345 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9349 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9351 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9352 /// isn't available.
9353 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9354 const X86Subtarget *Subtarget,
9355 SelectionDAG &DAG) {
9357 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9358 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9359 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9360 ArrayRef<int> Mask = SVOp->getMask();
9361 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9363 // If we have a single input to the zero element, insert that into V1 if we
9364 // can do so cheaply.
9366 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 8; });
9367 if (NumV2Elements == 1 && Mask[0] >= 8)
9368 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9369 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9372 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9376 // Check for being able to broadcast a single element.
9377 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9378 Mask, Subtarget, DAG))
9381 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9382 // options to efficiently lower the shuffle.
9383 SmallVector<int, 4> RepeatedMask;
9384 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9385 assert(RepeatedMask.size() == 4 &&
9386 "Repeated masks must be half the mask width!");
9388 // Use even/odd duplicate instructions for masks that match their pattern.
9389 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9390 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9391 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9392 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9394 if (isSingleInputShuffleMask(Mask))
9395 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9396 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9398 // Use dedicated unpack instructions for masks that match their pattern.
9399 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9400 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9401 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9402 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9403 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9404 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9405 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9406 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9408 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9409 // have already handled any direct blends. We also need to squash the
9410 // repeated mask into a simulated v4f32 mask.
9411 for (int i = 0; i < 4; ++i)
9412 if (RepeatedMask[i] >= 8)
9413 RepeatedMask[i] -= 4;
9414 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9417 // If we have a single input shuffle with different shuffle patterns in the
9418 // two 128-bit lanes use the variable mask to VPERMILPS.
9419 if (isSingleInputShuffleMask(Mask)) {
9420 SDValue VPermMask[8];
9421 for (int i = 0; i < 8; ++i)
9422 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9423 : DAG.getConstant(Mask[i], MVT::i32);
9424 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9426 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9427 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9429 if (Subtarget->hasAVX2())
9430 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9431 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9432 DAG.getNode(ISD::BUILD_VECTOR, DL,
9433 MVT::v8i32, VPermMask)),
9436 // Otherwise, fall back.
9437 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9441 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9443 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9444 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9447 // If we have AVX2 then we always want to lower with a blend because at v8 we
9448 // can fully permute the elements.
9449 if (Subtarget->hasAVX2())
9450 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9453 // Otherwise fall back on generic lowering.
9454 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9457 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9459 /// This routine is only called when we have AVX2 and thus a reasonable
9460 /// instruction set for v8i32 shuffling..
9461 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9462 const X86Subtarget *Subtarget,
9463 SelectionDAG &DAG) {
9465 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9466 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9467 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9468 ArrayRef<int> Mask = SVOp->getMask();
9469 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9470 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9472 // Whenever we can lower this as a zext, that instruction is strictly faster
9473 // than any alternative. It also allows us to fold memory operands into the
9474 // shuffle in many cases.
9475 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9476 Mask, Subtarget, DAG))
9479 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9483 // Check for being able to broadcast a single element.
9484 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9485 Mask, Subtarget, DAG))
9488 // If the shuffle mask is repeated in each 128-bit lane we can use more
9489 // efficient instructions that mirror the shuffles across the two 128-bit
9491 SmallVector<int, 4> RepeatedMask;
9492 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9493 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9494 if (isSingleInputShuffleMask(Mask))
9495 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9496 getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9498 // Use dedicated unpack instructions for masks that match their pattern.
9499 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9500 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9501 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9502 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9503 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9504 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9505 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9506 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9509 // Try to use shift instructions.
9511 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9514 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9515 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9518 // If the shuffle patterns aren't repeated but it is a single input, directly
9519 // generate a cross-lane VPERMD instruction.
9520 if (isSingleInputShuffleMask(Mask)) {
9521 SDValue VPermMask[8];
9522 for (int i = 0; i < 8; ++i)
9523 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9524 : DAG.getConstant(Mask[i], MVT::i32);
9526 X86ISD::VPERMV, DL, MVT::v8i32,
9527 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9530 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9532 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9533 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9536 // Otherwise fall back on generic blend lowering.
9537 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9541 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9543 /// This routine is only called when we have AVX2 and thus a reasonable
9544 /// instruction set for v16i16 shuffling..
9545 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9546 const X86Subtarget *Subtarget,
9547 SelectionDAG &DAG) {
9549 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9550 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9551 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9552 ArrayRef<int> Mask = SVOp->getMask();
9553 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9554 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9556 // Whenever we can lower this as a zext, that instruction is strictly faster
9557 // than any alternative. It also allows us to fold memory operands into the
9558 // shuffle in many cases.
9559 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9560 Mask, Subtarget, DAG))
9563 // Check for being able to broadcast a single element.
9564 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9565 Mask, Subtarget, DAG))
9568 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9572 // Use dedicated unpack instructions for masks that match their pattern.
9573 if (isShuffleEquivalent(V1, V2, Mask,
9574 {// First 128-bit lane:
9575 0, 16, 1, 17, 2, 18, 3, 19,
9576 // Second 128-bit lane:
9577 8, 24, 9, 25, 10, 26, 11, 27}))
9578 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9579 if (isShuffleEquivalent(V1, V2, Mask,
9580 {// First 128-bit lane:
9581 4, 20, 5, 21, 6, 22, 7, 23,
9582 // Second 128-bit lane:
9583 12, 28, 13, 29, 14, 30, 15, 31}))
9584 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9586 // Try to use shift instructions.
9588 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9591 // Try to use byte rotation instructions.
9592 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9593 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9596 if (isSingleInputShuffleMask(Mask)) {
9597 // There are no generalized cross-lane shuffle operations available on i16
9599 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9600 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9603 SmallVector<int, 8> RepeatedMask;
9604 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9605 // As this is a single-input shuffle, the repeated mask should be
9606 // a strictly valid v8i16 mask that we can pass through to the v8i16
9607 // lowering to handle even the v16 case.
9608 return lowerV8I16GeneralSingleInputVectorShuffle(
9609 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9612 SDValue PSHUFBMask[32];
9613 for (int i = 0; i < 16; ++i) {
9614 if (Mask[i] == -1) {
9615 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9619 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9620 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9621 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9622 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9625 ISD::BITCAST, DL, MVT::v16i16,
9627 X86ISD::PSHUFB, DL, MVT::v32i8,
9628 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9629 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9632 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9634 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9635 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9638 // Otherwise fall back on generic lowering.
9639 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9642 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9644 /// This routine is only called when we have AVX2 and thus a reasonable
9645 /// instruction set for v32i8 shuffling..
9646 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9647 const X86Subtarget *Subtarget,
9648 SelectionDAG &DAG) {
9650 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9651 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9652 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9653 ArrayRef<int> Mask = SVOp->getMask();
9654 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9655 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9657 // Whenever we can lower this as a zext, that instruction is strictly faster
9658 // than any alternative. It also allows us to fold memory operands into the
9659 // shuffle in many cases.
9660 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9661 Mask, Subtarget, DAG))
9664 // Check for being able to broadcast a single element.
9665 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9666 Mask, Subtarget, DAG))
9669 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9673 // Use dedicated unpack instructions for masks that match their pattern.
9674 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9676 if (isShuffleEquivalent(
9678 {// First 128-bit lane:
9679 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9680 // Second 128-bit lane:
9681 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9682 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9683 if (isShuffleEquivalent(
9685 {// First 128-bit lane:
9686 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9687 // Second 128-bit lane:
9688 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9689 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9691 // Try to use shift instructions.
9693 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9696 // Try to use byte rotation instructions.
9697 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9698 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9701 if (isSingleInputShuffleMask(Mask)) {
9702 // There are no generalized cross-lane shuffle operations available on i8
9704 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9705 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9708 SDValue PSHUFBMask[32];
9709 for (int i = 0; i < 32; ++i)
9712 ? DAG.getUNDEF(MVT::i8)
9713 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9716 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9717 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9720 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9722 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9723 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9726 // Otherwise fall back on generic lowering.
9727 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9730 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9732 /// This routine either breaks down the specific type of a 256-bit x86 vector
9733 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9734 /// together based on the available instructions.
9735 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9736 MVT VT, const X86Subtarget *Subtarget,
9737 SelectionDAG &DAG) {
9739 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9740 ArrayRef<int> Mask = SVOp->getMask();
9742 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9743 // check for those subtargets here and avoid much of the subtarget querying in
9744 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9745 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9746 // floating point types there eventually, just immediately cast everything to
9747 // a float and operate entirely in that domain.
9748 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9749 int ElementBits = VT.getScalarSizeInBits();
9750 if (ElementBits < 32)
9751 // No floating point type available, decompose into 128-bit vectors.
9752 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9754 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9755 VT.getVectorNumElements());
9756 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9757 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9758 return DAG.getNode(ISD::BITCAST, DL, VT,
9759 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9762 switch (VT.SimpleTy) {
9764 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9766 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9768 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9770 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9772 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9774 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9777 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9781 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9782 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9783 const X86Subtarget *Subtarget,
9784 SelectionDAG &DAG) {
9786 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9787 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9788 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9789 ArrayRef<int> Mask = SVOp->getMask();
9790 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9792 // X86 has dedicated unpack instructions that can handle specific blend
9793 // operations: UNPCKH and UNPCKL.
9794 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9795 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9796 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9797 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9799 // FIXME: Implement direct support for this type!
9800 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9803 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9804 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9805 const X86Subtarget *Subtarget,
9806 SelectionDAG &DAG) {
9808 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9809 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9810 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9811 ArrayRef<int> Mask = SVOp->getMask();
9812 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9814 // Use dedicated unpack instructions for masks that match their pattern.
9815 if (isShuffleEquivalent(V1, V2, Mask,
9816 {// First 128-bit lane.
9817 0, 16, 1, 17, 4, 20, 5, 21,
9818 // Second 128-bit lane.
9819 8, 24, 9, 25, 12, 28, 13, 29}))
9820 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9821 if (isShuffleEquivalent(V1, V2, Mask,
9822 {// First 128-bit lane.
9823 2, 18, 3, 19, 6, 22, 7, 23,
9824 // Second 128-bit lane.
9825 10, 26, 11, 27, 14, 30, 15, 31}))
9826 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9828 // FIXME: Implement direct support for this type!
9829 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9832 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
9833 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9834 const X86Subtarget *Subtarget,
9835 SelectionDAG &DAG) {
9837 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9838 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
9839 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9840 ArrayRef<int> Mask = SVOp->getMask();
9841 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9843 // X86 has dedicated unpack instructions that can handle specific blend
9844 // operations: UNPCKH and UNPCKL.
9845 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9846 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
9847 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9848 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
9850 // FIXME: Implement direct support for this type!
9851 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
9854 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
9855 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9856 const X86Subtarget *Subtarget,
9857 SelectionDAG &DAG) {
9859 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9860 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
9861 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9862 ArrayRef<int> Mask = SVOp->getMask();
9863 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9865 // Use dedicated unpack instructions for masks that match their pattern.
9866 if (isShuffleEquivalent(V1, V2, Mask,
9867 {// First 128-bit lane.
9868 0, 16, 1, 17, 4, 20, 5, 21,
9869 // Second 128-bit lane.
9870 8, 24, 9, 25, 12, 28, 13, 29}))
9871 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
9872 if (isShuffleEquivalent(V1, V2, Mask,
9873 {// First 128-bit lane.
9874 2, 18, 3, 19, 6, 22, 7, 23,
9875 // Second 128-bit lane.
9876 10, 26, 11, 27, 14, 30, 15, 31}))
9877 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
9879 // FIXME: Implement direct support for this type!
9880 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
9883 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
9884 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885 const X86Subtarget *Subtarget,
9886 SelectionDAG &DAG) {
9888 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9889 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
9890 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9891 ArrayRef<int> Mask = SVOp->getMask();
9892 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9893 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
9895 // FIXME: Implement direct support for this type!
9896 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
9899 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
9900 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9901 const X86Subtarget *Subtarget,
9902 SelectionDAG &DAG) {
9904 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9905 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
9906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9907 ArrayRef<int> Mask = SVOp->getMask();
9908 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
9909 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
9911 // FIXME: Implement direct support for this type!
9912 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
9915 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
9917 /// This routine either breaks down the specific type of a 512-bit x86 vector
9918 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
9919 /// together based on the available instructions.
9920 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9921 MVT VT, const X86Subtarget *Subtarget,
9922 SelectionDAG &DAG) {
9924 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9925 ArrayRef<int> Mask = SVOp->getMask();
9926 assert(Subtarget->hasAVX512() &&
9927 "Cannot lower 512-bit vectors w/ basic ISA!");
9929 // Check for being able to broadcast a single element.
9930 if (SDValue Broadcast =
9931 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
9934 // Dispatch to each element type for lowering. If we don't have supprot for
9935 // specific element type shuffles at 512 bits, immediately split them and
9936 // lower them. Each lowering routine of a given type is allowed to assume that
9937 // the requisite ISA extensions for that element type are available.
9938 switch (VT.SimpleTy) {
9940 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9942 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9944 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9946 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9948 if (Subtarget->hasBWI())
9949 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9952 if (Subtarget->hasBWI())
9953 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9957 llvm_unreachable("Not a valid 512-bit x86 vector type!");
9960 // Otherwise fall back on splitting.
9961 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9964 /// \brief Top-level lowering for x86 vector shuffles.
9966 /// This handles decomposition, canonicalization, and lowering of all x86
9967 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9968 /// above in helper routines. The canonicalization attempts to widen shuffles
9969 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9970 /// s.t. only one of the two inputs needs to be tested, etc.
9971 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9972 SelectionDAG &DAG) {
9973 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9974 ArrayRef<int> Mask = SVOp->getMask();
9975 SDValue V1 = Op.getOperand(0);
9976 SDValue V2 = Op.getOperand(1);
9977 MVT VT = Op.getSimpleValueType();
9978 int NumElements = VT.getVectorNumElements();
9981 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9983 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9984 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9985 if (V1IsUndef && V2IsUndef)
9986 return DAG.getUNDEF(VT);
9988 // When we create a shuffle node we put the UNDEF node to second operand,
9989 // but in some cases the first operand may be transformed to UNDEF.
9990 // In this case we should just commute the node.
9992 return DAG.getCommutedVectorShuffle(*SVOp);
9994 // Check for non-undef masks pointing at an undef vector and make the masks
9995 // undef as well. This makes it easier to match the shuffle based solely on
9999 if (M >= NumElements) {
10000 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10001 for (int &M : NewMask)
10002 if (M >= NumElements)
10004 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10007 // We actually see shuffles that are entirely re-arrangements of a set of
10008 // zero inputs. This mostly happens while decomposing complex shuffles into
10009 // simple ones. Directly lower these as a buildvector of zeros.
10010 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10011 if (Zeroable.all())
10012 return getZeroVector(VT, Subtarget, DAG, dl);
10014 // Try to collapse shuffles into using a vector type with fewer elements but
10015 // wider element types. We cap this to not form integers or floating point
10016 // elements wider than 64 bits, but it might be interesting to form i128
10017 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10018 SmallVector<int, 16> WidenedMask;
10019 if (VT.getScalarSizeInBits() < 64 &&
10020 canWidenShuffleElements(Mask, WidenedMask)) {
10021 MVT NewEltVT = VT.isFloatingPoint()
10022 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10023 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10024 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10025 // Make sure that the new vector type is legal. For example, v2f64 isn't
10027 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10028 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10029 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10030 return DAG.getNode(ISD::BITCAST, dl, VT,
10031 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10035 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10036 for (int M : SVOp->getMask())
10038 ++NumUndefElements;
10039 else if (M < NumElements)
10044 // Commute the shuffle as needed such that more elements come from V1 than
10045 // V2. This allows us to match the shuffle pattern strictly on how many
10046 // elements come from V1 without handling the symmetric cases.
10047 if (NumV2Elements > NumV1Elements)
10048 return DAG.getCommutedVectorShuffle(*SVOp);
10050 // When the number of V1 and V2 elements are the same, try to minimize the
10051 // number of uses of V2 in the low half of the vector. When that is tied,
10052 // ensure that the sum of indices for V1 is equal to or lower than the sum
10053 // indices for V2. When those are equal, try to ensure that the number of odd
10054 // indices for V1 is lower than the number of odd indices for V2.
10055 if (NumV1Elements == NumV2Elements) {
10056 int LowV1Elements = 0, LowV2Elements = 0;
10057 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10058 if (M >= NumElements)
10062 if (LowV2Elements > LowV1Elements) {
10063 return DAG.getCommutedVectorShuffle(*SVOp);
10064 } else if (LowV2Elements == LowV1Elements) {
10065 int SumV1Indices = 0, SumV2Indices = 0;
10066 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10067 if (SVOp->getMask()[i] >= NumElements)
10069 else if (SVOp->getMask()[i] >= 0)
10071 if (SumV2Indices < SumV1Indices) {
10072 return DAG.getCommutedVectorShuffle(*SVOp);
10073 } else if (SumV2Indices == SumV1Indices) {
10074 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10075 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10076 if (SVOp->getMask()[i] >= NumElements)
10077 NumV2OddIndices += i % 2;
10078 else if (SVOp->getMask()[i] >= 0)
10079 NumV1OddIndices += i % 2;
10080 if (NumV2OddIndices < NumV1OddIndices)
10081 return DAG.getCommutedVectorShuffle(*SVOp);
10086 // For each vector width, delegate to a specialized lowering routine.
10087 if (VT.getSizeInBits() == 128)
10088 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10090 if (VT.getSizeInBits() == 256)
10091 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10093 // Force AVX-512 vectors to be scalarized for now.
10094 // FIXME: Implement AVX-512 support!
10095 if (VT.getSizeInBits() == 512)
10096 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10098 llvm_unreachable("Unimplemented!");
10101 // This function assumes its argument is a BUILD_VECTOR of constants or
10102 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10104 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10105 unsigned &MaskValue) {
10107 unsigned NumElems = BuildVector->getNumOperands();
10108 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10109 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10110 unsigned NumElemsInLane = NumElems / NumLanes;
10112 // Blend for v16i16 should be symetric for the both lanes.
10113 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10114 SDValue EltCond = BuildVector->getOperand(i);
10115 SDValue SndLaneEltCond =
10116 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10118 int Lane1Cond = -1, Lane2Cond = -1;
10119 if (isa<ConstantSDNode>(EltCond))
10120 Lane1Cond = !isZero(EltCond);
10121 if (isa<ConstantSDNode>(SndLaneEltCond))
10122 Lane2Cond = !isZero(SndLaneEltCond);
10124 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10125 // Lane1Cond != 0, means we want the first argument.
10126 // Lane1Cond == 0, means we want the second argument.
10127 // The encoding of this argument is 0 for the first argument, 1
10128 // for the second. Therefore, invert the condition.
10129 MaskValue |= !Lane1Cond << i;
10130 else if (Lane1Cond < 0)
10131 MaskValue |= !Lane2Cond << i;
10138 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10139 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10140 const X86Subtarget *Subtarget,
10141 SelectionDAG &DAG) {
10142 SDValue Cond = Op.getOperand(0);
10143 SDValue LHS = Op.getOperand(1);
10144 SDValue RHS = Op.getOperand(2);
10146 MVT VT = Op.getSimpleValueType();
10148 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10150 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10152 // Only non-legal VSELECTs reach this lowering, convert those into generic
10153 // shuffles and re-use the shuffle lowering path for blends.
10154 SmallVector<int, 32> Mask;
10155 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10156 SDValue CondElt = CondBV->getOperand(i);
10158 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10160 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10163 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10164 // A vselect where all conditions and data are constants can be optimized into
10165 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10166 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10167 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10168 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10171 // Try to lower this to a blend-style vector shuffle. This can handle all
10172 // constant condition cases.
10173 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10176 // Variable blends are only legal from SSE4.1 onward.
10177 if (!Subtarget->hasSSE41())
10180 // Only some types will be legal on some subtargets. If we can emit a legal
10181 // VSELECT-matching blend, return Op, and but if we need to expand, return
10183 switch (Op.getSimpleValueType().SimpleTy) {
10185 // Most of the vector types have blends past SSE4.1.
10189 // The byte blends for AVX vectors were introduced only in AVX2.
10190 if (Subtarget->hasAVX2())
10197 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10198 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10201 // FIXME: We should custom lower this by fixing the condition and using i8
10207 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10208 MVT VT = Op.getSimpleValueType();
10211 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10214 if (VT.getSizeInBits() == 8) {
10215 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10216 Op.getOperand(0), Op.getOperand(1));
10217 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10218 DAG.getValueType(VT));
10219 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10222 if (VT.getSizeInBits() == 16) {
10223 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10224 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10226 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10227 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10228 DAG.getNode(ISD::BITCAST, dl,
10231 Op.getOperand(1)));
10232 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10233 Op.getOperand(0), Op.getOperand(1));
10234 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10235 DAG.getValueType(VT));
10236 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10239 if (VT == MVT::f32) {
10240 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10241 // the result back to FR32 register. It's only worth matching if the
10242 // result has a single use which is a store or a bitcast to i32. And in
10243 // the case of a store, it's not worth it if the index is a constant 0,
10244 // because a MOVSSmr can be used instead, which is smaller and faster.
10245 if (!Op.hasOneUse())
10247 SDNode *User = *Op.getNode()->use_begin();
10248 if ((User->getOpcode() != ISD::STORE ||
10249 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10250 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10251 (User->getOpcode() != ISD::BITCAST ||
10252 User->getValueType(0) != MVT::i32))
10254 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10255 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10258 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10261 if (VT == MVT::i32 || VT == MVT::i64) {
10262 // ExtractPS/pextrq works with constant index.
10263 if (isa<ConstantSDNode>(Op.getOperand(1)))
10269 /// Extract one bit from mask vector, like v16i1 or v8i1.
10270 /// AVX-512 feature.
10272 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10273 SDValue Vec = Op.getOperand(0);
10275 MVT VecVT = Vec.getSimpleValueType();
10276 SDValue Idx = Op.getOperand(1);
10277 MVT EltVT = Op.getSimpleValueType();
10279 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10280 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10281 "Unexpected vector type in ExtractBitFromMaskVector");
10283 // variable index can't be handled in mask registers,
10284 // extend vector to VR512
10285 if (!isa<ConstantSDNode>(Idx)) {
10286 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10287 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10288 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10289 ExtVT.getVectorElementType(), Ext, Idx);
10290 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10293 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10294 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10295 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10296 rc = getRegClassFor(MVT::v16i1);
10297 unsigned MaxSift = rc->getSize()*8 - 1;
10298 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10299 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10300 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10301 DAG.getConstant(MaxSift, MVT::i8));
10302 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10303 DAG.getIntPtrConstant(0));
10307 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10308 SelectionDAG &DAG) const {
10310 SDValue Vec = Op.getOperand(0);
10311 MVT VecVT = Vec.getSimpleValueType();
10312 SDValue Idx = Op.getOperand(1);
10314 if (Op.getSimpleValueType() == MVT::i1)
10315 return ExtractBitFromMaskVector(Op, DAG);
10317 if (!isa<ConstantSDNode>(Idx)) {
10318 if (VecVT.is512BitVector() ||
10319 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10320 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10323 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10324 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10325 MaskEltVT.getSizeInBits());
10327 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10328 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10329 getZeroVector(MaskVT, Subtarget, DAG, dl),
10330 Idx, DAG.getConstant(0, getPointerTy()));
10331 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10332 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10333 Perm, DAG.getConstant(0, getPointerTy()));
10338 // If this is a 256-bit vector result, first extract the 128-bit vector and
10339 // then extract the element from the 128-bit vector.
10340 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10342 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10343 // Get the 128-bit vector.
10344 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10345 MVT EltVT = VecVT.getVectorElementType();
10347 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10349 //if (IdxVal >= NumElems/2)
10350 // IdxVal -= NumElems/2;
10351 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10353 DAG.getConstant(IdxVal, MVT::i32));
10356 assert(VecVT.is128BitVector() && "Unexpected vector length");
10358 if (Subtarget->hasSSE41()) {
10359 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10364 MVT VT = Op.getSimpleValueType();
10365 // TODO: handle v16i8.
10366 if (VT.getSizeInBits() == 16) {
10367 SDValue Vec = Op.getOperand(0);
10368 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10370 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10371 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10372 DAG.getNode(ISD::BITCAST, dl,
10374 Op.getOperand(1)));
10375 // Transform it so it match pextrw which produces a 32-bit result.
10376 MVT EltVT = MVT::i32;
10377 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10378 Op.getOperand(0), Op.getOperand(1));
10379 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10380 DAG.getValueType(VT));
10381 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10384 if (VT.getSizeInBits() == 32) {
10385 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10389 // SHUFPS the element to the lowest double word, then movss.
10390 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10391 MVT VVT = Op.getOperand(0).getSimpleValueType();
10392 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10393 DAG.getUNDEF(VVT), Mask);
10394 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10395 DAG.getIntPtrConstant(0));
10398 if (VT.getSizeInBits() == 64) {
10399 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10400 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10401 // to match extract_elt for f64.
10402 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10406 // UNPCKHPD the element to the lowest double word, then movsd.
10407 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10408 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10409 int Mask[2] = { 1, -1 };
10410 MVT VVT = Op.getOperand(0).getSimpleValueType();
10411 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10412 DAG.getUNDEF(VVT), Mask);
10413 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10414 DAG.getIntPtrConstant(0));
10420 /// Insert one bit to mask vector, like v16i1 or v8i1.
10421 /// AVX-512 feature.
10423 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10425 SDValue Vec = Op.getOperand(0);
10426 SDValue Elt = Op.getOperand(1);
10427 SDValue Idx = Op.getOperand(2);
10428 MVT VecVT = Vec.getSimpleValueType();
10430 if (!isa<ConstantSDNode>(Idx)) {
10431 // Non constant index. Extend source and destination,
10432 // insert element and then truncate the result.
10433 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10434 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10435 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10436 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10437 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10438 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10441 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10442 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10443 if (Vec.getOpcode() == ISD::UNDEF)
10444 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10445 DAG.getConstant(IdxVal, MVT::i8));
10446 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10447 unsigned MaxSift = rc->getSize()*8 - 1;
10448 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10449 DAG.getConstant(MaxSift, MVT::i8));
10450 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10451 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10452 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10455 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10456 SelectionDAG &DAG) const {
10457 MVT VT = Op.getSimpleValueType();
10458 MVT EltVT = VT.getVectorElementType();
10460 if (EltVT == MVT::i1)
10461 return InsertBitToMaskVector(Op, DAG);
10464 SDValue N0 = Op.getOperand(0);
10465 SDValue N1 = Op.getOperand(1);
10466 SDValue N2 = Op.getOperand(2);
10467 if (!isa<ConstantSDNode>(N2))
10469 auto *N2C = cast<ConstantSDNode>(N2);
10470 unsigned IdxVal = N2C->getZExtValue();
10472 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10473 // into that, and then insert the subvector back into the result.
10474 if (VT.is256BitVector() || VT.is512BitVector()) {
10475 // Get the desired 128-bit vector half.
10476 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10478 // Insert the element into the desired half.
10479 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10480 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10482 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10483 DAG.getConstant(IdxIn128, MVT::i32));
10485 // Insert the changed part back to the 256-bit vector
10486 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10488 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10490 if (Subtarget->hasSSE41()) {
10491 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10493 if (VT == MVT::v8i16) {
10494 Opc = X86ISD::PINSRW;
10496 assert(VT == MVT::v16i8);
10497 Opc = X86ISD::PINSRB;
10500 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10502 if (N1.getValueType() != MVT::i32)
10503 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10504 if (N2.getValueType() != MVT::i32)
10505 N2 = DAG.getIntPtrConstant(IdxVal);
10506 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10509 if (EltVT == MVT::f32) {
10510 // Bits [7:6] of the constant are the source select. This will always be
10511 // zero here. The DAG Combiner may combine an extract_elt index into
10513 // bits. For example (insert (extract, 3), 2) could be matched by
10515 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10516 // Bits [5:4] of the constant are the destination select. This is the
10517 // value of the incoming immediate.
10518 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10519 // combine either bitwise AND or insert of float 0.0 to set these bits.
10520 N2 = DAG.getIntPtrConstant(IdxVal << 4);
10521 // Create this as a scalar to vector..
10522 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10523 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10526 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10527 // PINSR* works with constant index.
10532 if (EltVT == MVT::i8)
10535 if (EltVT.getSizeInBits() == 16) {
10536 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10537 // as its second argument.
10538 if (N1.getValueType() != MVT::i32)
10539 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10540 if (N2.getValueType() != MVT::i32)
10541 N2 = DAG.getIntPtrConstant(IdxVal);
10542 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10547 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10549 MVT OpVT = Op.getSimpleValueType();
10551 // If this is a 256-bit vector result, first insert into a 128-bit
10552 // vector and then insert into the 256-bit vector.
10553 if (!OpVT.is128BitVector()) {
10554 // Insert into a 128-bit vector.
10555 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10556 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10557 OpVT.getVectorNumElements() / SizeFactor);
10559 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10561 // Insert the 128-bit vector.
10562 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10565 if (OpVT == MVT::v1i64 &&
10566 Op.getOperand(0).getValueType() == MVT::i64)
10567 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10569 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10570 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10571 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10572 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10575 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10576 // a simple subregister reference or explicit instructions to grab
10577 // upper bits of a vector.
10578 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10579 SelectionDAG &DAG) {
10581 SDValue In = Op.getOperand(0);
10582 SDValue Idx = Op.getOperand(1);
10583 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10584 MVT ResVT = Op.getSimpleValueType();
10585 MVT InVT = In.getSimpleValueType();
10587 if (Subtarget->hasFp256()) {
10588 if (ResVT.is128BitVector() &&
10589 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10590 isa<ConstantSDNode>(Idx)) {
10591 return Extract128BitVector(In, IdxVal, DAG, dl);
10593 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10594 isa<ConstantSDNode>(Idx)) {
10595 return Extract256BitVector(In, IdxVal, DAG, dl);
10601 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10602 // simple superregister reference or explicit instructions to insert
10603 // the upper bits of a vector.
10604 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10605 SelectionDAG &DAG) {
10606 if (!Subtarget->hasAVX())
10610 SDValue Vec = Op.getOperand(0);
10611 SDValue SubVec = Op.getOperand(1);
10612 SDValue Idx = Op.getOperand(2);
10614 if (!isa<ConstantSDNode>(Idx))
10617 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10618 MVT OpVT = Op.getSimpleValueType();
10619 MVT SubVecVT = SubVec.getSimpleValueType();
10621 // Fold two 16-byte subvector loads into one 32-byte load:
10622 // (insert_subvector (insert_subvector undef, (load addr), 0),
10623 // (load addr + 16), Elts/2)
10625 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10626 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10627 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10628 !Subtarget->isUnalignedMem32Slow()) {
10629 SDValue SubVec2 = Vec.getOperand(1);
10630 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10631 if (Idx2->getZExtValue() == 0) {
10632 SDValue Ops[] = { SubVec2, SubVec };
10633 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10640 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10641 SubVecVT.is128BitVector())
10642 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10644 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10645 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10647 if (OpVT.getVectorElementType() == MVT::i1) {
10648 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10650 SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10651 SDValue Undef = DAG.getUNDEF(OpVT);
10652 unsigned NumElems = OpVT.getVectorNumElements();
10653 SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10655 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10656 // Zero upper bits of the Vec
10657 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10658 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10660 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10662 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10663 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10666 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10668 // Zero upper bits of the Vec2
10669 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10670 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10671 // Zero lower bits of the Vec
10672 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10673 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10674 // Merge them together
10675 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10681 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10682 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10683 // one of the above mentioned nodes. It has to be wrapped because otherwise
10684 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10685 // be used to form addressing mode. These wrapped nodes will be selected
10688 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10689 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10691 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10692 // global base reg.
10693 unsigned char OpFlag = 0;
10694 unsigned WrapperKind = X86ISD::Wrapper;
10695 CodeModel::Model M = DAG.getTarget().getCodeModel();
10697 if (Subtarget->isPICStyleRIPRel() &&
10698 (M == CodeModel::Small || M == CodeModel::Kernel))
10699 WrapperKind = X86ISD::WrapperRIP;
10700 else if (Subtarget->isPICStyleGOT())
10701 OpFlag = X86II::MO_GOTOFF;
10702 else if (Subtarget->isPICStyleStubPIC())
10703 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10705 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10706 CP->getAlignment(),
10707 CP->getOffset(), OpFlag);
10709 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10710 // With PIC, the address is actually $g + Offset.
10712 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10713 DAG.getNode(X86ISD::GlobalBaseReg,
10714 SDLoc(), getPointerTy()),
10721 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10722 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10724 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10725 // global base reg.
10726 unsigned char OpFlag = 0;
10727 unsigned WrapperKind = X86ISD::Wrapper;
10728 CodeModel::Model M = DAG.getTarget().getCodeModel();
10730 if (Subtarget->isPICStyleRIPRel() &&
10731 (M == CodeModel::Small || M == CodeModel::Kernel))
10732 WrapperKind = X86ISD::WrapperRIP;
10733 else if (Subtarget->isPICStyleGOT())
10734 OpFlag = X86II::MO_GOTOFF;
10735 else if (Subtarget->isPICStyleStubPIC())
10736 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10738 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10741 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10743 // With PIC, the address is actually $g + Offset.
10745 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10746 DAG.getNode(X86ISD::GlobalBaseReg,
10747 SDLoc(), getPointerTy()),
10754 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10755 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10757 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10758 // global base reg.
10759 unsigned char OpFlag = 0;
10760 unsigned WrapperKind = X86ISD::Wrapper;
10761 CodeModel::Model M = DAG.getTarget().getCodeModel();
10763 if (Subtarget->isPICStyleRIPRel() &&
10764 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10765 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10766 OpFlag = X86II::MO_GOTPCREL;
10767 WrapperKind = X86ISD::WrapperRIP;
10768 } else if (Subtarget->isPICStyleGOT()) {
10769 OpFlag = X86II::MO_GOT;
10770 } else if (Subtarget->isPICStyleStubPIC()) {
10771 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10772 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10773 OpFlag = X86II::MO_DARWIN_NONLAZY;
10776 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10779 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10781 // With PIC, the address is actually $g + Offset.
10782 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10783 !Subtarget->is64Bit()) {
10784 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10785 DAG.getNode(X86ISD::GlobalBaseReg,
10786 SDLoc(), getPointerTy()),
10790 // For symbols that require a load from a stub to get the address, emit the
10792 if (isGlobalStubReference(OpFlag))
10793 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10794 MachinePointerInfo::getGOT(), false, false, false, 0);
10800 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10801 // Create the TargetBlockAddressAddress node.
10802 unsigned char OpFlags =
10803 Subtarget->ClassifyBlockAddressReference();
10804 CodeModel::Model M = DAG.getTarget().getCodeModel();
10805 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10806 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10808 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10811 if (Subtarget->isPICStyleRIPRel() &&
10812 (M == CodeModel::Small || M == CodeModel::Kernel))
10813 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10815 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10817 // With PIC, the address is actually $g + Offset.
10818 if (isGlobalRelativeToPICBase(OpFlags)) {
10819 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10820 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10828 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10829 int64_t Offset, SelectionDAG &DAG) const {
10830 // Create the TargetGlobalAddress node, folding in the constant
10831 // offset if it is legal.
10832 unsigned char OpFlags =
10833 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10834 CodeModel::Model M = DAG.getTarget().getCodeModel();
10836 if (OpFlags == X86II::MO_NO_FLAG &&
10837 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10838 // A direct static reference to a global.
10839 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10842 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10845 if (Subtarget->isPICStyleRIPRel() &&
10846 (M == CodeModel::Small || M == CodeModel::Kernel))
10847 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10849 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10851 // With PIC, the address is actually $g + Offset.
10852 if (isGlobalRelativeToPICBase(OpFlags)) {
10853 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10854 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10858 // For globals that require a load from a stub to get the address, emit the
10860 if (isGlobalStubReference(OpFlags))
10861 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10862 MachinePointerInfo::getGOT(), false, false, false, 0);
10864 // If there was a non-zero offset that we didn't fold, create an explicit
10865 // addition for it.
10867 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10868 DAG.getConstant(Offset, getPointerTy()));
10874 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10875 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10876 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10877 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10881 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10882 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10883 unsigned char OperandFlags, bool LocalDynamic = false) {
10884 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10885 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10887 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10888 GA->getValueType(0),
10892 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10896 SDValue Ops[] = { Chain, TGA, *InFlag };
10897 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10899 SDValue Ops[] = { Chain, TGA };
10900 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10903 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10904 MFI->setAdjustsStack(true);
10905 MFI->setHasCalls(true);
10907 SDValue Flag = Chain.getValue(1);
10908 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10911 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10913 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10916 SDLoc dl(GA); // ? function entry point might be better
10917 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10918 DAG.getNode(X86ISD::GlobalBaseReg,
10919 SDLoc(), PtrVT), InFlag);
10920 InFlag = Chain.getValue(1);
10922 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10925 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10927 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10929 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10930 X86::RAX, X86II::MO_TLSGD);
10933 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10939 // Get the start address of the TLS block for this module.
10940 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10941 .getInfo<X86MachineFunctionInfo>();
10942 MFI->incNumLocalDynamicTLSAccesses();
10946 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10947 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10950 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10951 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10952 InFlag = Chain.getValue(1);
10953 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10954 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10957 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10961 unsigned char OperandFlags = X86II::MO_DTPOFF;
10962 unsigned WrapperKind = X86ISD::Wrapper;
10963 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10964 GA->getValueType(0),
10965 GA->getOffset(), OperandFlags);
10966 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10968 // Add x@dtpoff with the base.
10969 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10972 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10973 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10974 const EVT PtrVT, TLSModel::Model model,
10975 bool is64Bit, bool isPIC) {
10978 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10979 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10980 is64Bit ? 257 : 256));
10982 SDValue ThreadPointer =
10983 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10984 MachinePointerInfo(Ptr), false, false, false, 0);
10986 unsigned char OperandFlags = 0;
10987 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10989 unsigned WrapperKind = X86ISD::Wrapper;
10990 if (model == TLSModel::LocalExec) {
10991 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10992 } else if (model == TLSModel::InitialExec) {
10994 OperandFlags = X86II::MO_GOTTPOFF;
10995 WrapperKind = X86ISD::WrapperRIP;
10997 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11000 llvm_unreachable("Unexpected model");
11003 // emit "addl x@ntpoff,%eax" (local exec)
11004 // or "addl x@indntpoff,%eax" (initial exec)
11005 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11007 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11008 GA->getOffset(), OperandFlags);
11009 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11011 if (model == TLSModel::InitialExec) {
11012 if (isPIC && !is64Bit) {
11013 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11014 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11018 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11019 MachinePointerInfo::getGOT(), false, false, false, 0);
11022 // The address of the thread local variable is the add of the thread
11023 // pointer with the offset of the variable.
11024 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11028 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11030 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11031 const GlobalValue *GV = GA->getGlobal();
11033 if (Subtarget->isTargetELF()) {
11034 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11037 case TLSModel::GeneralDynamic:
11038 if (Subtarget->is64Bit())
11039 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11040 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11041 case TLSModel::LocalDynamic:
11042 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11043 Subtarget->is64Bit());
11044 case TLSModel::InitialExec:
11045 case TLSModel::LocalExec:
11046 return LowerToTLSExecModel(
11047 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11048 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11050 llvm_unreachable("Unknown TLS model.");
11053 if (Subtarget->isTargetDarwin()) {
11054 // Darwin only has one model of TLS. Lower to that.
11055 unsigned char OpFlag = 0;
11056 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11057 X86ISD::WrapperRIP : X86ISD::Wrapper;
11059 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11060 // global base reg.
11061 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11062 !Subtarget->is64Bit();
11064 OpFlag = X86II::MO_TLVP_PIC_BASE;
11066 OpFlag = X86II::MO_TLVP;
11068 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11069 GA->getValueType(0),
11070 GA->getOffset(), OpFlag);
11071 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11073 // With PIC32, the address is actually $g + Offset.
11075 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11076 DAG.getNode(X86ISD::GlobalBaseReg,
11077 SDLoc(), getPointerTy()),
11080 // Lowering the machine isd will make sure everything is in the right
11082 SDValue Chain = DAG.getEntryNode();
11083 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11084 SDValue Args[] = { Chain, Offset };
11085 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11087 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11088 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11089 MFI->setAdjustsStack(true);
11091 // And our return value (tls address) is in the standard call return value
11093 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11094 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11095 Chain.getValue(1));
11098 if (Subtarget->isTargetKnownWindowsMSVC() ||
11099 Subtarget->isTargetWindowsGNU()) {
11100 // Just use the implicit TLS architecture
11101 // Need to generate someting similar to:
11102 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11104 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11105 // mov rcx, qword [rdx+rcx*8]
11106 // mov eax, .tls$:tlsvar
11107 // [rax+rcx] contains the address
11108 // Windows 64bit: gs:0x58
11109 // Windows 32bit: fs:__tls_array
11112 SDValue Chain = DAG.getEntryNode();
11114 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11115 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11116 // use its literal value of 0x2C.
11117 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11118 ? Type::getInt8PtrTy(*DAG.getContext(),
11120 : Type::getInt32PtrTy(*DAG.getContext(),
11124 Subtarget->is64Bit()
11125 ? DAG.getIntPtrConstant(0x58)
11126 : (Subtarget->isTargetWindowsGNU()
11127 ? DAG.getIntPtrConstant(0x2C)
11128 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11130 SDValue ThreadPointer =
11131 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11132 MachinePointerInfo(Ptr), false, false, false, 0);
11134 // Load the _tls_index variable
11135 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11136 if (Subtarget->is64Bit())
11137 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11138 IDX, MachinePointerInfo(), MVT::i32,
11139 false, false, false, 0);
11141 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11142 false, false, false, 0);
11144 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11146 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11148 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11149 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11150 false, false, false, 0);
11152 // Get the offset of start of .tls section
11153 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11154 GA->getValueType(0),
11155 GA->getOffset(), X86II::MO_SECREL);
11156 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11158 // The address of the thread local variable is the add of the thread
11159 // pointer with the offset of the variable.
11160 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11163 llvm_unreachable("TLS not implemented for this target.");
11166 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11167 /// and take a 2 x i32 value to shift plus a shift amount.
11168 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11169 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11170 MVT VT = Op.getSimpleValueType();
11171 unsigned VTBits = VT.getSizeInBits();
11173 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11174 SDValue ShOpLo = Op.getOperand(0);
11175 SDValue ShOpHi = Op.getOperand(1);
11176 SDValue ShAmt = Op.getOperand(2);
11177 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11178 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11180 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11181 DAG.getConstant(VTBits - 1, MVT::i8));
11182 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11183 DAG.getConstant(VTBits - 1, MVT::i8))
11184 : DAG.getConstant(0, VT);
11186 SDValue Tmp2, Tmp3;
11187 if (Op.getOpcode() == ISD::SHL_PARTS) {
11188 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11189 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11191 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11192 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11195 // If the shift amount is larger or equal than the width of a part we can't
11196 // rely on the results of shld/shrd. Insert a test and select the appropriate
11197 // values for large shift amounts.
11198 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11199 DAG.getConstant(VTBits, MVT::i8));
11200 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11201 AndNode, DAG.getConstant(0, MVT::i8));
11204 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11205 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11206 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11208 if (Op.getOpcode() == ISD::SHL_PARTS) {
11209 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11210 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11212 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11213 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11216 SDValue Ops[2] = { Lo, Hi };
11217 return DAG.getMergeValues(Ops, dl);
11220 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11221 SelectionDAG &DAG) const {
11222 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11225 if (SrcVT.isVector()) {
11226 if (SrcVT.getVectorElementType() == MVT::i1) {
11227 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11228 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11229 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11230 Op.getOperand(0)));
11235 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11236 "Unknown SINT_TO_FP to lower!");
11238 // These are really Legal; return the operand so the caller accepts it as
11240 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11242 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11243 Subtarget->is64Bit()) {
11247 unsigned Size = SrcVT.getSizeInBits()/8;
11248 MachineFunction &MF = DAG.getMachineFunction();
11249 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11250 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11251 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11253 MachinePointerInfo::getFixedStack(SSFI),
11255 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11258 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11260 SelectionDAG &DAG) const {
11264 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11266 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11268 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11270 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11272 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11273 MachineMemOperand *MMO;
11275 int SSFI = FI->getIndex();
11277 DAG.getMachineFunction()
11278 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11279 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11281 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11282 StackSlot = StackSlot.getOperand(1);
11284 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11285 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11287 Tys, Ops, SrcVT, MMO);
11290 Chain = Result.getValue(1);
11291 SDValue InFlag = Result.getValue(2);
11293 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11294 // shouldn't be necessary except that RFP cannot be live across
11295 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11296 MachineFunction &MF = DAG.getMachineFunction();
11297 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11298 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11299 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11300 Tys = DAG.getVTList(MVT::Other);
11302 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11304 MachineMemOperand *MMO =
11305 DAG.getMachineFunction()
11306 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11307 MachineMemOperand::MOStore, SSFISize, SSFISize);
11309 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11310 Ops, Op.getValueType(), MMO);
11311 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11312 MachinePointerInfo::getFixedStack(SSFI),
11313 false, false, false, 0);
11319 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11320 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11321 SelectionDAG &DAG) const {
11322 // This algorithm is not obvious. Here it is what we're trying to output:
11325 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11326 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11328 haddpd %xmm0, %xmm0
11330 pshufd $0x4e, %xmm0, %xmm1
11336 LLVMContext *Context = DAG.getContext();
11338 // Build some magic constants.
11339 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11340 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11341 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11343 SmallVector<Constant*,2> CV1;
11345 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11346 APInt(64, 0x4330000000000000ULL))));
11348 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11349 APInt(64, 0x4530000000000000ULL))));
11350 Constant *C1 = ConstantVector::get(CV1);
11351 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11353 // Load the 64-bit value into an XMM register.
11354 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11356 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11357 MachinePointerInfo::getConstantPool(),
11358 false, false, false, 16);
11359 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11360 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11363 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11364 MachinePointerInfo::getConstantPool(),
11365 false, false, false, 16);
11366 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11367 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11370 if (Subtarget->hasSSE3()) {
11371 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11372 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11374 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11375 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11377 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11378 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11382 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11383 DAG.getIntPtrConstant(0));
11386 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11387 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11388 SelectionDAG &DAG) const {
11390 // FP constant to bias correct the final result.
11391 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11394 // Load the 32-bit value into an XMM register.
11395 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11398 // Zero out the upper parts of the register.
11399 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11401 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11402 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11403 DAG.getIntPtrConstant(0));
11405 // Or the load with the bias.
11406 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11407 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11408 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11409 MVT::v2f64, Load)),
11410 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11411 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11412 MVT::v2f64, Bias)));
11413 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11414 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11415 DAG.getIntPtrConstant(0));
11417 // Subtract the bias.
11418 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11420 // Handle final rounding.
11421 EVT DestVT = Op.getValueType();
11423 if (DestVT.bitsLT(MVT::f64))
11424 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11425 DAG.getIntPtrConstant(0));
11426 if (DestVT.bitsGT(MVT::f64))
11427 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11429 // Handle final rounding.
11433 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11434 const X86Subtarget &Subtarget) {
11435 // The algorithm is the following:
11436 // #ifdef __SSE4_1__
11437 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11438 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11439 // (uint4) 0x53000000, 0xaa);
11441 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11442 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11444 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11445 // return (float4) lo + fhi;
11448 SDValue V = Op->getOperand(0);
11449 EVT VecIntVT = V.getValueType();
11450 bool Is128 = VecIntVT == MVT::v4i32;
11451 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11452 // If we convert to something else than the supported type, e.g., to v4f64,
11454 if (VecFloatVT != Op->getValueType(0))
11457 unsigned NumElts = VecIntVT.getVectorNumElements();
11458 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11459 "Unsupported custom type");
11460 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11462 // In the #idef/#else code, we have in common:
11463 // - The vector of constants:
11469 // Create the splat vector for 0x4b000000.
11470 SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11471 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11472 CstLow, CstLow, CstLow, CstLow};
11473 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11474 makeArrayRef(&CstLowArray[0], NumElts));
11475 // Create the splat vector for 0x53000000.
11476 SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11477 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11478 CstHigh, CstHigh, CstHigh, CstHigh};
11479 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11480 makeArrayRef(&CstHighArray[0], NumElts));
11482 // Create the right shift.
11483 SDValue CstShift = DAG.getConstant(16, MVT::i32);
11484 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11485 CstShift, CstShift, CstShift, CstShift};
11486 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11487 makeArrayRef(&CstShiftArray[0], NumElts));
11488 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11491 if (Subtarget.hasSSE41()) {
11492 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11493 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11494 SDValue VecCstLowBitcast =
11495 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11496 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11497 // Low will be bitcasted right away, so do not bother bitcasting back to its
11499 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11500 VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11501 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11502 // (uint4) 0x53000000, 0xaa);
11503 SDValue VecCstHighBitcast =
11504 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11505 SDValue VecShiftBitcast =
11506 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11507 // High will be bitcasted right away, so do not bother bitcasting back to
11508 // its original type.
11509 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11510 VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11512 SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11513 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11514 CstMask, CstMask, CstMask);
11515 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11516 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11517 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11519 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11520 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11523 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11524 SDValue CstFAdd = DAG.getConstantFP(
11525 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11526 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11527 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11528 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11529 makeArrayRef(&CstFAddArray[0], NumElts));
11531 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11532 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11534 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11535 // return (float4) lo + fhi;
11536 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11537 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11540 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11541 SelectionDAG &DAG) const {
11542 SDValue N0 = Op.getOperand(0);
11543 MVT SVT = N0.getSimpleValueType();
11546 switch (SVT.SimpleTy) {
11548 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11553 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11554 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11555 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11559 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11561 llvm_unreachable(nullptr);
11564 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11565 SelectionDAG &DAG) const {
11566 SDValue N0 = Op.getOperand(0);
11569 if (Op.getValueType().isVector())
11570 return lowerUINT_TO_FP_vec(Op, DAG);
11572 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11573 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11574 // the optimization here.
11575 if (DAG.SignBitIsZero(N0))
11576 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11578 MVT SrcVT = N0.getSimpleValueType();
11579 MVT DstVT = Op.getSimpleValueType();
11580 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11581 return LowerUINT_TO_FP_i64(Op, DAG);
11582 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11583 return LowerUINT_TO_FP_i32(Op, DAG);
11584 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11587 // Make a 64-bit buffer, and use it to build an FILD.
11588 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11589 if (SrcVT == MVT::i32) {
11590 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11591 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11592 getPointerTy(), StackSlot, WordOff);
11593 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11594 StackSlot, MachinePointerInfo(),
11596 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11597 OffsetSlot, MachinePointerInfo(),
11599 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11603 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11604 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11605 StackSlot, MachinePointerInfo(),
11607 // For i64 source, we need to add the appropriate power of 2 if the input
11608 // was negative. This is the same as the optimization in
11609 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11610 // we must be careful to do the computation in x87 extended precision, not
11611 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11612 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11613 MachineMemOperand *MMO =
11614 DAG.getMachineFunction()
11615 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11616 MachineMemOperand::MOLoad, 8, 8);
11618 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11619 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11620 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11623 APInt FF(32, 0x5F800000ULL);
11625 // Check whether the sign bit is set.
11626 SDValue SignSet = DAG.getSetCC(dl,
11627 getSetCCResultType(*DAG.getContext(), MVT::i64),
11628 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11631 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11632 SDValue FudgePtr = DAG.getConstantPool(
11633 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11636 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11637 SDValue Zero = DAG.getIntPtrConstant(0);
11638 SDValue Four = DAG.getIntPtrConstant(4);
11639 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11641 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11643 // Load the value out, extending it from f32 to f80.
11644 // FIXME: Avoid the extend by constructing the right constant pool?
11645 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11646 FudgePtr, MachinePointerInfo::getConstantPool(),
11647 MVT::f32, false, false, false, 4);
11648 // Extend everything to 80 bits to force it to be done on x87.
11649 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11650 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11653 std::pair<SDValue,SDValue>
11654 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11655 bool IsSigned, bool IsReplace) const {
11658 EVT DstTy = Op.getValueType();
11660 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11661 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11665 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11666 DstTy.getSimpleVT() >= MVT::i16 &&
11667 "Unknown FP_TO_INT to lower!");
11669 // These are really Legal.
11670 if (DstTy == MVT::i32 &&
11671 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11672 return std::make_pair(SDValue(), SDValue());
11673 if (Subtarget->is64Bit() &&
11674 DstTy == MVT::i64 &&
11675 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11676 return std::make_pair(SDValue(), SDValue());
11678 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11679 // stack slot, or into the FTOL runtime function.
11680 MachineFunction &MF = DAG.getMachineFunction();
11681 unsigned MemSize = DstTy.getSizeInBits()/8;
11682 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11683 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11686 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11687 Opc = X86ISD::WIN_FTOL;
11689 switch (DstTy.getSimpleVT().SimpleTy) {
11690 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11691 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11692 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11693 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11696 SDValue Chain = DAG.getEntryNode();
11697 SDValue Value = Op.getOperand(0);
11698 EVT TheVT = Op.getOperand(0).getValueType();
11699 // FIXME This causes a redundant load/store if the SSE-class value is already
11700 // in memory, such as if it is on the callstack.
11701 if (isScalarFPTypeInSSEReg(TheVT)) {
11702 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11703 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11704 MachinePointerInfo::getFixedStack(SSFI),
11706 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11708 Chain, StackSlot, DAG.getValueType(TheVT)
11711 MachineMemOperand *MMO =
11712 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11713 MachineMemOperand::MOLoad, MemSize, MemSize);
11714 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11715 Chain = Value.getValue(1);
11716 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11717 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11720 MachineMemOperand *MMO =
11721 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11722 MachineMemOperand::MOStore, MemSize, MemSize);
11724 if (Opc != X86ISD::WIN_FTOL) {
11725 // Build the FP_TO_INT*_IN_MEM
11726 SDValue Ops[] = { Chain, Value, StackSlot };
11727 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11729 return std::make_pair(FIST, StackSlot);
11731 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11732 DAG.getVTList(MVT::Other, MVT::Glue),
11734 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11735 MVT::i32, ftol.getValue(1));
11736 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11737 MVT::i32, eax.getValue(2));
11738 SDValue Ops[] = { eax, edx };
11739 SDValue pair = IsReplace
11740 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11741 : DAG.getMergeValues(Ops, DL);
11742 return std::make_pair(pair, SDValue());
11746 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11747 const X86Subtarget *Subtarget) {
11748 MVT VT = Op->getSimpleValueType(0);
11749 SDValue In = Op->getOperand(0);
11750 MVT InVT = In.getSimpleValueType();
11753 // Optimize vectors in AVX mode:
11756 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11757 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11758 // Concat upper and lower parts.
11761 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11762 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11763 // Concat upper and lower parts.
11766 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11767 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11768 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11771 if (Subtarget->hasInt256())
11772 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11774 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11775 SDValue Undef = DAG.getUNDEF(InVT);
11776 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11777 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11778 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11780 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11781 VT.getVectorNumElements()/2);
11783 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11784 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11786 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11789 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11790 SelectionDAG &DAG) {
11791 MVT VT = Op->getSimpleValueType(0);
11792 SDValue In = Op->getOperand(0);
11793 MVT InVT = In.getSimpleValueType();
11795 unsigned int NumElts = VT.getVectorNumElements();
11796 if (NumElts != 8 && NumElts != 16)
11799 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11800 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11802 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11803 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11804 // Now we have only mask extension
11805 assert(InVT.getVectorElementType() == MVT::i1);
11806 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11807 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11808 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11809 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11810 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11811 MachinePointerInfo::getConstantPool(),
11812 false, false, false, Alignment);
11814 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11815 if (VT.is512BitVector())
11817 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11820 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11821 SelectionDAG &DAG) {
11822 if (Subtarget->hasFp256()) {
11823 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11831 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11832 SelectionDAG &DAG) {
11834 MVT VT = Op.getSimpleValueType();
11835 SDValue In = Op.getOperand(0);
11836 MVT SVT = In.getSimpleValueType();
11838 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11839 return LowerZERO_EXTEND_AVX512(Op, DAG);
11841 if (Subtarget->hasFp256()) {
11842 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11847 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11848 VT.getVectorNumElements() != SVT.getVectorNumElements());
11852 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11854 MVT VT = Op.getSimpleValueType();
11855 SDValue In = Op.getOperand(0);
11856 MVT InVT = In.getSimpleValueType();
11858 if (VT == MVT::i1) {
11859 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11860 "Invalid scalar TRUNCATE operation");
11861 if (InVT.getSizeInBits() >= 32)
11863 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11864 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11866 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11867 "Invalid TRUNCATE operation");
11869 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11870 if (VT.getVectorElementType().getSizeInBits() >=8)
11871 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11873 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11874 unsigned NumElts = InVT.getVectorNumElements();
11875 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11876 if (InVT.getSizeInBits() < 512) {
11877 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11878 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11882 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11883 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11884 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11885 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11886 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11887 MachinePointerInfo::getConstantPool(),
11888 false, false, false, Alignment);
11889 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11890 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11891 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11894 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11895 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11896 if (Subtarget->hasInt256()) {
11897 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11898 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11899 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11901 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11902 DAG.getIntPtrConstant(0));
11905 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11906 DAG.getIntPtrConstant(0));
11907 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11908 DAG.getIntPtrConstant(2));
11909 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11910 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11911 static const int ShufMask[] = {0, 2, 4, 6};
11912 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11915 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11916 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11917 if (Subtarget->hasInt256()) {
11918 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11920 SmallVector<SDValue,32> pshufbMask;
11921 for (unsigned i = 0; i < 2; ++i) {
11922 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11923 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11924 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11925 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11926 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11927 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11928 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11929 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11930 for (unsigned j = 0; j < 8; ++j)
11931 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11933 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11934 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11935 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11937 static const int ShufMask[] = {0, 2, -1, -1};
11938 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11940 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11941 DAG.getIntPtrConstant(0));
11942 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11945 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11946 DAG.getIntPtrConstant(0));
11948 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11949 DAG.getIntPtrConstant(4));
11951 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11952 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11954 // The PSHUFB mask:
11955 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11956 -1, -1, -1, -1, -1, -1, -1, -1};
11958 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11959 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11960 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11962 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11963 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11965 // The MOVLHPS Mask:
11966 static const int ShufMask2[] = {0, 1, 4, 5};
11967 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11968 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11971 // Handle truncation of V256 to V128 using shuffles.
11972 if (!VT.is128BitVector() || !InVT.is256BitVector())
11975 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11977 unsigned NumElems = VT.getVectorNumElements();
11978 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11980 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11981 // Prepare truncation shuffle mask
11982 for (unsigned i = 0; i != NumElems; ++i)
11983 MaskVec[i] = i * 2;
11984 SDValue V = DAG.getVectorShuffle(NVT, DL,
11985 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11986 DAG.getUNDEF(NVT), &MaskVec[0]);
11987 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11988 DAG.getIntPtrConstant(0));
11991 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11992 SelectionDAG &DAG) const {
11993 assert(!Op.getSimpleValueType().isVector());
11995 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11996 /*IsSigned=*/ true, /*IsReplace=*/ false);
11997 SDValue FIST = Vals.first, StackSlot = Vals.second;
11998 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11999 if (!FIST.getNode()) return Op;
12001 if (StackSlot.getNode())
12002 // Load the result.
12003 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12004 FIST, StackSlot, MachinePointerInfo(),
12005 false, false, false, 0);
12007 // The node is the result.
12011 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12012 SelectionDAG &DAG) const {
12013 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12014 /*IsSigned=*/ false, /*IsReplace=*/ false);
12015 SDValue FIST = Vals.first, StackSlot = Vals.second;
12016 assert(FIST.getNode() && "Unexpected failure");
12018 if (StackSlot.getNode())
12019 // Load the result.
12020 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12021 FIST, StackSlot, MachinePointerInfo(),
12022 false, false, false, 0);
12024 // The node is the result.
12028 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12030 MVT VT = Op.getSimpleValueType();
12031 SDValue In = Op.getOperand(0);
12032 MVT SVT = In.getSimpleValueType();
12034 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12036 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12037 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12038 In, DAG.getUNDEF(SVT)));
12041 /// The only differences between FABS and FNEG are the mask and the logic op.
12042 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12043 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12044 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12045 "Wrong opcode for lowering FABS or FNEG.");
12047 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12049 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12050 // into an FNABS. We'll lower the FABS after that if it is still in use.
12052 for (SDNode *User : Op->uses())
12053 if (User->getOpcode() == ISD::FNEG)
12056 SDValue Op0 = Op.getOperand(0);
12057 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12060 MVT VT = Op.getSimpleValueType();
12061 // Assume scalar op for initialization; update for vector if needed.
12062 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12063 // generate a 16-byte vector constant and logic op even for the scalar case.
12064 // Using a 16-byte mask allows folding the load of the mask with
12065 // the logic op, so it can save (~4 bytes) on code size.
12067 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12068 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12069 // decide if we should generate a 16-byte constant mask when we only need 4 or
12070 // 8 bytes for the scalar case.
12071 if (VT.isVector()) {
12072 EltVT = VT.getVectorElementType();
12073 NumElts = VT.getVectorNumElements();
12076 unsigned EltBits = EltVT.getSizeInBits();
12077 LLVMContext *Context = DAG.getContext();
12078 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12080 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12081 Constant *C = ConstantInt::get(*Context, MaskElt);
12082 C = ConstantVector::getSplat(NumElts, C);
12083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12084 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12085 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12086 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12087 MachinePointerInfo::getConstantPool(),
12088 false, false, false, Alignment);
12090 if (VT.isVector()) {
12091 // For a vector, cast operands to a vector type, perform the logic op,
12092 // and cast the result back to the original value type.
12093 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12094 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12095 SDValue Operand = IsFNABS ?
12096 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12097 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12098 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12099 return DAG.getNode(ISD::BITCAST, dl, VT,
12100 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12103 // If not vector, then scalar.
12104 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12105 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12106 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12109 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12111 LLVMContext *Context = DAG.getContext();
12112 SDValue Op0 = Op.getOperand(0);
12113 SDValue Op1 = Op.getOperand(1);
12115 MVT VT = Op.getSimpleValueType();
12116 MVT SrcVT = Op1.getSimpleValueType();
12118 // If second operand is smaller, extend it first.
12119 if (SrcVT.bitsLT(VT)) {
12120 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12123 // And if it is bigger, shrink it first.
12124 if (SrcVT.bitsGT(VT)) {
12125 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12129 // At this point the operands and the result should have the same
12130 // type, and that won't be f80 since that is not custom lowered.
12132 const fltSemantics &Sem =
12133 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12134 const unsigned SizeInBits = VT.getSizeInBits();
12136 SmallVector<Constant *, 4> CV(
12137 VT == MVT::f64 ? 2 : 4,
12138 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12140 // First, clear all bits but the sign bit from the second operand (sign).
12141 CV[0] = ConstantFP::get(*Context,
12142 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12143 Constant *C = ConstantVector::get(CV);
12144 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12145 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12146 MachinePointerInfo::getConstantPool(),
12147 false, false, false, 16);
12148 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12150 // Next, clear the sign bit from the first operand (magnitude).
12151 // If it's a constant, we can clear it here.
12152 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12153 APFloat APF = Op0CN->getValueAPF();
12154 // If the magnitude is a positive zero, the sign bit alone is enough.
12155 if (APF.isPosZero())
12158 CV[0] = ConstantFP::get(*Context, APF);
12160 CV[0] = ConstantFP::get(
12162 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12164 C = ConstantVector::get(CV);
12165 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12166 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12167 MachinePointerInfo::getConstantPool(),
12168 false, false, false, 16);
12169 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12170 if (!isa<ConstantFPSDNode>(Op0))
12171 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12173 // OR the magnitude value with the sign bit.
12174 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12177 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12178 SDValue N0 = Op.getOperand(0);
12180 MVT VT = Op.getSimpleValueType();
12182 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12183 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12184 DAG.getConstant(1, VT));
12185 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12188 // Check whether an OR'd tree is PTEST-able.
12189 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12190 SelectionDAG &DAG) {
12191 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12193 if (!Subtarget->hasSSE41())
12196 if (!Op->hasOneUse())
12199 SDNode *N = Op.getNode();
12202 SmallVector<SDValue, 8> Opnds;
12203 DenseMap<SDValue, unsigned> VecInMap;
12204 SmallVector<SDValue, 8> VecIns;
12205 EVT VT = MVT::Other;
12207 // Recognize a special case where a vector is casted into wide integer to
12209 Opnds.push_back(N->getOperand(0));
12210 Opnds.push_back(N->getOperand(1));
12212 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12213 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12214 // BFS traverse all OR'd operands.
12215 if (I->getOpcode() == ISD::OR) {
12216 Opnds.push_back(I->getOperand(0));
12217 Opnds.push_back(I->getOperand(1));
12218 // Re-evaluate the number of nodes to be traversed.
12219 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12223 // Quit if a non-EXTRACT_VECTOR_ELT
12224 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12227 // Quit if without a constant index.
12228 SDValue Idx = I->getOperand(1);
12229 if (!isa<ConstantSDNode>(Idx))
12232 SDValue ExtractedFromVec = I->getOperand(0);
12233 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12234 if (M == VecInMap.end()) {
12235 VT = ExtractedFromVec.getValueType();
12236 // Quit if not 128/256-bit vector.
12237 if (!VT.is128BitVector() && !VT.is256BitVector())
12239 // Quit if not the same type.
12240 if (VecInMap.begin() != VecInMap.end() &&
12241 VT != VecInMap.begin()->first.getValueType())
12243 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12244 VecIns.push_back(ExtractedFromVec);
12246 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12249 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12250 "Not extracted from 128-/256-bit vector.");
12252 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12254 for (DenseMap<SDValue, unsigned>::const_iterator
12255 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12256 // Quit if not all elements are used.
12257 if (I->second != FullMask)
12261 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12263 // Cast all vectors into TestVT for PTEST.
12264 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12265 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12267 // If more than one full vectors are evaluated, OR them first before PTEST.
12268 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12269 // Each iteration will OR 2 nodes and append the result until there is only
12270 // 1 node left, i.e. the final OR'd value of all vectors.
12271 SDValue LHS = VecIns[Slot];
12272 SDValue RHS = VecIns[Slot + 1];
12273 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12276 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12277 VecIns.back(), VecIns.back());
12280 /// \brief return true if \c Op has a use that doesn't just read flags.
12281 static bool hasNonFlagsUse(SDValue Op) {
12282 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12284 SDNode *User = *UI;
12285 unsigned UOpNo = UI.getOperandNo();
12286 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12287 // Look pass truncate.
12288 UOpNo = User->use_begin().getOperandNo();
12289 User = *User->use_begin();
12292 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12293 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12299 /// Emit nodes that will be selected as "test Op0,Op0", or something
12301 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12302 SelectionDAG &DAG) const {
12303 if (Op.getValueType() == MVT::i1) {
12304 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12305 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12306 DAG.getConstant(0, MVT::i8));
12308 // CF and OF aren't always set the way we want. Determine which
12309 // of these we need.
12310 bool NeedCF = false;
12311 bool NeedOF = false;
12314 case X86::COND_A: case X86::COND_AE:
12315 case X86::COND_B: case X86::COND_BE:
12318 case X86::COND_G: case X86::COND_GE:
12319 case X86::COND_L: case X86::COND_LE:
12320 case X86::COND_O: case X86::COND_NO: {
12321 // Check if we really need to set the
12322 // Overflow flag. If NoSignedWrap is present
12323 // that is not actually needed.
12324 switch (Op->getOpcode()) {
12329 const BinaryWithFlagsSDNode *BinNode =
12330 cast<BinaryWithFlagsSDNode>(Op.getNode());
12331 if (BinNode->hasNoSignedWrap())
12341 // See if we can use the EFLAGS value from the operand instead of
12342 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12343 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12344 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12345 // Emit a CMP with 0, which is the TEST pattern.
12346 //if (Op.getValueType() == MVT::i1)
12347 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12348 // DAG.getConstant(0, MVT::i1));
12349 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12350 DAG.getConstant(0, Op.getValueType()));
12352 unsigned Opcode = 0;
12353 unsigned NumOperands = 0;
12355 // Truncate operations may prevent the merge of the SETCC instruction
12356 // and the arithmetic instruction before it. Attempt to truncate the operands
12357 // of the arithmetic instruction and use a reduced bit-width instruction.
12358 bool NeedTruncation = false;
12359 SDValue ArithOp = Op;
12360 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12361 SDValue Arith = Op->getOperand(0);
12362 // Both the trunc and the arithmetic op need to have one user each.
12363 if (Arith->hasOneUse())
12364 switch (Arith.getOpcode()) {
12371 NeedTruncation = true;
12377 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12378 // which may be the result of a CAST. We use the variable 'Op', which is the
12379 // non-casted variable when we check for possible users.
12380 switch (ArithOp.getOpcode()) {
12382 // Due to an isel shortcoming, be conservative if this add is likely to be
12383 // selected as part of a load-modify-store instruction. When the root node
12384 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12385 // uses of other nodes in the match, such as the ADD in this case. This
12386 // leads to the ADD being left around and reselected, with the result being
12387 // two adds in the output. Alas, even if none our users are stores, that
12388 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12389 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12390 // climbing the DAG back to the root, and it doesn't seem to be worth the
12392 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12393 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12394 if (UI->getOpcode() != ISD::CopyToReg &&
12395 UI->getOpcode() != ISD::SETCC &&
12396 UI->getOpcode() != ISD::STORE)
12399 if (ConstantSDNode *C =
12400 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12401 // An add of one will be selected as an INC.
12402 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12403 Opcode = X86ISD::INC;
12408 // An add of negative one (subtract of one) will be selected as a DEC.
12409 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12410 Opcode = X86ISD::DEC;
12416 // Otherwise use a regular EFLAGS-setting add.
12417 Opcode = X86ISD::ADD;
12422 // If we have a constant logical shift that's only used in a comparison
12423 // against zero turn it into an equivalent AND. This allows turning it into
12424 // a TEST instruction later.
12425 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12426 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12427 EVT VT = Op.getValueType();
12428 unsigned BitWidth = VT.getSizeInBits();
12429 unsigned ShAmt = Op->getConstantOperandVal(1);
12430 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12432 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12433 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12434 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12435 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12437 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12438 DAG.getConstant(Mask, VT));
12439 DAG.ReplaceAllUsesWith(Op, New);
12445 // If the primary and result isn't used, don't bother using X86ISD::AND,
12446 // because a TEST instruction will be better.
12447 if (!hasNonFlagsUse(Op))
12453 // Due to the ISEL shortcoming noted above, be conservative if this op is
12454 // likely to be selected as part of a load-modify-store instruction.
12455 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12456 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12457 if (UI->getOpcode() == ISD::STORE)
12460 // Otherwise use a regular EFLAGS-setting instruction.
12461 switch (ArithOp.getOpcode()) {
12462 default: llvm_unreachable("unexpected operator!");
12463 case ISD::SUB: Opcode = X86ISD::SUB; break;
12464 case ISD::XOR: Opcode = X86ISD::XOR; break;
12465 case ISD::AND: Opcode = X86ISD::AND; break;
12467 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12468 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12469 if (EFLAGS.getNode())
12472 Opcode = X86ISD::OR;
12486 return SDValue(Op.getNode(), 1);
12492 // If we found that truncation is beneficial, perform the truncation and
12494 if (NeedTruncation) {
12495 EVT VT = Op.getValueType();
12496 SDValue WideVal = Op->getOperand(0);
12497 EVT WideVT = WideVal.getValueType();
12498 unsigned ConvertedOp = 0;
12499 // Use a target machine opcode to prevent further DAGCombine
12500 // optimizations that may separate the arithmetic operations
12501 // from the setcc node.
12502 switch (WideVal.getOpcode()) {
12504 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12505 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12506 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12507 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12508 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12513 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12514 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12515 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12516 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12522 // Emit a CMP with 0, which is the TEST pattern.
12523 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12524 DAG.getConstant(0, Op.getValueType()));
12526 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12527 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12529 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12530 DAG.ReplaceAllUsesWith(Op, New);
12531 return SDValue(New.getNode(), 1);
12534 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12536 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12537 SDLoc dl, SelectionDAG &DAG) const {
12538 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12539 if (C->getAPIntValue() == 0)
12540 return EmitTest(Op0, X86CC, dl, DAG);
12542 if (Op0.getValueType() == MVT::i1)
12543 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12546 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12547 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12548 // Do the comparison at i32 if it's smaller, besides the Atom case.
12549 // This avoids subregister aliasing issues. Keep the smaller reference
12550 // if we're optimizing for size, however, as that'll allow better folding
12551 // of memory operations.
12552 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12553 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12554 Attribute::MinSize) &&
12555 !Subtarget->isAtom()) {
12556 unsigned ExtendOp =
12557 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12558 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12559 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12561 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12562 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12563 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12565 return SDValue(Sub.getNode(), 1);
12567 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12570 /// Convert a comparison if required by the subtarget.
12571 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12572 SelectionDAG &DAG) const {
12573 // If the subtarget does not support the FUCOMI instruction, floating-point
12574 // comparisons have to be converted.
12575 if (Subtarget->hasCMov() ||
12576 Cmp.getOpcode() != X86ISD::CMP ||
12577 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12578 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12581 // The instruction selector will select an FUCOM instruction instead of
12582 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12583 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12584 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12586 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12587 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12588 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12589 DAG.getConstant(8, MVT::i8));
12590 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12591 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12594 /// The minimum architected relative accuracy is 2^-12. We need one
12595 /// Newton-Raphson step to have a good float result (24 bits of precision).
12596 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12597 DAGCombinerInfo &DCI,
12598 unsigned &RefinementSteps,
12599 bool &UseOneConstNR) const {
12600 // FIXME: We should use instruction latency models to calculate the cost of
12601 // each potential sequence, but this is very hard to do reliably because
12602 // at least Intel's Core* chips have variable timing based on the number of
12603 // significant digits in the divisor and/or sqrt operand.
12604 if (!Subtarget->useSqrtEst())
12607 EVT VT = Op.getValueType();
12609 // SSE1 has rsqrtss and rsqrtps.
12610 // TODO: Add support for AVX512 (v16f32).
12611 // It is likely not profitable to do this for f64 because a double-precision
12612 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12613 // instructions: convert to single, rsqrtss, convert back to double, refine
12614 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12615 // along with FMA, this could be a throughput win.
12616 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12617 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12618 RefinementSteps = 1;
12619 UseOneConstNR = false;
12620 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12625 /// The minimum architected relative accuracy is 2^-12. We need one
12626 /// Newton-Raphson step to have a good float result (24 bits of precision).
12627 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12628 DAGCombinerInfo &DCI,
12629 unsigned &RefinementSteps) const {
12630 // FIXME: We should use instruction latency models to calculate the cost of
12631 // each potential sequence, but this is very hard to do reliably because
12632 // at least Intel's Core* chips have variable timing based on the number of
12633 // significant digits in the divisor.
12634 if (!Subtarget->useReciprocalEst())
12637 EVT VT = Op.getValueType();
12639 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12640 // TODO: Add support for AVX512 (v16f32).
12641 // It is likely not profitable to do this for f64 because a double-precision
12642 // reciprocal estimate with refinement on x86 prior to FMA requires
12643 // 15 instructions: convert to single, rcpss, convert back to double, refine
12644 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12645 // along with FMA, this could be a throughput win.
12646 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12647 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12648 RefinementSteps = ReciprocalEstimateRefinementSteps;
12649 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12654 static bool isAllOnes(SDValue V) {
12655 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12656 return C && C->isAllOnesValue();
12659 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12660 /// if it's possible.
12661 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12662 SDLoc dl, SelectionDAG &DAG) const {
12663 SDValue Op0 = And.getOperand(0);
12664 SDValue Op1 = And.getOperand(1);
12665 if (Op0.getOpcode() == ISD::TRUNCATE)
12666 Op0 = Op0.getOperand(0);
12667 if (Op1.getOpcode() == ISD::TRUNCATE)
12668 Op1 = Op1.getOperand(0);
12671 if (Op1.getOpcode() == ISD::SHL)
12672 std::swap(Op0, Op1);
12673 if (Op0.getOpcode() == ISD::SHL) {
12674 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12675 if (And00C->getZExtValue() == 1) {
12676 // If we looked past a truncate, check that it's only truncating away
12678 unsigned BitWidth = Op0.getValueSizeInBits();
12679 unsigned AndBitWidth = And.getValueSizeInBits();
12680 if (BitWidth > AndBitWidth) {
12682 DAG.computeKnownBits(Op0, Zeros, Ones);
12683 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12687 RHS = Op0.getOperand(1);
12689 } else if (Op1.getOpcode() == ISD::Constant) {
12690 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12691 uint64_t AndRHSVal = AndRHS->getZExtValue();
12692 SDValue AndLHS = Op0;
12694 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12695 LHS = AndLHS.getOperand(0);
12696 RHS = AndLHS.getOperand(1);
12699 // Use BT if the immediate can't be encoded in a TEST instruction.
12700 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12702 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12706 if (LHS.getNode()) {
12707 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12708 // instruction. Since the shift amount is in-range-or-undefined, we know
12709 // that doing a bittest on the i32 value is ok. We extend to i32 because
12710 // the encoding for the i16 version is larger than the i32 version.
12711 // Also promote i16 to i32 for performance / code size reason.
12712 if (LHS.getValueType() == MVT::i8 ||
12713 LHS.getValueType() == MVT::i16)
12714 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12716 // If the operand types disagree, extend the shift amount to match. Since
12717 // BT ignores high bits (like shifts) we can use anyextend.
12718 if (LHS.getValueType() != RHS.getValueType())
12719 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12721 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12722 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12723 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12724 DAG.getConstant(Cond, MVT::i8), BT);
12730 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12732 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12737 // SSE Condition code mapping:
12746 switch (SetCCOpcode) {
12747 default: llvm_unreachable("Unexpected SETCC condition");
12749 case ISD::SETEQ: SSECC = 0; break;
12751 case ISD::SETGT: Swap = true; // Fallthrough
12753 case ISD::SETOLT: SSECC = 1; break;
12755 case ISD::SETGE: Swap = true; // Fallthrough
12757 case ISD::SETOLE: SSECC = 2; break;
12758 case ISD::SETUO: SSECC = 3; break;
12760 case ISD::SETNE: SSECC = 4; break;
12761 case ISD::SETULE: Swap = true; // Fallthrough
12762 case ISD::SETUGE: SSECC = 5; break;
12763 case ISD::SETULT: Swap = true; // Fallthrough
12764 case ISD::SETUGT: SSECC = 6; break;
12765 case ISD::SETO: SSECC = 7; break;
12767 case ISD::SETONE: SSECC = 8; break;
12770 std::swap(Op0, Op1);
12775 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12776 // ones, and then concatenate the result back.
12777 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12778 MVT VT = Op.getSimpleValueType();
12780 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12781 "Unsupported value type for operation");
12783 unsigned NumElems = VT.getVectorNumElements();
12785 SDValue CC = Op.getOperand(2);
12787 // Extract the LHS vectors
12788 SDValue LHS = Op.getOperand(0);
12789 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12790 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12792 // Extract the RHS vectors
12793 SDValue RHS = Op.getOperand(1);
12794 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12795 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12797 // Issue the operation on the smaller types and concatenate the result back
12798 MVT EltVT = VT.getVectorElementType();
12799 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12800 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12801 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12802 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12805 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12806 const X86Subtarget *Subtarget) {
12807 SDValue Op0 = Op.getOperand(0);
12808 SDValue Op1 = Op.getOperand(1);
12809 SDValue CC = Op.getOperand(2);
12810 MVT VT = Op.getSimpleValueType();
12813 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12814 Op.getValueType().getScalarType() == MVT::i1 &&
12815 "Cannot set masked compare for this operation");
12817 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12819 bool Unsigned = false;
12822 switch (SetCCOpcode) {
12823 default: llvm_unreachable("Unexpected SETCC condition");
12824 case ISD::SETNE: SSECC = 4; break;
12825 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12826 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12827 case ISD::SETLT: Swap = true; //fall-through
12828 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12829 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12830 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12831 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12832 case ISD::SETULE: Unsigned = true; //fall-through
12833 case ISD::SETLE: SSECC = 2; break;
12837 std::swap(Op0, Op1);
12839 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12840 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12841 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12842 DAG.getConstant(SSECC, MVT::i8));
12845 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12846 /// operand \p Op1. If non-trivial (for example because it's not constant)
12847 /// return an empty value.
12848 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12850 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12854 MVT VT = Op1.getSimpleValueType();
12855 MVT EVT = VT.getVectorElementType();
12856 unsigned n = VT.getVectorNumElements();
12857 SmallVector<SDValue, 8> ULTOp1;
12859 for (unsigned i = 0; i < n; ++i) {
12860 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12861 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12864 // Avoid underflow.
12865 APInt Val = Elt->getAPIntValue();
12869 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12872 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12875 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12876 SelectionDAG &DAG) {
12877 SDValue Op0 = Op.getOperand(0);
12878 SDValue Op1 = Op.getOperand(1);
12879 SDValue CC = Op.getOperand(2);
12880 MVT VT = Op.getSimpleValueType();
12881 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12882 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12887 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12888 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12891 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12892 unsigned Opc = X86ISD::CMPP;
12893 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12894 assert(VT.getVectorNumElements() <= 16);
12895 Opc = X86ISD::CMPM;
12897 // In the two special cases we can't handle, emit two comparisons.
12900 unsigned CombineOpc;
12901 if (SetCCOpcode == ISD::SETUEQ) {
12902 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12904 assert(SetCCOpcode == ISD::SETONE);
12905 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12908 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12909 DAG.getConstant(CC0, MVT::i8));
12910 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12911 DAG.getConstant(CC1, MVT::i8));
12912 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12914 // Handle all other FP comparisons here.
12915 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12916 DAG.getConstant(SSECC, MVT::i8));
12919 // Break 256-bit integer vector compare into smaller ones.
12920 if (VT.is256BitVector() && !Subtarget->hasInt256())
12921 return Lower256IntVSETCC(Op, DAG);
12923 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12924 EVT OpVT = Op1.getValueType();
12925 if (Subtarget->hasAVX512()) {
12926 if (Op1.getValueType().is512BitVector() ||
12927 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
12928 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12929 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12931 // In AVX-512 architecture setcc returns mask with i1 elements,
12932 // But there is no compare instruction for i8 and i16 elements in KNL.
12933 // We are not talking about 512-bit operands in this case, these
12934 // types are illegal.
12936 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12937 OpVT.getVectorElementType().getSizeInBits() >= 8))
12938 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12939 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12942 // We are handling one of the integer comparisons here. Since SSE only has
12943 // GT and EQ comparisons for integer, swapping operands and multiple
12944 // operations may be required for some comparisons.
12946 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12947 bool Subus = false;
12949 switch (SetCCOpcode) {
12950 default: llvm_unreachable("Unexpected SETCC condition");
12951 case ISD::SETNE: Invert = true;
12952 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12953 case ISD::SETLT: Swap = true;
12954 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12955 case ISD::SETGE: Swap = true;
12956 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12957 Invert = true; break;
12958 case ISD::SETULT: Swap = true;
12959 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12960 FlipSigns = true; break;
12961 case ISD::SETUGE: Swap = true;
12962 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12963 FlipSigns = true; Invert = true; break;
12966 // Special case: Use min/max operations for SETULE/SETUGE
12967 MVT VET = VT.getVectorElementType();
12969 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12970 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12973 switch (SetCCOpcode) {
12975 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12976 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12979 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12982 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12983 if (!MinMax && hasSubus) {
12984 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12986 // t = psubus Op0, Op1
12987 // pcmpeq t, <0..0>
12988 switch (SetCCOpcode) {
12990 case ISD::SETULT: {
12991 // If the comparison is against a constant we can turn this into a
12992 // setule. With psubus, setule does not require a swap. This is
12993 // beneficial because the constant in the register is no longer
12994 // destructed as the destination so it can be hoisted out of a loop.
12995 // Only do this pre-AVX since vpcmp* is no longer destructive.
12996 if (Subtarget->hasAVX())
12998 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12999 if (ULEOp1.getNode()) {
13001 Subus = true; Invert = false; Swap = false;
13005 // Psubus is better than flip-sign because it requires no inversion.
13006 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13007 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13011 Opc = X86ISD::SUBUS;
13017 std::swap(Op0, Op1);
13019 // Check that the operation in question is available (most are plain SSE2,
13020 // but PCMPGTQ and PCMPEQQ have different requirements).
13021 if (VT == MVT::v2i64) {
13022 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13023 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13025 // First cast everything to the right type.
13026 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13027 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13029 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13030 // bits of the inputs before performing those operations. The lower
13031 // compare is always unsigned.
13034 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13036 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13037 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13038 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13039 Sign, Zero, Sign, Zero);
13041 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13042 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13044 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13045 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13046 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13048 // Create masks for only the low parts/high parts of the 64 bit integers.
13049 static const int MaskHi[] = { 1, 1, 3, 3 };
13050 static const int MaskLo[] = { 0, 0, 2, 2 };
13051 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13052 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13053 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13055 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13056 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13059 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13061 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13064 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13065 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13066 // pcmpeqd + pshufd + pand.
13067 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13069 // First cast everything to the right type.
13070 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13071 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13074 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13076 // Make sure the lower and upper halves are both all-ones.
13077 static const int Mask[] = { 1, 0, 3, 2 };
13078 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13079 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13082 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13084 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13088 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13089 // bits of the inputs before performing those operations.
13091 EVT EltVT = VT.getVectorElementType();
13092 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13093 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13094 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13097 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13099 // If the logical-not of the result is required, perform that now.
13101 Result = DAG.getNOT(dl, Result, VT);
13104 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13107 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13108 getZeroVector(VT, Subtarget, DAG, dl));
13113 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13115 MVT VT = Op.getSimpleValueType();
13117 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13119 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13120 && "SetCC type must be 8-bit or 1-bit integer");
13121 SDValue Op0 = Op.getOperand(0);
13122 SDValue Op1 = Op.getOperand(1);
13124 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13126 // Optimize to BT if possible.
13127 // Lower (X & (1 << N)) == 0 to BT(X, N).
13128 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13129 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13130 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13131 Op1.getOpcode() == ISD::Constant &&
13132 cast<ConstantSDNode>(Op1)->isNullValue() &&
13133 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13134 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13135 if (NewSetCC.getNode()) {
13137 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13142 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13144 if (Op1.getOpcode() == ISD::Constant &&
13145 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13146 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13147 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13149 // If the input is a setcc, then reuse the input setcc or use a new one with
13150 // the inverted condition.
13151 if (Op0.getOpcode() == X86ISD::SETCC) {
13152 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13153 bool Invert = (CC == ISD::SETNE) ^
13154 cast<ConstantSDNode>(Op1)->isNullValue();
13158 CCode = X86::GetOppositeBranchCondition(CCode);
13159 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13160 DAG.getConstant(CCode, MVT::i8),
13161 Op0.getOperand(1));
13163 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13167 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13168 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13169 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13171 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13172 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13175 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13176 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13177 if (X86CC == X86::COND_INVALID)
13180 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13181 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13182 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13183 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13185 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13189 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13190 static bool isX86LogicalCmp(SDValue Op) {
13191 unsigned Opc = Op.getNode()->getOpcode();
13192 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13193 Opc == X86ISD::SAHF)
13195 if (Op.getResNo() == 1 &&
13196 (Opc == X86ISD::ADD ||
13197 Opc == X86ISD::SUB ||
13198 Opc == X86ISD::ADC ||
13199 Opc == X86ISD::SBB ||
13200 Opc == X86ISD::SMUL ||
13201 Opc == X86ISD::UMUL ||
13202 Opc == X86ISD::INC ||
13203 Opc == X86ISD::DEC ||
13204 Opc == X86ISD::OR ||
13205 Opc == X86ISD::XOR ||
13206 Opc == X86ISD::AND))
13209 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13215 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13216 if (V.getOpcode() != ISD::TRUNCATE)
13219 SDValue VOp0 = V.getOperand(0);
13220 unsigned InBits = VOp0.getValueSizeInBits();
13221 unsigned Bits = V.getValueSizeInBits();
13222 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13225 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13226 bool addTest = true;
13227 SDValue Cond = Op.getOperand(0);
13228 SDValue Op1 = Op.getOperand(1);
13229 SDValue Op2 = Op.getOperand(2);
13231 EVT VT = Op1.getValueType();
13234 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13235 // are available or VBLENDV if AVX is available.
13236 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13237 if (Cond.getOpcode() == ISD::SETCC &&
13238 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13239 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13240 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13241 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13242 int SSECC = translateX86FSETCC(
13243 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13246 if (Subtarget->hasAVX512()) {
13247 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13248 DAG.getConstant(SSECC, MVT::i8));
13249 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13252 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13253 DAG.getConstant(SSECC, MVT::i8));
13255 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13256 // of 3 logic instructions for size savings and potentially speed.
13257 // Unfortunately, there is no scalar form of VBLENDV.
13259 // If either operand is a constant, don't try this. We can expect to
13260 // optimize away at least one of the logic instructions later in that
13261 // case, so that sequence would be faster than a variable blend.
13263 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13264 // uses XMM0 as the selection register. That may need just as many
13265 // instructions as the AND/ANDN/OR sequence due to register moves, so
13268 if (Subtarget->hasAVX() &&
13269 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13271 // Convert to vectors, do a VSELECT, and convert back to scalar.
13272 // All of the conversions should be optimized away.
13274 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13275 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13276 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13277 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13279 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13280 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13282 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13284 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13285 VSel, DAG.getIntPtrConstant(0));
13287 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13288 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13289 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13293 if (Cond.getOpcode() == ISD::SETCC) {
13294 SDValue NewCond = LowerSETCC(Cond, DAG);
13295 if (NewCond.getNode())
13299 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13300 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13301 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13302 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13303 if (Cond.getOpcode() == X86ISD::SETCC &&
13304 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13305 isZero(Cond.getOperand(1).getOperand(1))) {
13306 SDValue Cmp = Cond.getOperand(1);
13308 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13310 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13311 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13312 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13314 SDValue CmpOp0 = Cmp.getOperand(0);
13315 // Apply further optimizations for special cases
13316 // (select (x != 0), -1, 0) -> neg & sbb
13317 // (select (x == 0), 0, -1) -> neg & sbb
13318 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13319 if (YC->isNullValue() &&
13320 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13321 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13322 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13323 DAG.getConstant(0, CmpOp0.getValueType()),
13325 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13326 DAG.getConstant(X86::COND_B, MVT::i8),
13327 SDValue(Neg.getNode(), 1));
13331 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13332 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13333 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13335 SDValue Res = // Res = 0 or -1.
13336 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13337 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13339 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13340 Res = DAG.getNOT(DL, Res, Res.getValueType());
13342 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13343 if (!N2C || !N2C->isNullValue())
13344 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13349 // Look past (and (setcc_carry (cmp ...)), 1).
13350 if (Cond.getOpcode() == ISD::AND &&
13351 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13352 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13353 if (C && C->getAPIntValue() == 1)
13354 Cond = Cond.getOperand(0);
13357 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13358 // setting operand in place of the X86ISD::SETCC.
13359 unsigned CondOpcode = Cond.getOpcode();
13360 if (CondOpcode == X86ISD::SETCC ||
13361 CondOpcode == X86ISD::SETCC_CARRY) {
13362 CC = Cond.getOperand(0);
13364 SDValue Cmp = Cond.getOperand(1);
13365 unsigned Opc = Cmp.getOpcode();
13366 MVT VT = Op.getSimpleValueType();
13368 bool IllegalFPCMov = false;
13369 if (VT.isFloatingPoint() && !VT.isVector() &&
13370 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13371 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13373 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13374 Opc == X86ISD::BT) { // FIXME
13378 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13379 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13380 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13381 Cond.getOperand(0).getValueType() != MVT::i8)) {
13382 SDValue LHS = Cond.getOperand(0);
13383 SDValue RHS = Cond.getOperand(1);
13384 unsigned X86Opcode;
13387 switch (CondOpcode) {
13388 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13389 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13390 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13391 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13392 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13393 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13394 default: llvm_unreachable("unexpected overflowing operator");
13396 if (CondOpcode == ISD::UMULO)
13397 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13400 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13402 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13404 if (CondOpcode == ISD::UMULO)
13405 Cond = X86Op.getValue(2);
13407 Cond = X86Op.getValue(1);
13409 CC = DAG.getConstant(X86Cond, MVT::i8);
13414 // Look pass the truncate if the high bits are known zero.
13415 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13416 Cond = Cond.getOperand(0);
13418 // We know the result of AND is compared against zero. Try to match
13420 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13421 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13422 if (NewSetCC.getNode()) {
13423 CC = NewSetCC.getOperand(0);
13424 Cond = NewSetCC.getOperand(1);
13431 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13432 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13435 // a < b ? -1 : 0 -> RES = ~setcc_carry
13436 // a < b ? 0 : -1 -> RES = setcc_carry
13437 // a >= b ? -1 : 0 -> RES = setcc_carry
13438 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13439 if (Cond.getOpcode() == X86ISD::SUB) {
13440 Cond = ConvertCmpIfNecessary(Cond, DAG);
13441 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13443 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13444 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13445 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13446 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13447 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13448 return DAG.getNOT(DL, Res, Res.getValueType());
13453 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13454 // widen the cmov and push the truncate through. This avoids introducing a new
13455 // branch during isel and doesn't add any extensions.
13456 if (Op.getValueType() == MVT::i8 &&
13457 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13458 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13459 if (T1.getValueType() == T2.getValueType() &&
13460 // Blacklist CopyFromReg to avoid partial register stalls.
13461 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13462 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13463 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13464 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13468 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13469 // condition is true.
13470 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13471 SDValue Ops[] = { Op2, Op1, CC, Cond };
13472 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13475 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13476 SelectionDAG &DAG) {
13477 MVT VT = Op->getSimpleValueType(0);
13478 SDValue In = Op->getOperand(0);
13479 MVT InVT = In.getSimpleValueType();
13480 MVT VTElt = VT.getVectorElementType();
13481 MVT InVTElt = InVT.getVectorElementType();
13485 if ((InVTElt == MVT::i1) &&
13486 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13487 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13489 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13490 VTElt.getSizeInBits() <= 16)) ||
13492 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13493 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13495 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13496 VTElt.getSizeInBits() >= 32))))
13497 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13499 unsigned int NumElts = VT.getVectorNumElements();
13501 if (NumElts != 8 && NumElts != 16)
13504 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13505 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13506 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13507 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13510 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13511 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13513 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13514 Constant *C = ConstantInt::get(*DAG.getContext(),
13515 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13517 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13518 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13519 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13520 MachinePointerInfo::getConstantPool(),
13521 false, false, false, Alignment);
13522 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13523 if (VT.is512BitVector())
13525 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13528 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13529 SelectionDAG &DAG) {
13530 MVT VT = Op->getSimpleValueType(0);
13531 SDValue In = Op->getOperand(0);
13532 MVT InVT = In.getSimpleValueType();
13535 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13536 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13538 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13539 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13540 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13543 if (Subtarget->hasInt256())
13544 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13546 // Optimize vectors in AVX mode
13547 // Sign extend v8i16 to v8i32 and
13550 // Divide input vector into two parts
13551 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13552 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13553 // concat the vectors to original VT
13555 unsigned NumElems = InVT.getVectorNumElements();
13556 SDValue Undef = DAG.getUNDEF(InVT);
13558 SmallVector<int,8> ShufMask1(NumElems, -1);
13559 for (unsigned i = 0; i != NumElems/2; ++i)
13562 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13564 SmallVector<int,8> ShufMask2(NumElems, -1);
13565 for (unsigned i = 0; i != NumElems/2; ++i)
13566 ShufMask2[i] = i + NumElems/2;
13568 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13570 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13571 VT.getVectorNumElements()/2);
13573 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13574 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13576 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13579 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13580 // may emit an illegal shuffle but the expansion is still better than scalar
13581 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13582 // we'll emit a shuffle and a arithmetic shift.
13583 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13584 // TODO: It is possible to support ZExt by zeroing the undef values during
13585 // the shuffle phase or after the shuffle.
13586 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13587 SelectionDAG &DAG) {
13588 MVT RegVT = Op.getSimpleValueType();
13589 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13590 assert(RegVT.isInteger() &&
13591 "We only custom lower integer vector sext loads.");
13593 // Nothing useful we can do without SSE2 shuffles.
13594 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13596 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13598 EVT MemVT = Ld->getMemoryVT();
13599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13600 unsigned RegSz = RegVT.getSizeInBits();
13602 ISD::LoadExtType Ext = Ld->getExtensionType();
13604 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13605 && "Only anyext and sext are currently implemented.");
13606 assert(MemVT != RegVT && "Cannot extend to the same type");
13607 assert(MemVT.isVector() && "Must load a vector from memory");
13609 unsigned NumElems = RegVT.getVectorNumElements();
13610 unsigned MemSz = MemVT.getSizeInBits();
13611 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13613 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13614 // The only way in which we have a legal 256-bit vector result but not the
13615 // integer 256-bit operations needed to directly lower a sextload is if we
13616 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13617 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13618 // correctly legalized. We do this late to allow the canonical form of
13619 // sextload to persist throughout the rest of the DAG combiner -- it wants
13620 // to fold together any extensions it can, and so will fuse a sign_extend
13621 // of an sextload into a sextload targeting a wider value.
13623 if (MemSz == 128) {
13624 // Just switch this to a normal load.
13625 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13626 "it must be a legal 128-bit vector "
13628 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13629 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13630 Ld->isInvariant(), Ld->getAlignment());
13632 assert(MemSz < 128 &&
13633 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13634 // Do an sext load to a 128-bit vector type. We want to use the same
13635 // number of elements, but elements half as wide. This will end up being
13636 // recursively lowered by this routine, but will succeed as we definitely
13637 // have all the necessary features if we're using AVX1.
13639 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13640 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13642 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13643 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13644 Ld->isNonTemporal(), Ld->isInvariant(),
13645 Ld->getAlignment());
13648 // Replace chain users with the new chain.
13649 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13650 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13652 // Finally, do a normal sign-extend to the desired register.
13653 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13656 // All sizes must be a power of two.
13657 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13658 "Non-power-of-two elements are not custom lowered!");
13660 // Attempt to load the original value using scalar loads.
13661 // Find the largest scalar type that divides the total loaded size.
13662 MVT SclrLoadTy = MVT::i8;
13663 for (MVT Tp : MVT::integer_valuetypes()) {
13664 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13669 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13670 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13672 SclrLoadTy = MVT::f64;
13674 // Calculate the number of scalar loads that we need to perform
13675 // in order to load our vector from memory.
13676 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13678 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13679 "Can only lower sext loads with a single scalar load!");
13681 unsigned loadRegZize = RegSz;
13682 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13685 // Represent our vector as a sequence of elements which are the
13686 // largest scalar that we can load.
13687 EVT LoadUnitVecVT = EVT::getVectorVT(
13688 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13690 // Represent the data using the same element type that is stored in
13691 // memory. In practice, we ''widen'' MemVT.
13693 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13694 loadRegZize / MemVT.getScalarType().getSizeInBits());
13696 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13697 "Invalid vector type");
13699 // We can't shuffle using an illegal type.
13700 assert(TLI.isTypeLegal(WideVecVT) &&
13701 "We only lower types that form legal widened vector types");
13703 SmallVector<SDValue, 8> Chains;
13704 SDValue Ptr = Ld->getBasePtr();
13705 SDValue Increment =
13706 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13707 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13709 for (unsigned i = 0; i < NumLoads; ++i) {
13710 // Perform a single load.
13711 SDValue ScalarLoad =
13712 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13713 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13714 Ld->getAlignment());
13715 Chains.push_back(ScalarLoad.getValue(1));
13716 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13717 // another round of DAGCombining.
13719 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13721 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13722 ScalarLoad, DAG.getIntPtrConstant(i));
13724 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13727 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13729 // Bitcast the loaded value to a vector of the original element type, in
13730 // the size of the target vector type.
13731 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13732 unsigned SizeRatio = RegSz / MemSz;
13734 if (Ext == ISD::SEXTLOAD) {
13735 // If we have SSE4.1, we can directly emit a VSEXT node.
13736 if (Subtarget->hasSSE41()) {
13737 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13738 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13742 // Otherwise we'll shuffle the small elements in the high bits of the
13743 // larger type and perform an arithmetic shift. If the shift is not legal
13744 // it's better to scalarize.
13745 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13746 "We can't implement a sext load without an arithmetic right shift!");
13748 // Redistribute the loaded elements into the different locations.
13749 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13750 for (unsigned i = 0; i != NumElems; ++i)
13751 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13753 SDValue Shuff = DAG.getVectorShuffle(
13754 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13756 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13758 // Build the arithmetic shift.
13759 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13760 MemVT.getVectorElementType().getSizeInBits();
13762 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13764 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13768 // Redistribute the loaded elements into the different locations.
13769 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13770 for (unsigned i = 0; i != NumElems; ++i)
13771 ShuffleVec[i * SizeRatio] = i;
13773 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13774 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13776 // Bitcast to the requested type.
13777 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13778 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13782 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13783 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13784 // from the AND / OR.
13785 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13786 Opc = Op.getOpcode();
13787 if (Opc != ISD::OR && Opc != ISD::AND)
13789 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13790 Op.getOperand(0).hasOneUse() &&
13791 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13792 Op.getOperand(1).hasOneUse());
13795 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13796 // 1 and that the SETCC node has a single use.
13797 static bool isXor1OfSetCC(SDValue Op) {
13798 if (Op.getOpcode() != ISD::XOR)
13800 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13801 if (N1C && N1C->getAPIntValue() == 1) {
13802 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13803 Op.getOperand(0).hasOneUse();
13808 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13809 bool addTest = true;
13810 SDValue Chain = Op.getOperand(0);
13811 SDValue Cond = Op.getOperand(1);
13812 SDValue Dest = Op.getOperand(2);
13815 bool Inverted = false;
13817 if (Cond.getOpcode() == ISD::SETCC) {
13818 // Check for setcc([su]{add,sub,mul}o == 0).
13819 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13820 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13821 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13822 Cond.getOperand(0).getResNo() == 1 &&
13823 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13824 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13825 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13826 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13827 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13828 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13830 Cond = Cond.getOperand(0);
13832 SDValue NewCond = LowerSETCC(Cond, DAG);
13833 if (NewCond.getNode())
13838 // FIXME: LowerXALUO doesn't handle these!!
13839 else if (Cond.getOpcode() == X86ISD::ADD ||
13840 Cond.getOpcode() == X86ISD::SUB ||
13841 Cond.getOpcode() == X86ISD::SMUL ||
13842 Cond.getOpcode() == X86ISD::UMUL)
13843 Cond = LowerXALUO(Cond, DAG);
13846 // Look pass (and (setcc_carry (cmp ...)), 1).
13847 if (Cond.getOpcode() == ISD::AND &&
13848 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13849 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13850 if (C && C->getAPIntValue() == 1)
13851 Cond = Cond.getOperand(0);
13854 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13855 // setting operand in place of the X86ISD::SETCC.
13856 unsigned CondOpcode = Cond.getOpcode();
13857 if (CondOpcode == X86ISD::SETCC ||
13858 CondOpcode == X86ISD::SETCC_CARRY) {
13859 CC = Cond.getOperand(0);
13861 SDValue Cmp = Cond.getOperand(1);
13862 unsigned Opc = Cmp.getOpcode();
13863 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13864 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13868 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13872 // These can only come from an arithmetic instruction with overflow,
13873 // e.g. SADDO, UADDO.
13874 Cond = Cond.getNode()->getOperand(1);
13880 CondOpcode = Cond.getOpcode();
13881 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13882 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13883 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13884 Cond.getOperand(0).getValueType() != MVT::i8)) {
13885 SDValue LHS = Cond.getOperand(0);
13886 SDValue RHS = Cond.getOperand(1);
13887 unsigned X86Opcode;
13890 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13891 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13893 switch (CondOpcode) {
13894 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13896 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13898 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13901 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13902 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13906 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13909 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13910 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13911 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13912 default: llvm_unreachable("unexpected overflowing operator");
13915 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13916 if (CondOpcode == ISD::UMULO)
13917 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13920 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13922 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13924 if (CondOpcode == ISD::UMULO)
13925 Cond = X86Op.getValue(2);
13927 Cond = X86Op.getValue(1);
13929 CC = DAG.getConstant(X86Cond, MVT::i8);
13933 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13934 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13935 if (CondOpc == ISD::OR) {
13936 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13937 // two branches instead of an explicit OR instruction with a
13939 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13940 isX86LogicalCmp(Cmp)) {
13941 CC = Cond.getOperand(0).getOperand(0);
13942 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13943 Chain, Dest, CC, Cmp);
13944 CC = Cond.getOperand(1).getOperand(0);
13948 } else { // ISD::AND
13949 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13950 // two branches instead of an explicit AND instruction with a
13951 // separate test. However, we only do this if this block doesn't
13952 // have a fall-through edge, because this requires an explicit
13953 // jmp when the condition is false.
13954 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13955 isX86LogicalCmp(Cmp) &&
13956 Op.getNode()->hasOneUse()) {
13957 X86::CondCode CCode =
13958 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13959 CCode = X86::GetOppositeBranchCondition(CCode);
13960 CC = DAG.getConstant(CCode, MVT::i8);
13961 SDNode *User = *Op.getNode()->use_begin();
13962 // Look for an unconditional branch following this conditional branch.
13963 // We need this because we need to reverse the successors in order
13964 // to implement FCMP_OEQ.
13965 if (User->getOpcode() == ISD::BR) {
13966 SDValue FalseBB = User->getOperand(1);
13968 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13969 assert(NewBR == User);
13973 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13974 Chain, Dest, CC, Cmp);
13975 X86::CondCode CCode =
13976 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13977 CCode = X86::GetOppositeBranchCondition(CCode);
13978 CC = DAG.getConstant(CCode, MVT::i8);
13984 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13985 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13986 // It should be transformed during dag combiner except when the condition
13987 // is set by a arithmetics with overflow node.
13988 X86::CondCode CCode =
13989 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13990 CCode = X86::GetOppositeBranchCondition(CCode);
13991 CC = DAG.getConstant(CCode, MVT::i8);
13992 Cond = Cond.getOperand(0).getOperand(1);
13994 } else if (Cond.getOpcode() == ISD::SETCC &&
13995 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13996 // For FCMP_OEQ, we can emit
13997 // two branches instead of an explicit AND instruction with a
13998 // separate test. However, we only do this if this block doesn't
13999 // have a fall-through edge, because this requires an explicit
14000 // jmp when the condition is false.
14001 if (Op.getNode()->hasOneUse()) {
14002 SDNode *User = *Op.getNode()->use_begin();
14003 // Look for an unconditional branch following this conditional branch.
14004 // We need this because we need to reverse the successors in order
14005 // to implement FCMP_OEQ.
14006 if (User->getOpcode() == ISD::BR) {
14007 SDValue FalseBB = User->getOperand(1);
14009 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14010 assert(NewBR == User);
14014 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14015 Cond.getOperand(0), Cond.getOperand(1));
14016 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14017 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14018 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14019 Chain, Dest, CC, Cmp);
14020 CC = DAG.getConstant(X86::COND_P, MVT::i8);
14025 } else if (Cond.getOpcode() == ISD::SETCC &&
14026 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14027 // For FCMP_UNE, we can emit
14028 // two branches instead of an explicit AND instruction with a
14029 // separate test. However, we only do this if this block doesn't
14030 // have a fall-through edge, because this requires an explicit
14031 // jmp when the condition is false.
14032 if (Op.getNode()->hasOneUse()) {
14033 SDNode *User = *Op.getNode()->use_begin();
14034 // Look for an unconditional branch following this conditional branch.
14035 // We need this because we need to reverse the successors in order
14036 // to implement FCMP_UNE.
14037 if (User->getOpcode() == ISD::BR) {
14038 SDValue FalseBB = User->getOperand(1);
14040 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14041 assert(NewBR == User);
14044 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14045 Cond.getOperand(0), Cond.getOperand(1));
14046 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14047 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14048 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14049 Chain, Dest, CC, Cmp);
14050 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14060 // Look pass the truncate if the high bits are known zero.
14061 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14062 Cond = Cond.getOperand(0);
14064 // We know the result of AND is compared against zero. Try to match
14066 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14067 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14068 if (NewSetCC.getNode()) {
14069 CC = NewSetCC.getOperand(0);
14070 Cond = NewSetCC.getOperand(1);
14077 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14078 CC = DAG.getConstant(X86Cond, MVT::i8);
14079 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14081 Cond = ConvertCmpIfNecessary(Cond, DAG);
14082 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14083 Chain, Dest, CC, Cond);
14086 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14087 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14088 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14089 // that the guard pages used by the OS virtual memory manager are allocated in
14090 // correct sequence.
14092 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14093 SelectionDAG &DAG) const {
14094 MachineFunction &MF = DAG.getMachineFunction();
14095 bool SplitStack = MF.shouldSplitStack();
14096 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14101 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14102 SDNode* Node = Op.getNode();
14104 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14105 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14106 " not tell us which reg is the stack pointer!");
14107 EVT VT = Node->getValueType(0);
14108 SDValue Tmp1 = SDValue(Node, 0);
14109 SDValue Tmp2 = SDValue(Node, 1);
14110 SDValue Tmp3 = Node->getOperand(2);
14111 SDValue Chain = Tmp1.getOperand(0);
14113 // Chain the dynamic stack allocation so that it doesn't modify the stack
14114 // pointer when other instructions are using the stack.
14115 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14118 SDValue Size = Tmp2.getOperand(1);
14119 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14120 Chain = SP.getValue(1);
14121 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14122 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14123 unsigned StackAlign = TFI.getStackAlignment();
14124 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14125 if (Align > StackAlign)
14126 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14127 DAG.getConstant(-(uint64_t)Align, VT));
14128 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14130 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14131 DAG.getIntPtrConstant(0, true), SDValue(),
14134 SDValue Ops[2] = { Tmp1, Tmp2 };
14135 return DAG.getMergeValues(Ops, dl);
14139 SDValue Chain = Op.getOperand(0);
14140 SDValue Size = Op.getOperand(1);
14141 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14142 EVT VT = Op.getNode()->getValueType(0);
14144 bool Is64Bit = Subtarget->is64Bit();
14145 EVT SPTy = getPointerTy();
14148 MachineRegisterInfo &MRI = MF.getRegInfo();
14151 // The 64 bit implementation of segmented stacks needs to clobber both r10
14152 // r11. This makes it impossible to use it along with nested parameters.
14153 const Function *F = MF.getFunction();
14155 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14157 if (I->hasNestAttr())
14158 report_fatal_error("Cannot use segmented stacks with functions that "
14159 "have nested arguments.");
14162 const TargetRegisterClass *AddrRegClass =
14163 getRegClassFor(getPointerTy());
14164 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14165 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14166 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14167 DAG.getRegister(Vreg, SPTy));
14168 SDValue Ops1[2] = { Value, Chain };
14169 return DAG.getMergeValues(Ops1, dl);
14172 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14174 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14175 Flag = Chain.getValue(1);
14176 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14178 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14180 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14181 unsigned SPReg = RegInfo->getStackRegister();
14182 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14183 Chain = SP.getValue(1);
14186 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14187 DAG.getConstant(-(uint64_t)Align, VT));
14188 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14191 SDValue Ops1[2] = { SP, Chain };
14192 return DAG.getMergeValues(Ops1, dl);
14196 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14197 MachineFunction &MF = DAG.getMachineFunction();
14198 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14200 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14203 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14204 // vastart just stores the address of the VarArgsFrameIndex slot into the
14205 // memory location argument.
14206 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14208 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14209 MachinePointerInfo(SV), false, false, 0);
14213 // gp_offset (0 - 6 * 8)
14214 // fp_offset (48 - 48 + 8 * 16)
14215 // overflow_arg_area (point to parameters coming in memory).
14217 SmallVector<SDValue, 8> MemOps;
14218 SDValue FIN = Op.getOperand(1);
14220 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14221 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14223 FIN, MachinePointerInfo(SV), false, false, 0);
14224 MemOps.push_back(Store);
14227 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14228 FIN, DAG.getIntPtrConstant(4));
14229 Store = DAG.getStore(Op.getOperand(0), DL,
14230 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14232 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14233 MemOps.push_back(Store);
14235 // Store ptr to overflow_arg_area
14236 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14237 FIN, DAG.getIntPtrConstant(4));
14238 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14240 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14241 MachinePointerInfo(SV, 8),
14243 MemOps.push_back(Store);
14245 // Store ptr to reg_save_area.
14246 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14247 FIN, DAG.getIntPtrConstant(8));
14248 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14250 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14251 MachinePointerInfo(SV, 16), false, false, 0);
14252 MemOps.push_back(Store);
14253 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14256 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14257 assert(Subtarget->is64Bit() &&
14258 "LowerVAARG only handles 64-bit va_arg!");
14259 assert((Subtarget->isTargetLinux() ||
14260 Subtarget->isTargetDarwin()) &&
14261 "Unhandled target in LowerVAARG");
14262 assert(Op.getNode()->getNumOperands() == 4);
14263 SDValue Chain = Op.getOperand(0);
14264 SDValue SrcPtr = Op.getOperand(1);
14265 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14266 unsigned Align = Op.getConstantOperandVal(3);
14269 EVT ArgVT = Op.getNode()->getValueType(0);
14270 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14271 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14274 // Decide which area this value should be read from.
14275 // TODO: Implement the AMD64 ABI in its entirety. This simple
14276 // selection mechanism works only for the basic types.
14277 if (ArgVT == MVT::f80) {
14278 llvm_unreachable("va_arg for f80 not yet implemented");
14279 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14280 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14281 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14282 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14284 llvm_unreachable("Unhandled argument type in LowerVAARG");
14287 if (ArgMode == 2) {
14288 // Sanity Check: Make sure using fp_offset makes sense.
14289 assert(!DAG.getTarget().Options.UseSoftFloat &&
14290 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14291 Attribute::NoImplicitFloat)) &&
14292 Subtarget->hasSSE1());
14295 // Insert VAARG_64 node into the DAG
14296 // VAARG_64 returns two values: Variable Argument Address, Chain
14297 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14298 DAG.getConstant(ArgMode, MVT::i8),
14299 DAG.getConstant(Align, MVT::i32)};
14300 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14301 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14302 VTs, InstOps, MVT::i64,
14303 MachinePointerInfo(SV),
14305 /*Volatile=*/false,
14307 /*WriteMem=*/true);
14308 Chain = VAARG.getValue(1);
14310 // Load the next argument and return it
14311 return DAG.getLoad(ArgVT, dl,
14314 MachinePointerInfo(),
14315 false, false, false, 0);
14318 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14319 SelectionDAG &DAG) {
14320 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14321 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14322 SDValue Chain = Op.getOperand(0);
14323 SDValue DstPtr = Op.getOperand(1);
14324 SDValue SrcPtr = Op.getOperand(2);
14325 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14326 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14329 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14330 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14332 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14335 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14336 // amount is a constant. Takes immediate version of shift as input.
14337 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14338 SDValue SrcOp, uint64_t ShiftAmt,
14339 SelectionDAG &DAG) {
14340 MVT ElementType = VT.getVectorElementType();
14342 // Fold this packed shift into its first operand if ShiftAmt is 0.
14346 // Check for ShiftAmt >= element width
14347 if (ShiftAmt >= ElementType.getSizeInBits()) {
14348 if (Opc == X86ISD::VSRAI)
14349 ShiftAmt = ElementType.getSizeInBits() - 1;
14351 return DAG.getConstant(0, VT);
14354 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14355 && "Unknown target vector shift-by-constant node");
14357 // Fold this packed vector shift into a build vector if SrcOp is a
14358 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14359 if (VT == SrcOp.getSimpleValueType() &&
14360 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14361 SmallVector<SDValue, 8> Elts;
14362 unsigned NumElts = SrcOp->getNumOperands();
14363 ConstantSDNode *ND;
14366 default: llvm_unreachable(nullptr);
14367 case X86ISD::VSHLI:
14368 for (unsigned i=0; i!=NumElts; ++i) {
14369 SDValue CurrentOp = SrcOp->getOperand(i);
14370 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14371 Elts.push_back(CurrentOp);
14374 ND = cast<ConstantSDNode>(CurrentOp);
14375 const APInt &C = ND->getAPIntValue();
14376 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14379 case X86ISD::VSRLI:
14380 for (unsigned i=0; i!=NumElts; ++i) {
14381 SDValue CurrentOp = SrcOp->getOperand(i);
14382 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14383 Elts.push_back(CurrentOp);
14386 ND = cast<ConstantSDNode>(CurrentOp);
14387 const APInt &C = ND->getAPIntValue();
14388 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14391 case X86ISD::VSRAI:
14392 for (unsigned i=0; i!=NumElts; ++i) {
14393 SDValue CurrentOp = SrcOp->getOperand(i);
14394 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14395 Elts.push_back(CurrentOp);
14398 ND = cast<ConstantSDNode>(CurrentOp);
14399 const APInt &C = ND->getAPIntValue();
14400 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14405 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14408 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14411 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14412 // may or may not be a constant. Takes immediate version of shift as input.
14413 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14414 SDValue SrcOp, SDValue ShAmt,
14415 SelectionDAG &DAG) {
14416 MVT SVT = ShAmt.getSimpleValueType();
14417 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14419 // Catch shift-by-constant.
14420 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14421 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14422 CShAmt->getZExtValue(), DAG);
14424 // Change opcode to non-immediate version
14426 default: llvm_unreachable("Unknown target vector shift node");
14427 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14428 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14429 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14432 const X86Subtarget &Subtarget =
14433 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14434 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14435 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14436 // Let the shuffle legalizer expand this shift amount node.
14437 SDValue Op0 = ShAmt.getOperand(0);
14438 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14439 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14441 // Need to build a vector containing shift amount.
14442 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14443 SmallVector<SDValue, 4> ShOps;
14444 ShOps.push_back(ShAmt);
14445 if (SVT == MVT::i32) {
14446 ShOps.push_back(DAG.getConstant(0, SVT));
14447 ShOps.push_back(DAG.getUNDEF(SVT));
14449 ShOps.push_back(DAG.getUNDEF(SVT));
14451 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14452 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14455 // The return type has to be a 128-bit type with the same element
14456 // type as the input type.
14457 MVT EltVT = VT.getVectorElementType();
14458 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14460 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14461 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14464 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14465 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14466 /// necessary casting for \p Mask when lowering masking intrinsics.
14467 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14468 SDValue PreservedSrc,
14469 const X86Subtarget *Subtarget,
14470 SelectionDAG &DAG) {
14471 EVT VT = Op.getValueType();
14472 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14473 MVT::i1, VT.getVectorNumElements());
14474 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14475 Mask.getValueType().getSizeInBits());
14478 assert(MaskVT.isSimple() && "invalid mask type");
14480 if (isAllOnes(Mask))
14483 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14484 // are extracted by EXTRACT_SUBVECTOR.
14485 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14486 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14487 DAG.getIntPtrConstant(0));
14489 switch (Op.getOpcode()) {
14491 case X86ISD::PCMPEQM:
14492 case X86ISD::PCMPGTM:
14494 case X86ISD::CMPMU:
14495 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14497 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14498 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14499 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14502 /// \brief Creates an SDNode for a predicated scalar operation.
14503 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14504 /// The mask is comming as MVT::i8 and it should be truncated
14505 /// to MVT::i1 while lowering masking intrinsics.
14506 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14507 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14508 /// a scalar instruction.
14509 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14510 SDValue PreservedSrc,
14511 const X86Subtarget *Subtarget,
14512 SelectionDAG &DAG) {
14513 if (isAllOnes(Mask))
14516 EVT VT = Op.getValueType();
14518 // The mask should be of type MVT::i1
14519 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14521 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14522 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14523 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14526 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14527 SelectionDAG &DAG) {
14529 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14530 EVT VT = Op.getValueType();
14531 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14533 switch(IntrData->Type) {
14534 case INTR_TYPE_1OP:
14535 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14536 case INTR_TYPE_2OP:
14537 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14539 case INTR_TYPE_3OP:
14540 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14541 Op.getOperand(2), Op.getOperand(3));
14542 case INTR_TYPE_1OP_MASK_RM: {
14543 SDValue Src = Op.getOperand(1);
14544 SDValue Src0 = Op.getOperand(2);
14545 SDValue Mask = Op.getOperand(3);
14546 SDValue RoundingMode = Op.getOperand(4);
14547 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14549 Mask, Src0, Subtarget, DAG);
14551 case INTR_TYPE_SCALAR_MASK_RM: {
14552 SDValue Src1 = Op.getOperand(1);
14553 SDValue Src2 = Op.getOperand(2);
14554 SDValue Src0 = Op.getOperand(3);
14555 SDValue Mask = Op.getOperand(4);
14556 // There are 2 kinds of intrinsics in this group:
14557 // (1) With supress-all-exceptions (sae) - 6 operands
14558 // (2) With rounding mode and sae - 7 operands.
14559 if (Op.getNumOperands() == 6) {
14560 SDValue Sae = Op.getOperand(5);
14561 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14563 Mask, Src0, Subtarget, DAG);
14565 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14566 SDValue RoundingMode = Op.getOperand(5);
14567 SDValue Sae = Op.getOperand(6);
14568 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14569 RoundingMode, Sae),
14570 Mask, Src0, Subtarget, DAG);
14572 case INTR_TYPE_2OP_MASK: {
14573 SDValue Src1 = Op.getOperand(1);
14574 SDValue Src2 = Op.getOperand(2);
14575 SDValue PassThru = Op.getOperand(3);
14576 SDValue Mask = Op.getOperand(4);
14577 // We specify 2 possible opcodes for intrinsics with rounding modes.
14578 // First, we check if the intrinsic may have non-default rounding mode,
14579 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14580 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14581 if (IntrWithRoundingModeOpcode != 0) {
14582 SDValue Rnd = Op.getOperand(5);
14583 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14584 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14585 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14586 dl, Op.getValueType(),
14588 Mask, PassThru, Subtarget, DAG);
14591 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14593 Mask, PassThru, Subtarget, DAG);
14595 case FMA_OP_MASK: {
14596 SDValue Src1 = Op.getOperand(1);
14597 SDValue Src2 = Op.getOperand(2);
14598 SDValue Src3 = Op.getOperand(3);
14599 SDValue Mask = Op.getOperand(4);
14600 // We specify 2 possible opcodes for intrinsics with rounding modes.
14601 // First, we check if the intrinsic may have non-default rounding mode,
14602 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14603 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14604 if (IntrWithRoundingModeOpcode != 0) {
14605 SDValue Rnd = Op.getOperand(5);
14606 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14607 X86::STATIC_ROUNDING::CUR_DIRECTION)
14608 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14609 dl, Op.getValueType(),
14610 Src1, Src2, Src3, Rnd),
14611 Mask, Src1, Subtarget, DAG);
14613 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14614 dl, Op.getValueType(),
14616 Mask, Src1, Subtarget, DAG);
14619 case CMP_MASK_CC: {
14620 // Comparison intrinsics with masks.
14621 // Example of transformation:
14622 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14623 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14625 // (v8i1 (insert_subvector undef,
14626 // (v2i1 (and (PCMPEQM %a, %b),
14627 // (extract_subvector
14628 // (v8i1 (bitcast %mask)), 0))), 0))))
14629 EVT VT = Op.getOperand(1).getValueType();
14630 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14631 VT.getVectorNumElements());
14632 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14633 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14634 Mask.getValueType().getSizeInBits());
14636 if (IntrData->Type == CMP_MASK_CC) {
14637 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14638 Op.getOperand(2), Op.getOperand(3));
14640 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14641 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14644 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14645 DAG.getTargetConstant(0, MaskVT),
14647 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14648 DAG.getUNDEF(BitcastVT), CmpMask,
14649 DAG.getIntPtrConstant(0));
14650 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14652 case COMI: { // Comparison intrinsics
14653 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14654 SDValue LHS = Op.getOperand(1);
14655 SDValue RHS = Op.getOperand(2);
14656 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14657 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14658 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14659 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14660 DAG.getConstant(X86CC, MVT::i8), Cond);
14661 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14664 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14665 Op.getOperand(1), Op.getOperand(2), DAG);
14667 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14668 Op.getSimpleValueType(),
14670 Op.getOperand(2), DAG),
14671 Op.getOperand(4), Op.getOperand(3), Subtarget,
14673 case COMPRESS_EXPAND_IN_REG: {
14674 SDValue Mask = Op.getOperand(3);
14675 SDValue DataToCompress = Op.getOperand(1);
14676 SDValue PassThru = Op.getOperand(2);
14677 if (isAllOnes(Mask)) // return data as is
14678 return Op.getOperand(1);
14679 EVT VT = Op.getValueType();
14680 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14681 VT.getVectorNumElements());
14682 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14683 Mask.getValueType().getSizeInBits());
14685 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14686 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14687 DAG.getIntPtrConstant(0));
14689 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14693 SDValue Mask = Op.getOperand(3);
14694 EVT VT = Op.getValueType();
14695 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14696 VT.getVectorNumElements());
14697 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14698 Mask.getValueType().getSizeInBits());
14700 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14701 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14702 DAG.getIntPtrConstant(0));
14703 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14712 default: return SDValue(); // Don't custom lower most intrinsics.
14714 case Intrinsic::x86_avx512_mask_valign_q_512:
14715 case Intrinsic::x86_avx512_mask_valign_d_512:
14716 // Vector source operands are swapped.
14717 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14718 Op.getValueType(), Op.getOperand(2),
14721 Op.getOperand(5), Op.getOperand(4),
14724 // ptest and testp intrinsics. The intrinsic these come from are designed to
14725 // return an integer value, not just an instruction so lower it to the ptest
14726 // or testp pattern and a setcc for the result.
14727 case Intrinsic::x86_sse41_ptestz:
14728 case Intrinsic::x86_sse41_ptestc:
14729 case Intrinsic::x86_sse41_ptestnzc:
14730 case Intrinsic::x86_avx_ptestz_256:
14731 case Intrinsic::x86_avx_ptestc_256:
14732 case Intrinsic::x86_avx_ptestnzc_256:
14733 case Intrinsic::x86_avx_vtestz_ps:
14734 case Intrinsic::x86_avx_vtestc_ps:
14735 case Intrinsic::x86_avx_vtestnzc_ps:
14736 case Intrinsic::x86_avx_vtestz_pd:
14737 case Intrinsic::x86_avx_vtestc_pd:
14738 case Intrinsic::x86_avx_vtestnzc_pd:
14739 case Intrinsic::x86_avx_vtestz_ps_256:
14740 case Intrinsic::x86_avx_vtestc_ps_256:
14741 case Intrinsic::x86_avx_vtestnzc_ps_256:
14742 case Intrinsic::x86_avx_vtestz_pd_256:
14743 case Intrinsic::x86_avx_vtestc_pd_256:
14744 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14745 bool IsTestPacked = false;
14748 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14749 case Intrinsic::x86_avx_vtestz_ps:
14750 case Intrinsic::x86_avx_vtestz_pd:
14751 case Intrinsic::x86_avx_vtestz_ps_256:
14752 case Intrinsic::x86_avx_vtestz_pd_256:
14753 IsTestPacked = true; // Fallthrough
14754 case Intrinsic::x86_sse41_ptestz:
14755 case Intrinsic::x86_avx_ptestz_256:
14757 X86CC = X86::COND_E;
14759 case Intrinsic::x86_avx_vtestc_ps:
14760 case Intrinsic::x86_avx_vtestc_pd:
14761 case Intrinsic::x86_avx_vtestc_ps_256:
14762 case Intrinsic::x86_avx_vtestc_pd_256:
14763 IsTestPacked = true; // Fallthrough
14764 case Intrinsic::x86_sse41_ptestc:
14765 case Intrinsic::x86_avx_ptestc_256:
14767 X86CC = X86::COND_B;
14769 case Intrinsic::x86_avx_vtestnzc_ps:
14770 case Intrinsic::x86_avx_vtestnzc_pd:
14771 case Intrinsic::x86_avx_vtestnzc_ps_256:
14772 case Intrinsic::x86_avx_vtestnzc_pd_256:
14773 IsTestPacked = true; // Fallthrough
14774 case Intrinsic::x86_sse41_ptestnzc:
14775 case Intrinsic::x86_avx_ptestnzc_256:
14777 X86CC = X86::COND_A;
14781 SDValue LHS = Op.getOperand(1);
14782 SDValue RHS = Op.getOperand(2);
14783 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14784 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14785 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14786 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14787 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14789 case Intrinsic::x86_avx512_kortestz_w:
14790 case Intrinsic::x86_avx512_kortestc_w: {
14791 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14792 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14793 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14794 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14795 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14796 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14797 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14800 case Intrinsic::x86_sse42_pcmpistria128:
14801 case Intrinsic::x86_sse42_pcmpestria128:
14802 case Intrinsic::x86_sse42_pcmpistric128:
14803 case Intrinsic::x86_sse42_pcmpestric128:
14804 case Intrinsic::x86_sse42_pcmpistrio128:
14805 case Intrinsic::x86_sse42_pcmpestrio128:
14806 case Intrinsic::x86_sse42_pcmpistris128:
14807 case Intrinsic::x86_sse42_pcmpestris128:
14808 case Intrinsic::x86_sse42_pcmpistriz128:
14809 case Intrinsic::x86_sse42_pcmpestriz128: {
14813 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14814 case Intrinsic::x86_sse42_pcmpistria128:
14815 Opcode = X86ISD::PCMPISTRI;
14816 X86CC = X86::COND_A;
14818 case Intrinsic::x86_sse42_pcmpestria128:
14819 Opcode = X86ISD::PCMPESTRI;
14820 X86CC = X86::COND_A;
14822 case Intrinsic::x86_sse42_pcmpistric128:
14823 Opcode = X86ISD::PCMPISTRI;
14824 X86CC = X86::COND_B;
14826 case Intrinsic::x86_sse42_pcmpestric128:
14827 Opcode = X86ISD::PCMPESTRI;
14828 X86CC = X86::COND_B;
14830 case Intrinsic::x86_sse42_pcmpistrio128:
14831 Opcode = X86ISD::PCMPISTRI;
14832 X86CC = X86::COND_O;
14834 case Intrinsic::x86_sse42_pcmpestrio128:
14835 Opcode = X86ISD::PCMPESTRI;
14836 X86CC = X86::COND_O;
14838 case Intrinsic::x86_sse42_pcmpistris128:
14839 Opcode = X86ISD::PCMPISTRI;
14840 X86CC = X86::COND_S;
14842 case Intrinsic::x86_sse42_pcmpestris128:
14843 Opcode = X86ISD::PCMPESTRI;
14844 X86CC = X86::COND_S;
14846 case Intrinsic::x86_sse42_pcmpistriz128:
14847 Opcode = X86ISD::PCMPISTRI;
14848 X86CC = X86::COND_E;
14850 case Intrinsic::x86_sse42_pcmpestriz128:
14851 Opcode = X86ISD::PCMPESTRI;
14852 X86CC = X86::COND_E;
14855 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14856 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14857 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14858 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14859 DAG.getConstant(X86CC, MVT::i8),
14860 SDValue(PCMP.getNode(), 1));
14861 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14864 case Intrinsic::x86_sse42_pcmpistri128:
14865 case Intrinsic::x86_sse42_pcmpestri128: {
14867 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14868 Opcode = X86ISD::PCMPISTRI;
14870 Opcode = X86ISD::PCMPESTRI;
14872 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14873 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14874 return DAG.getNode(Opcode, dl, VTs, NewOps);
14879 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14880 SDValue Src, SDValue Mask, SDValue Base,
14881 SDValue Index, SDValue ScaleOp, SDValue Chain,
14882 const X86Subtarget * Subtarget) {
14884 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14885 assert(C && "Invalid scale type");
14886 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14887 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14888 Index.getSimpleValueType().getVectorNumElements());
14890 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14892 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14894 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14895 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14896 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14897 SDValue Segment = DAG.getRegister(0, MVT::i32);
14898 if (Src.getOpcode() == ISD::UNDEF)
14899 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14900 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14901 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14902 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14903 return DAG.getMergeValues(RetOps, dl);
14906 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14907 SDValue Src, SDValue Mask, SDValue Base,
14908 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14910 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14911 assert(C && "Invalid scale type");
14912 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14913 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14914 SDValue Segment = DAG.getRegister(0, MVT::i32);
14915 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14916 Index.getSimpleValueType().getVectorNumElements());
14918 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14920 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14922 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14923 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14924 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14925 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14926 return SDValue(Res, 1);
14929 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14930 SDValue Mask, SDValue Base, SDValue Index,
14931 SDValue ScaleOp, SDValue Chain) {
14933 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14934 assert(C && "Invalid scale type");
14935 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14936 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14937 SDValue Segment = DAG.getRegister(0, MVT::i32);
14939 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14941 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14943 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14945 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14946 //SDVTList VTs = DAG.getVTList(MVT::Other);
14947 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14948 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14949 return SDValue(Res, 0);
14952 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14953 // read performance monitor counters (x86_rdpmc).
14954 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14955 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14956 SmallVectorImpl<SDValue> &Results) {
14957 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14958 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14961 // The ECX register is used to select the index of the performance counter
14963 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14965 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14967 // Reads the content of a 64-bit performance counter and returns it in the
14968 // registers EDX:EAX.
14969 if (Subtarget->is64Bit()) {
14970 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14971 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14974 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14975 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14978 Chain = HI.getValue(1);
14980 if (Subtarget->is64Bit()) {
14981 // The EAX register is loaded with the low-order 32 bits. The EDX register
14982 // is loaded with the supported high-order bits of the counter.
14983 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14984 DAG.getConstant(32, MVT::i8));
14985 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14986 Results.push_back(Chain);
14990 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14991 SDValue Ops[] = { LO, HI };
14992 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14993 Results.push_back(Pair);
14994 Results.push_back(Chain);
14997 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14998 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14999 // also used to custom lower READCYCLECOUNTER nodes.
15000 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15001 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15002 SmallVectorImpl<SDValue> &Results) {
15003 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15004 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15007 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15008 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15009 // and the EAX register is loaded with the low-order 32 bits.
15010 if (Subtarget->is64Bit()) {
15011 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15012 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15015 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15016 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15019 SDValue Chain = HI.getValue(1);
15021 if (Opcode == X86ISD::RDTSCP_DAG) {
15022 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15024 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15025 // the ECX register. Add 'ecx' explicitly to the chain.
15026 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15028 // Explicitly store the content of ECX at the location passed in input
15029 // to the 'rdtscp' intrinsic.
15030 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15031 MachinePointerInfo(), false, false, 0);
15034 if (Subtarget->is64Bit()) {
15035 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15036 // the EAX register is loaded with the low-order 32 bits.
15037 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15038 DAG.getConstant(32, MVT::i8));
15039 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15040 Results.push_back(Chain);
15044 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15045 SDValue Ops[] = { LO, HI };
15046 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15047 Results.push_back(Pair);
15048 Results.push_back(Chain);
15051 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15052 SelectionDAG &DAG) {
15053 SmallVector<SDValue, 2> Results;
15055 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15057 return DAG.getMergeValues(Results, DL);
15061 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15062 SelectionDAG &DAG) {
15063 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15065 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15070 switch(IntrData->Type) {
15072 llvm_unreachable("Unknown Intrinsic Type");
15076 // Emit the node with the right value type.
15077 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15078 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15080 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15081 // Otherwise return the value from Rand, which is always 0, casted to i32.
15082 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15083 DAG.getConstant(1, Op->getValueType(1)),
15084 DAG.getConstant(X86::COND_B, MVT::i32),
15085 SDValue(Result.getNode(), 1) };
15086 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15087 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15090 // Return { result, isValid, chain }.
15091 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15092 SDValue(Result.getNode(), 2));
15095 //gather(v1, mask, index, base, scale);
15096 SDValue Chain = Op.getOperand(0);
15097 SDValue Src = Op.getOperand(2);
15098 SDValue Base = Op.getOperand(3);
15099 SDValue Index = Op.getOperand(4);
15100 SDValue Mask = Op.getOperand(5);
15101 SDValue Scale = Op.getOperand(6);
15102 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15106 //scatter(base, mask, index, v1, scale);
15107 SDValue Chain = Op.getOperand(0);
15108 SDValue Base = Op.getOperand(2);
15109 SDValue Mask = Op.getOperand(3);
15110 SDValue Index = Op.getOperand(4);
15111 SDValue Src = Op.getOperand(5);
15112 SDValue Scale = Op.getOperand(6);
15113 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15116 SDValue Hint = Op.getOperand(6);
15118 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15119 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15120 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15121 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15122 SDValue Chain = Op.getOperand(0);
15123 SDValue Mask = Op.getOperand(2);
15124 SDValue Index = Op.getOperand(3);
15125 SDValue Base = Op.getOperand(4);
15126 SDValue Scale = Op.getOperand(5);
15127 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15129 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15131 SmallVector<SDValue, 2> Results;
15132 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15133 return DAG.getMergeValues(Results, dl);
15135 // Read Performance Monitoring Counters.
15137 SmallVector<SDValue, 2> Results;
15138 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15139 return DAG.getMergeValues(Results, dl);
15141 // XTEST intrinsics.
15143 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15144 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15145 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15146 DAG.getConstant(X86::COND_NE, MVT::i8),
15148 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15149 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15150 Ret, SDValue(InTrans.getNode(), 1));
15154 SmallVector<SDValue, 2> Results;
15155 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15156 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15157 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15158 DAG.getConstant(-1, MVT::i8));
15159 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15160 Op.getOperand(4), GenCF.getValue(1));
15161 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15162 Op.getOperand(5), MachinePointerInfo(),
15164 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15165 DAG.getConstant(X86::COND_B, MVT::i8),
15167 Results.push_back(SetCC);
15168 Results.push_back(Store);
15169 return DAG.getMergeValues(Results, dl);
15171 case COMPRESS_TO_MEM: {
15173 SDValue Mask = Op.getOperand(4);
15174 SDValue DataToCompress = Op.getOperand(3);
15175 SDValue Addr = Op.getOperand(2);
15176 SDValue Chain = Op.getOperand(0);
15178 if (isAllOnes(Mask)) // return just a store
15179 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15180 MachinePointerInfo(), false, false, 0);
15182 EVT VT = DataToCompress.getValueType();
15183 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15184 VT.getVectorNumElements());
15185 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15186 Mask.getValueType().getSizeInBits());
15187 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15188 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15189 DAG.getIntPtrConstant(0));
15191 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15192 DataToCompress, DAG.getUNDEF(VT));
15193 return DAG.getStore(Chain, dl, Compressed, Addr,
15194 MachinePointerInfo(), false, false, 0);
15196 case EXPAND_FROM_MEM: {
15198 SDValue Mask = Op.getOperand(4);
15199 SDValue PathThru = Op.getOperand(3);
15200 SDValue Addr = Op.getOperand(2);
15201 SDValue Chain = Op.getOperand(0);
15202 EVT VT = Op.getValueType();
15204 if (isAllOnes(Mask)) // return just a load
15205 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15207 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15208 VT.getVectorNumElements());
15209 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15210 Mask.getValueType().getSizeInBits());
15211 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15212 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15213 DAG.getIntPtrConstant(0));
15215 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15216 false, false, false, 0);
15218 SDValue Results[] = {
15219 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15221 return DAG.getMergeValues(Results, dl);
15226 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15227 SelectionDAG &DAG) const {
15228 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15229 MFI->setReturnAddressIsTaken(true);
15231 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15234 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15236 EVT PtrVT = getPointerTy();
15239 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15240 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15241 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15242 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15243 DAG.getNode(ISD::ADD, dl, PtrVT,
15244 FrameAddr, Offset),
15245 MachinePointerInfo(), false, false, false, 0);
15248 // Just load the return address.
15249 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15250 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15251 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15254 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15255 MachineFunction &MF = DAG.getMachineFunction();
15256 MachineFrameInfo *MFI = MF.getFrameInfo();
15257 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15258 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15259 EVT VT = Op.getValueType();
15261 MFI->setFrameAddressIsTaken(true);
15263 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15264 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15265 // is not possible to crawl up the stack without looking at the unwind codes
15267 int FrameAddrIndex = FuncInfo->getFAIndex();
15268 if (!FrameAddrIndex) {
15269 // Set up a frame object for the return address.
15270 unsigned SlotSize = RegInfo->getSlotSize();
15271 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15272 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15273 FuncInfo->setFAIndex(FrameAddrIndex);
15275 return DAG.getFrameIndex(FrameAddrIndex, VT);
15278 unsigned FrameReg =
15279 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15280 SDLoc dl(Op); // FIXME probably not meaningful
15281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15282 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15283 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15284 "Invalid Frame Register!");
15285 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15287 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15288 MachinePointerInfo(),
15289 false, false, false, 0);
15293 // FIXME? Maybe this could be a TableGen attribute on some registers and
15294 // this table could be generated automatically from RegInfo.
15295 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15297 unsigned Reg = StringSwitch<unsigned>(RegName)
15298 .Case("esp", X86::ESP)
15299 .Case("rsp", X86::RSP)
15303 report_fatal_error("Invalid register name global variable");
15306 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15307 SelectionDAG &DAG) const {
15308 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15309 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15312 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15313 SDValue Chain = Op.getOperand(0);
15314 SDValue Offset = Op.getOperand(1);
15315 SDValue Handler = Op.getOperand(2);
15318 EVT PtrVT = getPointerTy();
15319 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15320 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15321 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15322 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15323 "Invalid Frame Register!");
15324 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15325 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15327 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15328 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15329 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15330 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15332 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15334 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15335 DAG.getRegister(StoreAddrReg, PtrVT));
15338 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15339 SelectionDAG &DAG) const {
15341 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15342 DAG.getVTList(MVT::i32, MVT::Other),
15343 Op.getOperand(0), Op.getOperand(1));
15346 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15347 SelectionDAG &DAG) const {
15349 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15350 Op.getOperand(0), Op.getOperand(1));
15353 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15354 return Op.getOperand(0);
15357 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15358 SelectionDAG &DAG) const {
15359 SDValue Root = Op.getOperand(0);
15360 SDValue Trmp = Op.getOperand(1); // trampoline
15361 SDValue FPtr = Op.getOperand(2); // nested function
15362 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15365 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15366 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15368 if (Subtarget->is64Bit()) {
15369 SDValue OutChains[6];
15371 // Large code-model.
15372 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15373 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15375 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15376 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15378 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15380 // Load the pointer to the nested function into R11.
15381 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15382 SDValue Addr = Trmp;
15383 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15384 Addr, MachinePointerInfo(TrmpAddr),
15387 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15388 DAG.getConstant(2, MVT::i64));
15389 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15390 MachinePointerInfo(TrmpAddr, 2),
15393 // Load the 'nest' parameter value into R10.
15394 // R10 is specified in X86CallingConv.td
15395 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15396 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15397 DAG.getConstant(10, MVT::i64));
15398 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15399 Addr, MachinePointerInfo(TrmpAddr, 10),
15402 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15403 DAG.getConstant(12, MVT::i64));
15404 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15405 MachinePointerInfo(TrmpAddr, 12),
15408 // Jump to the nested function.
15409 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15410 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15411 DAG.getConstant(20, MVT::i64));
15412 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15413 Addr, MachinePointerInfo(TrmpAddr, 20),
15416 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15417 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15418 DAG.getConstant(22, MVT::i64));
15419 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15420 MachinePointerInfo(TrmpAddr, 22),
15423 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15425 const Function *Func =
15426 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15427 CallingConv::ID CC = Func->getCallingConv();
15432 llvm_unreachable("Unsupported calling convention");
15433 case CallingConv::C:
15434 case CallingConv::X86_StdCall: {
15435 // Pass 'nest' parameter in ECX.
15436 // Must be kept in sync with X86CallingConv.td
15437 NestReg = X86::ECX;
15439 // Check that ECX wasn't needed by an 'inreg' parameter.
15440 FunctionType *FTy = Func->getFunctionType();
15441 const AttributeSet &Attrs = Func->getAttributes();
15443 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15444 unsigned InRegCount = 0;
15447 for (FunctionType::param_iterator I = FTy->param_begin(),
15448 E = FTy->param_end(); I != E; ++I, ++Idx)
15449 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15450 // FIXME: should only count parameters that are lowered to integers.
15451 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15453 if (InRegCount > 2) {
15454 report_fatal_error("Nest register in use - reduce number of inreg"
15460 case CallingConv::X86_FastCall:
15461 case CallingConv::X86_ThisCall:
15462 case CallingConv::Fast:
15463 // Pass 'nest' parameter in EAX.
15464 // Must be kept in sync with X86CallingConv.td
15465 NestReg = X86::EAX;
15469 SDValue OutChains[4];
15470 SDValue Addr, Disp;
15472 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15473 DAG.getConstant(10, MVT::i32));
15474 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15476 // This is storing the opcode for MOV32ri.
15477 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15478 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15479 OutChains[0] = DAG.getStore(Root, dl,
15480 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15481 Trmp, MachinePointerInfo(TrmpAddr),
15484 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15485 DAG.getConstant(1, MVT::i32));
15486 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15487 MachinePointerInfo(TrmpAddr, 1),
15490 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15491 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15492 DAG.getConstant(5, MVT::i32));
15493 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15494 MachinePointerInfo(TrmpAddr, 5),
15497 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15498 DAG.getConstant(6, MVT::i32));
15499 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15500 MachinePointerInfo(TrmpAddr, 6),
15503 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15507 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15508 SelectionDAG &DAG) const {
15510 The rounding mode is in bits 11:10 of FPSR, and has the following
15512 00 Round to nearest
15517 FLT_ROUNDS, on the other hand, expects the following:
15524 To perform the conversion, we do:
15525 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15528 MachineFunction &MF = DAG.getMachineFunction();
15529 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15530 unsigned StackAlignment = TFI.getStackAlignment();
15531 MVT VT = Op.getSimpleValueType();
15534 // Save FP Control Word to stack slot
15535 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15536 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15538 MachineMemOperand *MMO =
15539 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15540 MachineMemOperand::MOStore, 2, 2);
15542 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15543 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15544 DAG.getVTList(MVT::Other),
15545 Ops, MVT::i16, MMO);
15547 // Load FP Control Word from stack slot
15548 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15549 MachinePointerInfo(), false, false, false, 0);
15551 // Transform as necessary
15553 DAG.getNode(ISD::SRL, DL, MVT::i16,
15554 DAG.getNode(ISD::AND, DL, MVT::i16,
15555 CWD, DAG.getConstant(0x800, MVT::i16)),
15556 DAG.getConstant(11, MVT::i8));
15558 DAG.getNode(ISD::SRL, DL, MVT::i16,
15559 DAG.getNode(ISD::AND, DL, MVT::i16,
15560 CWD, DAG.getConstant(0x400, MVT::i16)),
15561 DAG.getConstant(9, MVT::i8));
15564 DAG.getNode(ISD::AND, DL, MVT::i16,
15565 DAG.getNode(ISD::ADD, DL, MVT::i16,
15566 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15567 DAG.getConstant(1, MVT::i16)),
15568 DAG.getConstant(3, MVT::i16));
15570 return DAG.getNode((VT.getSizeInBits() < 16 ?
15571 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15574 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15575 MVT VT = Op.getSimpleValueType();
15577 unsigned NumBits = VT.getSizeInBits();
15580 Op = Op.getOperand(0);
15581 if (VT == MVT::i8) {
15582 // Zero extend to i32 since there is not an i8 bsr.
15584 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15587 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15588 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15589 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15591 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15594 DAG.getConstant(NumBits+NumBits-1, OpVT),
15595 DAG.getConstant(X86::COND_E, MVT::i8),
15598 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15600 // Finally xor with NumBits-1.
15601 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15604 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15608 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15609 MVT VT = Op.getSimpleValueType();
15611 unsigned NumBits = VT.getSizeInBits();
15614 Op = Op.getOperand(0);
15615 if (VT == MVT::i8) {
15616 // Zero extend to i32 since there is not an i8 bsr.
15618 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15621 // Issue a bsr (scan bits in reverse).
15622 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15623 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15625 // And xor with NumBits-1.
15626 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15629 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15633 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15634 MVT VT = Op.getSimpleValueType();
15635 unsigned NumBits = VT.getSizeInBits();
15637 Op = Op.getOperand(0);
15639 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15640 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15641 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15643 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15646 DAG.getConstant(NumBits, VT),
15647 DAG.getConstant(X86::COND_E, MVT::i8),
15650 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15653 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15654 // ones, and then concatenate the result back.
15655 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15656 MVT VT = Op.getSimpleValueType();
15658 assert(VT.is256BitVector() && VT.isInteger() &&
15659 "Unsupported value type for operation");
15661 unsigned NumElems = VT.getVectorNumElements();
15664 // Extract the LHS vectors
15665 SDValue LHS = Op.getOperand(0);
15666 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15667 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15669 // Extract the RHS vectors
15670 SDValue RHS = Op.getOperand(1);
15671 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15672 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15674 MVT EltVT = VT.getVectorElementType();
15675 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15677 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15678 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15679 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15682 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15683 assert(Op.getSimpleValueType().is256BitVector() &&
15684 Op.getSimpleValueType().isInteger() &&
15685 "Only handle AVX 256-bit vector integer operation");
15686 return Lower256IntArith(Op, DAG);
15689 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15690 assert(Op.getSimpleValueType().is256BitVector() &&
15691 Op.getSimpleValueType().isInteger() &&
15692 "Only handle AVX 256-bit vector integer operation");
15693 return Lower256IntArith(Op, DAG);
15696 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15697 SelectionDAG &DAG) {
15699 MVT VT = Op.getSimpleValueType();
15701 // Decompose 256-bit ops into smaller 128-bit ops.
15702 if (VT.is256BitVector() && !Subtarget->hasInt256())
15703 return Lower256IntArith(Op, DAG);
15705 SDValue A = Op.getOperand(0);
15706 SDValue B = Op.getOperand(1);
15708 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15709 if (VT == MVT::v4i32) {
15710 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15711 "Should not custom lower when pmuldq is available!");
15713 // Extract the odd parts.
15714 static const int UnpackMask[] = { 1, -1, 3, -1 };
15715 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15716 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15718 // Multiply the even parts.
15719 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15720 // Now multiply odd parts.
15721 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15723 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15724 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15726 // Merge the two vectors back together with a shuffle. This expands into 2
15728 static const int ShufMask[] = { 0, 4, 2, 6 };
15729 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15732 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15733 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15735 // Ahi = psrlqi(a, 32);
15736 // Bhi = psrlqi(b, 32);
15738 // AloBlo = pmuludq(a, b);
15739 // AloBhi = pmuludq(a, Bhi);
15740 // AhiBlo = pmuludq(Ahi, b);
15742 // AloBhi = psllqi(AloBhi, 32);
15743 // AhiBlo = psllqi(AhiBlo, 32);
15744 // return AloBlo + AloBhi + AhiBlo;
15746 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15747 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15749 // Bit cast to 32-bit vectors for MULUDQ
15750 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15751 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15752 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15753 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15754 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15755 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15757 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15758 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15759 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15761 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15762 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15764 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15765 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15768 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15769 assert(Subtarget->isTargetWin64() && "Unexpected target");
15770 EVT VT = Op.getValueType();
15771 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15772 "Unexpected return type for lowering");
15776 switch (Op->getOpcode()) {
15777 default: llvm_unreachable("Unexpected request for libcall!");
15778 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15779 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15780 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15781 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15782 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15783 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15787 SDValue InChain = DAG.getEntryNode();
15789 TargetLowering::ArgListTy Args;
15790 TargetLowering::ArgListEntry Entry;
15791 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15792 EVT ArgVT = Op->getOperand(i).getValueType();
15793 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15794 "Unexpected argument type for lowering");
15795 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15796 Entry.Node = StackPtr;
15797 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15799 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15800 Entry.Ty = PointerType::get(ArgTy,0);
15801 Entry.isSExt = false;
15802 Entry.isZExt = false;
15803 Args.push_back(Entry);
15806 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15809 TargetLowering::CallLoweringInfo CLI(DAG);
15810 CLI.setDebugLoc(dl).setChain(InChain)
15811 .setCallee(getLibcallCallingConv(LC),
15812 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15813 Callee, std::move(Args), 0)
15814 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15816 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15817 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15820 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15821 SelectionDAG &DAG) {
15822 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15823 EVT VT = Op0.getValueType();
15826 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15827 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15829 // PMULxD operations multiply each even value (starting at 0) of LHS with
15830 // the related value of RHS and produce a widen result.
15831 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15832 // => <2 x i64> <ae|cg>
15834 // In other word, to have all the results, we need to perform two PMULxD:
15835 // 1. one with the even values.
15836 // 2. one with the odd values.
15837 // To achieve #2, with need to place the odd values at an even position.
15839 // Place the odd value at an even position (basically, shift all values 1
15840 // step to the left):
15841 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15842 // <a|b|c|d> => <b|undef|d|undef>
15843 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15844 // <e|f|g|h> => <f|undef|h|undef>
15845 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15847 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15849 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15850 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15852 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15853 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15854 // => <2 x i64> <ae|cg>
15855 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15856 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15857 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15858 // => <2 x i64> <bf|dh>
15859 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15860 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15862 // Shuffle it back into the right order.
15863 SDValue Highs, Lows;
15864 if (VT == MVT::v8i32) {
15865 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15866 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15867 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15868 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15870 const int HighMask[] = {1, 5, 3, 7};
15871 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15872 const int LowMask[] = {0, 4, 2, 6};
15873 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15876 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15877 // unsigned multiply.
15878 if (IsSigned && !Subtarget->hasSSE41()) {
15880 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15881 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15882 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15883 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15884 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15886 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15887 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15890 // The first result of MUL_LOHI is actually the low value, followed by the
15892 SDValue Ops[] = {Lows, Highs};
15893 return DAG.getMergeValues(Ops, dl);
15896 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15897 const X86Subtarget *Subtarget) {
15898 MVT VT = Op.getSimpleValueType();
15900 SDValue R = Op.getOperand(0);
15901 SDValue Amt = Op.getOperand(1);
15903 // Optimize shl/srl/sra with constant shift amount.
15904 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15905 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15906 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15908 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15909 (Subtarget->hasInt256() &&
15910 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15911 (Subtarget->hasAVX512() &&
15912 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15913 if (Op.getOpcode() == ISD::SHL)
15914 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15916 if (Op.getOpcode() == ISD::SRL)
15917 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15919 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15920 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15924 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
15925 unsigned NumElts = VT.getVectorNumElements();
15926 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
15928 if (Op.getOpcode() == ISD::SHL) {
15929 // Make a large shift.
15930 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
15932 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15933 // Zero out the rightmost bits.
15934 SmallVector<SDValue, 32> V(
15935 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
15936 return DAG.getNode(ISD::AND, dl, VT, SHL,
15937 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15939 if (Op.getOpcode() == ISD::SRL) {
15940 // Make a large shift.
15941 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
15943 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15944 // Zero out the leftmost bits.
15945 SmallVector<SDValue, 32> V(
15946 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
15947 return DAG.getNode(ISD::AND, dl, VT, SRL,
15948 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15950 if (Op.getOpcode() == ISD::SRA) {
15951 if (ShiftAmt == 7) {
15952 // R s>> 7 === R s< 0
15953 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15954 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15957 // R s>> a === ((R u>> a) ^ m) - m
15958 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15959 SmallVector<SDValue, 32> V(NumElts,
15960 DAG.getConstant(128 >> ShiftAmt, MVT::i8));
15961 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15962 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15963 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15966 llvm_unreachable("Unknown shift opcode.");
15971 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15972 if (!Subtarget->is64Bit() &&
15973 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15974 Amt.getOpcode() == ISD::BITCAST &&
15975 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15976 Amt = Amt.getOperand(0);
15977 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15978 VT.getVectorNumElements();
15979 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15980 uint64_t ShiftAmt = 0;
15981 for (unsigned i = 0; i != Ratio; ++i) {
15982 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15986 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15988 // Check remaining shift amounts.
15989 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15990 uint64_t ShAmt = 0;
15991 for (unsigned j = 0; j != Ratio; ++j) {
15992 ConstantSDNode *C =
15993 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15997 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15999 if (ShAmt != ShiftAmt)
16002 switch (Op.getOpcode()) {
16004 llvm_unreachable("Unknown shift opcode!");
16006 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16009 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16012 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16020 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16021 const X86Subtarget* Subtarget) {
16022 MVT VT = Op.getSimpleValueType();
16024 SDValue R = Op.getOperand(0);
16025 SDValue Amt = Op.getOperand(1);
16027 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16028 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16029 (Subtarget->hasInt256() &&
16030 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16031 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16032 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16034 EVT EltVT = VT.getVectorElementType();
16036 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16037 // Check if this build_vector node is doing a splat.
16038 // If so, then set BaseShAmt equal to the splat value.
16039 BaseShAmt = BV->getSplatValue();
16040 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16041 BaseShAmt = SDValue();
16043 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16044 Amt = Amt.getOperand(0);
16046 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16047 if (SVN && SVN->isSplat()) {
16048 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16049 SDValue InVec = Amt.getOperand(0);
16050 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16051 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16052 "Unexpected shuffle index found!");
16053 BaseShAmt = InVec.getOperand(SplatIdx);
16054 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16055 if (ConstantSDNode *C =
16056 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16057 if (C->getZExtValue() == SplatIdx)
16058 BaseShAmt = InVec.getOperand(1);
16063 // Avoid introducing an extract element from a shuffle.
16064 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16065 DAG.getIntPtrConstant(SplatIdx));
16069 if (BaseShAmt.getNode()) {
16070 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16071 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16072 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16073 else if (EltVT.bitsLT(MVT::i32))
16074 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16076 switch (Op.getOpcode()) {
16078 llvm_unreachable("Unknown shift opcode!");
16080 switch (VT.SimpleTy) {
16081 default: return SDValue();
16090 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16093 switch (VT.SimpleTy) {
16094 default: return SDValue();
16101 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16104 switch (VT.SimpleTy) {
16105 default: return SDValue();
16114 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16120 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16121 if (!Subtarget->is64Bit() &&
16122 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16123 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16124 Amt.getOpcode() == ISD::BITCAST &&
16125 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16126 Amt = Amt.getOperand(0);
16127 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16128 VT.getVectorNumElements();
16129 std::vector<SDValue> Vals(Ratio);
16130 for (unsigned i = 0; i != Ratio; ++i)
16131 Vals[i] = Amt.getOperand(i);
16132 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16133 for (unsigned j = 0; j != Ratio; ++j)
16134 if (Vals[j] != Amt.getOperand(i + j))
16137 switch (Op.getOpcode()) {
16139 llvm_unreachable("Unknown shift opcode!");
16141 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16143 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16145 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16152 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16153 SelectionDAG &DAG) {
16154 MVT VT = Op.getSimpleValueType();
16156 SDValue R = Op.getOperand(0);
16157 SDValue Amt = Op.getOperand(1);
16160 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16161 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16163 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16167 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16171 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16173 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16174 if (Subtarget->hasInt256()) {
16175 if (Op.getOpcode() == ISD::SRL &&
16176 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16177 VT == MVT::v4i64 || VT == MVT::v8i32))
16179 if (Op.getOpcode() == ISD::SHL &&
16180 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16181 VT == MVT::v4i64 || VT == MVT::v8i32))
16183 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16187 // If possible, lower this packed shift into a vector multiply instead of
16188 // expanding it into a sequence of scalar shifts.
16189 // Do this only if the vector shift count is a constant build_vector.
16190 if (Op.getOpcode() == ISD::SHL &&
16191 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16192 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16193 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16194 SmallVector<SDValue, 8> Elts;
16195 EVT SVT = VT.getScalarType();
16196 unsigned SVTBits = SVT.getSizeInBits();
16197 const APInt &One = APInt(SVTBits, 1);
16198 unsigned NumElems = VT.getVectorNumElements();
16200 for (unsigned i=0; i !=NumElems; ++i) {
16201 SDValue Op = Amt->getOperand(i);
16202 if (Op->getOpcode() == ISD::UNDEF) {
16203 Elts.push_back(Op);
16207 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16208 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16209 uint64_t ShAmt = C.getZExtValue();
16210 if (ShAmt >= SVTBits) {
16211 Elts.push_back(DAG.getUNDEF(SVT));
16214 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16216 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16217 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16220 // Lower SHL with variable shift amount.
16221 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16222 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16224 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16225 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16226 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16227 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16230 // If possible, lower this shift as a sequence of two shifts by
16231 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16233 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16235 // Could be rewritten as:
16236 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16238 // The advantage is that the two shifts from the example would be
16239 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16240 // the vector shift into four scalar shifts plus four pairs of vector
16242 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16243 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16244 unsigned TargetOpcode = X86ISD::MOVSS;
16245 bool CanBeSimplified;
16246 // The splat value for the first packed shift (the 'X' from the example).
16247 SDValue Amt1 = Amt->getOperand(0);
16248 // The splat value for the second packed shift (the 'Y' from the example).
16249 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16250 Amt->getOperand(2);
16252 // See if it is possible to replace this node with a sequence of
16253 // two shifts followed by a MOVSS/MOVSD
16254 if (VT == MVT::v4i32) {
16255 // Check if it is legal to use a MOVSS.
16256 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16257 Amt2 == Amt->getOperand(3);
16258 if (!CanBeSimplified) {
16259 // Otherwise, check if we can still simplify this node using a MOVSD.
16260 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16261 Amt->getOperand(2) == Amt->getOperand(3);
16262 TargetOpcode = X86ISD::MOVSD;
16263 Amt2 = Amt->getOperand(2);
16266 // Do similar checks for the case where the machine value type
16268 CanBeSimplified = Amt1 == Amt->getOperand(1);
16269 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16270 CanBeSimplified = Amt2 == Amt->getOperand(i);
16272 if (!CanBeSimplified) {
16273 TargetOpcode = X86ISD::MOVSD;
16274 CanBeSimplified = true;
16275 Amt2 = Amt->getOperand(4);
16276 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16277 CanBeSimplified = Amt1 == Amt->getOperand(i);
16278 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16279 CanBeSimplified = Amt2 == Amt->getOperand(j);
16283 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16284 isa<ConstantSDNode>(Amt2)) {
16285 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16286 EVT CastVT = MVT::v4i32;
16288 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16289 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16291 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16292 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16293 if (TargetOpcode == X86ISD::MOVSD)
16294 CastVT = MVT::v2i64;
16295 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16296 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16297 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16299 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16303 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16304 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16307 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16308 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16310 // Turn 'a' into a mask suitable for VSELECT
16311 SDValue VSelM = DAG.getConstant(0x80, VT);
16312 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16313 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16315 SDValue CM1 = DAG.getConstant(0x0f, VT);
16316 SDValue CM2 = DAG.getConstant(0x3f, VT);
16318 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16319 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16320 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16321 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16322 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16325 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16326 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16327 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16329 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16330 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16331 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16332 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16333 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16336 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16337 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16338 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16340 // return VSELECT(r, r+r, a);
16341 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16342 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16346 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16347 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16348 // solution better.
16349 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16350 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16352 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16353 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16354 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16355 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16356 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16359 // Decompose 256-bit shifts into smaller 128-bit shifts.
16360 if (VT.is256BitVector()) {
16361 unsigned NumElems = VT.getVectorNumElements();
16362 MVT EltVT = VT.getVectorElementType();
16363 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16365 // Extract the two vectors
16366 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16367 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16369 // Recreate the shift amount vectors
16370 SDValue Amt1, Amt2;
16371 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16372 // Constant shift amount
16373 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16374 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16375 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16377 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16378 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16380 // Variable shift amount
16381 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16382 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16385 // Issue new vector shifts for the smaller types
16386 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16387 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16389 // Concatenate the result back
16390 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16396 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16397 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16398 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16399 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16400 // has only one use.
16401 SDNode *N = Op.getNode();
16402 SDValue LHS = N->getOperand(0);
16403 SDValue RHS = N->getOperand(1);
16404 unsigned BaseOp = 0;
16407 switch (Op.getOpcode()) {
16408 default: llvm_unreachable("Unknown ovf instruction!");
16410 // A subtract of one will be selected as a INC. Note that INC doesn't
16411 // set CF, so we can't do this for UADDO.
16412 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16414 BaseOp = X86ISD::INC;
16415 Cond = X86::COND_O;
16418 BaseOp = X86ISD::ADD;
16419 Cond = X86::COND_O;
16422 BaseOp = X86ISD::ADD;
16423 Cond = X86::COND_B;
16426 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16427 // set CF, so we can't do this for USUBO.
16428 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16430 BaseOp = X86ISD::DEC;
16431 Cond = X86::COND_O;
16434 BaseOp = X86ISD::SUB;
16435 Cond = X86::COND_O;
16438 BaseOp = X86ISD::SUB;
16439 Cond = X86::COND_B;
16442 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16443 Cond = X86::COND_O;
16445 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16446 if (N->getValueType(0) == MVT::i8) {
16447 BaseOp = X86ISD::UMUL8;
16448 Cond = X86::COND_O;
16451 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16453 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16456 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16457 DAG.getConstant(X86::COND_O, MVT::i32),
16458 SDValue(Sum.getNode(), 2));
16460 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16464 // Also sets EFLAGS.
16465 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16466 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16469 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16470 DAG.getConstant(Cond, MVT::i32),
16471 SDValue(Sum.getNode(), 1));
16473 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16476 /// Returns true if the operand type is exactly twice the native width, and
16477 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16478 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16479 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16480 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16481 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16484 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16485 else if (OpWidth == 128)
16486 return Subtarget->hasCmpxchg16b();
16491 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16492 return needsCmpXchgNb(SI->getValueOperand()->getType());
16495 // Note: this turns large loads into lock cmpxchg8b/16b.
16496 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16497 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16498 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16499 return needsCmpXchgNb(PTy->getElementType());
16502 TargetLoweringBase::AtomicRMWExpansionKind
16503 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16504 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16505 const Type *MemType = AI->getType();
16507 // If the operand is too big, we must see if cmpxchg8/16b is available
16508 // and default to library calls otherwise.
16509 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16510 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16511 : AtomicRMWExpansionKind::None;
16514 AtomicRMWInst::BinOp Op = AI->getOperation();
16517 llvm_unreachable("Unknown atomic operation");
16518 case AtomicRMWInst::Xchg:
16519 case AtomicRMWInst::Add:
16520 case AtomicRMWInst::Sub:
16521 // It's better to use xadd, xsub or xchg for these in all cases.
16522 return AtomicRMWExpansionKind::None;
16523 case AtomicRMWInst::Or:
16524 case AtomicRMWInst::And:
16525 case AtomicRMWInst::Xor:
16526 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16527 // prefix to a normal instruction for these operations.
16528 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16529 : AtomicRMWExpansionKind::None;
16530 case AtomicRMWInst::Nand:
16531 case AtomicRMWInst::Max:
16532 case AtomicRMWInst::Min:
16533 case AtomicRMWInst::UMax:
16534 case AtomicRMWInst::UMin:
16535 // These always require a non-trivial set of data operations on x86. We must
16536 // use a cmpxchg loop.
16537 return AtomicRMWExpansionKind::CmpXChg;
16541 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16542 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16543 // no-sse2). There isn't any reason to disable it if the target processor
16545 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16549 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16550 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16551 const Type *MemType = AI->getType();
16552 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16553 // there is no benefit in turning such RMWs into loads, and it is actually
16554 // harmful as it introduces a mfence.
16555 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16558 auto Builder = IRBuilder<>(AI);
16559 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16560 auto SynchScope = AI->getSynchScope();
16561 // We must restrict the ordering to avoid generating loads with Release or
16562 // ReleaseAcquire orderings.
16563 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16564 auto Ptr = AI->getPointerOperand();
16566 // Before the load we need a fence. Here is an example lifted from
16567 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16570 // x.store(1, relaxed);
16571 // r1 = y.fetch_add(0, release);
16573 // y.fetch_add(42, acquire);
16574 // r2 = x.load(relaxed);
16575 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16576 // lowered to just a load without a fence. A mfence flushes the store buffer,
16577 // making the optimization clearly correct.
16578 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16579 // otherwise, we might be able to be more agressive on relaxed idempotent
16580 // rmw. In practice, they do not look useful, so we don't try to be
16581 // especially clever.
16582 if (SynchScope == SingleThread) {
16583 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16584 // the IR level, so we must wrap it in an intrinsic.
16586 } else if (hasMFENCE(*Subtarget)) {
16587 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16588 Intrinsic::x86_sse2_mfence);
16589 Builder.CreateCall(MFence);
16591 // FIXME: it might make sense to use a locked operation here but on a
16592 // different cache-line to prevent cache-line bouncing. In practice it
16593 // is probably a small win, and x86 processors without mfence are rare
16594 // enough that we do not bother.
16598 // Finally we can emit the atomic load.
16599 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16600 AI->getType()->getPrimitiveSizeInBits());
16601 Loaded->setAtomic(Order, SynchScope);
16602 AI->replaceAllUsesWith(Loaded);
16603 AI->eraseFromParent();
16607 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16608 SelectionDAG &DAG) {
16610 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16611 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16612 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16613 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16615 // The only fence that needs an instruction is a sequentially-consistent
16616 // cross-thread fence.
16617 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16618 if (hasMFENCE(*Subtarget))
16619 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16621 SDValue Chain = Op.getOperand(0);
16622 SDValue Zero = DAG.getConstant(0, MVT::i32);
16624 DAG.getRegister(X86::ESP, MVT::i32), // Base
16625 DAG.getTargetConstant(1, MVT::i8), // Scale
16626 DAG.getRegister(0, MVT::i32), // Index
16627 DAG.getTargetConstant(0, MVT::i32), // Disp
16628 DAG.getRegister(0, MVT::i32), // Segment.
16632 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16633 return SDValue(Res, 0);
16636 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16637 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16640 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16641 SelectionDAG &DAG) {
16642 MVT T = Op.getSimpleValueType();
16646 switch(T.SimpleTy) {
16647 default: llvm_unreachable("Invalid value type!");
16648 case MVT::i8: Reg = X86::AL; size = 1; break;
16649 case MVT::i16: Reg = X86::AX; size = 2; break;
16650 case MVT::i32: Reg = X86::EAX; size = 4; break;
16652 assert(Subtarget->is64Bit() && "Node not type legal!");
16653 Reg = X86::RAX; size = 8;
16656 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16657 Op.getOperand(2), SDValue());
16658 SDValue Ops[] = { cpIn.getValue(0),
16661 DAG.getTargetConstant(size, MVT::i8),
16662 cpIn.getValue(1) };
16663 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16664 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16665 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16669 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16670 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16671 MVT::i32, cpOut.getValue(2));
16672 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16673 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16675 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16676 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16677 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16681 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16682 SelectionDAG &DAG) {
16683 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16684 MVT DstVT = Op.getSimpleValueType();
16686 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16687 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16688 if (DstVT != MVT::f64)
16689 // This conversion needs to be expanded.
16692 SDValue InVec = Op->getOperand(0);
16694 unsigned NumElts = SrcVT.getVectorNumElements();
16695 EVT SVT = SrcVT.getVectorElementType();
16697 // Widen the vector in input in the case of MVT::v2i32.
16698 // Example: from MVT::v2i32 to MVT::v4i32.
16699 SmallVector<SDValue, 16> Elts;
16700 for (unsigned i = 0, e = NumElts; i != e; ++i)
16701 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16702 DAG.getIntPtrConstant(i)));
16704 // Explicitly mark the extra elements as Undef.
16705 Elts.append(NumElts, DAG.getUNDEF(SVT));
16707 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16708 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16709 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16710 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16711 DAG.getIntPtrConstant(0));
16714 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16715 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16716 assert((DstVT == MVT::i64 ||
16717 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16718 "Unexpected custom BITCAST");
16719 // i64 <=> MMX conversions are Legal.
16720 if (SrcVT==MVT::i64 && DstVT.isVector())
16722 if (DstVT==MVT::i64 && SrcVT.isVector())
16724 // MMX <=> MMX conversions are Legal.
16725 if (SrcVT.isVector() && DstVT.isVector())
16727 // All other conversions need to be expanded.
16731 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
16732 SelectionDAG &DAG) {
16733 SDNode *Node = Op.getNode();
16736 Op = Op.getOperand(0);
16737 EVT VT = Op.getValueType();
16738 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16739 "CTPOP lowering only implemented for 128/256-bit wide vector types");
16741 unsigned NumElts = VT.getVectorNumElements();
16742 EVT EltVT = VT.getVectorElementType();
16743 unsigned Len = EltVT.getSizeInBits();
16745 // This is the vectorized version of the "best" algorithm from
16746 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
16747 // with a minor tweak to use a series of adds + shifts instead of vector
16748 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
16750 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
16751 // v8i32 => Always profitable
16753 // FIXME: There a couple of possible improvements:
16755 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
16756 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
16758 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
16759 "CTPOP not implemented for this vector element type.");
16761 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
16762 // extra legalization.
16763 bool NeedsBitcast = EltVT == MVT::i32;
16764 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
16766 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
16767 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
16768 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
16770 // v = v - ((v >> 1) & 0x55555555...)
16771 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
16772 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
16773 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
16775 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16777 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
16778 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
16780 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
16782 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
16783 if (VT != And.getValueType())
16784 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16785 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
16787 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
16788 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
16789 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
16790 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
16791 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
16793 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
16794 if (NeedsBitcast) {
16795 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
16796 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
16797 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
16800 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
16801 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
16802 if (VT != AndRHS.getValueType()) {
16803 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
16804 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
16806 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
16808 // v = (v + (v >> 4)) & 0x0F0F0F0F...
16809 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
16810 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
16811 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
16812 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16814 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
16815 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
16816 if (NeedsBitcast) {
16817 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16818 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
16820 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
16821 if (VT != And.getValueType())
16822 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16824 // The algorithm mentioned above uses:
16825 // v = (v * 0x01010101...) >> (Len - 8)
16827 // Change it to use vector adds + vector shifts which yield faster results on
16828 // Haswell than using vector integer multiplication.
16830 // For i32 elements:
16831 // v = v + (v >> 8)
16832 // v = v + (v >> 16)
16834 // For i64 elements:
16835 // v = v + (v >> 8)
16836 // v = v + (v >> 16)
16837 // v = v + (v >> 32)
16840 SmallVector<SDValue, 8> Csts;
16841 for (unsigned i = 8; i <= Len/2; i *= 2) {
16842 Csts.assign(NumElts, DAG.getConstant(i, EltVT));
16843 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
16844 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
16845 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
16849 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
16850 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
16851 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
16852 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
16853 if (NeedsBitcast) {
16854 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
16855 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
16857 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
16858 if (VT != And.getValueType())
16859 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
16864 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16865 SDNode *Node = Op.getNode();
16867 EVT T = Node->getValueType(0);
16868 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16869 DAG.getConstant(0, T), Node->getOperand(2));
16870 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16871 cast<AtomicSDNode>(Node)->getMemoryVT(),
16872 Node->getOperand(0),
16873 Node->getOperand(1), negOp,
16874 cast<AtomicSDNode>(Node)->getMemOperand(),
16875 cast<AtomicSDNode>(Node)->getOrdering(),
16876 cast<AtomicSDNode>(Node)->getSynchScope());
16879 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16880 SDNode *Node = Op.getNode();
16882 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16884 // Convert seq_cst store -> xchg
16885 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16886 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16887 // (The only way to get a 16-byte store is cmpxchg16b)
16888 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16889 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16890 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16891 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16892 cast<AtomicSDNode>(Node)->getMemoryVT(),
16893 Node->getOperand(0),
16894 Node->getOperand(1), Node->getOperand(2),
16895 cast<AtomicSDNode>(Node)->getMemOperand(),
16896 cast<AtomicSDNode>(Node)->getOrdering(),
16897 cast<AtomicSDNode>(Node)->getSynchScope());
16898 return Swap.getValue(1);
16900 // Other atomic stores have a simple pattern.
16904 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16905 EVT VT = Op.getNode()->getSimpleValueType(0);
16907 // Let legalize expand this if it isn't a legal type yet.
16908 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16911 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16914 bool ExtraOp = false;
16915 switch (Op.getOpcode()) {
16916 default: llvm_unreachable("Invalid code");
16917 case ISD::ADDC: Opc = X86ISD::ADD; break;
16918 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16919 case ISD::SUBC: Opc = X86ISD::SUB; break;
16920 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16924 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16926 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16927 Op.getOperand(1), Op.getOperand(2));
16930 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16931 SelectionDAG &DAG) {
16932 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16934 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16935 // which returns the values as { float, float } (in XMM0) or
16936 // { double, double } (which is returned in XMM0, XMM1).
16938 SDValue Arg = Op.getOperand(0);
16939 EVT ArgVT = Arg.getValueType();
16940 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16942 TargetLowering::ArgListTy Args;
16943 TargetLowering::ArgListEntry Entry;
16947 Entry.isSExt = false;
16948 Entry.isZExt = false;
16949 Args.push_back(Entry);
16951 bool isF64 = ArgVT == MVT::f64;
16952 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16953 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16954 // the results are returned via SRet in memory.
16955 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16956 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16957 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16959 Type *RetTy = isF64
16960 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
16961 : (Type*)VectorType::get(ArgTy, 4);
16963 TargetLowering::CallLoweringInfo CLI(DAG);
16964 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16965 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16967 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16970 // Returned in xmm0 and xmm1.
16971 return CallResult.first;
16973 // Returned in bits 0:31 and 32:64 xmm0.
16974 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16975 CallResult.first, DAG.getIntPtrConstant(0));
16976 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16977 CallResult.first, DAG.getIntPtrConstant(1));
16978 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16979 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16982 /// LowerOperation - Provide custom lowering hooks for some operations.
16984 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16985 switch (Op.getOpcode()) {
16986 default: llvm_unreachable("Should not custom lower this!");
16987 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16988 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16989 return LowerCMP_SWAP(Op, Subtarget, DAG);
16990 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
16991 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16992 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16993 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16994 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
16995 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
16996 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16997 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16998 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16999 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17000 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17001 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17002 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17003 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17004 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17005 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17006 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17007 case ISD::SHL_PARTS:
17008 case ISD::SRA_PARTS:
17009 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17010 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17011 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17012 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17013 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17014 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17015 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17016 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17017 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17018 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17019 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17021 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17022 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17023 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17024 case ISD::SETCC: return LowerSETCC(Op, DAG);
17025 case ISD::SELECT: return LowerSELECT(Op, DAG);
17026 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17027 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17028 case ISD::VASTART: return LowerVASTART(Op, DAG);
17029 case ISD::VAARG: return LowerVAARG(Op, DAG);
17030 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17031 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17032 case ISD::INTRINSIC_VOID:
17033 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17034 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17035 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17036 case ISD::FRAME_TO_ARGS_OFFSET:
17037 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17038 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17039 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17040 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17041 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17042 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17043 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17044 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17045 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17046 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17047 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17048 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17049 case ISD::UMUL_LOHI:
17050 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17053 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17059 case ISD::UMULO: return LowerXALUO(Op, DAG);
17060 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17061 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17065 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17066 case ISD::ADD: return LowerADD(Op, DAG);
17067 case ISD::SUB: return LowerSUB(Op, DAG);
17068 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17072 /// ReplaceNodeResults - Replace a node with an illegal result type
17073 /// with a new node built out of custom code.
17074 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17075 SmallVectorImpl<SDValue>&Results,
17076 SelectionDAG &DAG) const {
17078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17079 switch (N->getOpcode()) {
17081 llvm_unreachable("Do not know how to custom type legalize this operation!");
17082 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17083 case X86ISD::FMINC:
17085 case X86ISD::FMAXC:
17086 case X86ISD::FMAX: {
17087 EVT VT = N->getValueType(0);
17088 if (VT != MVT::v2f32)
17089 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17090 SDValue UNDEF = DAG.getUNDEF(VT);
17091 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17092 N->getOperand(0), UNDEF);
17093 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17094 N->getOperand(1), UNDEF);
17095 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17098 case ISD::SIGN_EXTEND_INREG:
17103 // We don't want to expand or promote these.
17110 case ISD::UDIVREM: {
17111 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17112 Results.push_back(V);
17115 case ISD::FP_TO_SINT:
17116 case ISD::FP_TO_UINT: {
17117 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17119 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17122 std::pair<SDValue,SDValue> Vals =
17123 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17124 SDValue FIST = Vals.first, StackSlot = Vals.second;
17125 if (FIST.getNode()) {
17126 EVT VT = N->getValueType(0);
17127 // Return a load from the stack slot.
17128 if (StackSlot.getNode())
17129 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17130 MachinePointerInfo(),
17131 false, false, false, 0));
17133 Results.push_back(FIST);
17137 case ISD::UINT_TO_FP: {
17138 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17139 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17140 N->getValueType(0) != MVT::v2f32)
17142 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17144 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17146 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17147 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17148 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17149 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17150 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17151 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17154 case ISD::FP_ROUND: {
17155 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17157 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17158 Results.push_back(V);
17161 case ISD::INTRINSIC_W_CHAIN: {
17162 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17164 default : llvm_unreachable("Do not know how to custom type "
17165 "legalize this intrinsic operation!");
17166 case Intrinsic::x86_rdtsc:
17167 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17169 case Intrinsic::x86_rdtscp:
17170 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17172 case Intrinsic::x86_rdpmc:
17173 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17176 case ISD::READCYCLECOUNTER: {
17177 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17180 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17181 EVT T = N->getValueType(0);
17182 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17183 bool Regs64bit = T == MVT::i128;
17184 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17185 SDValue cpInL, cpInH;
17186 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17187 DAG.getConstant(0, HalfT));
17188 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17189 DAG.getConstant(1, HalfT));
17190 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17191 Regs64bit ? X86::RAX : X86::EAX,
17193 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17194 Regs64bit ? X86::RDX : X86::EDX,
17195 cpInH, cpInL.getValue(1));
17196 SDValue swapInL, swapInH;
17197 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17198 DAG.getConstant(0, HalfT));
17199 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17200 DAG.getConstant(1, HalfT));
17201 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17202 Regs64bit ? X86::RBX : X86::EBX,
17203 swapInL, cpInH.getValue(1));
17204 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17205 Regs64bit ? X86::RCX : X86::ECX,
17206 swapInH, swapInL.getValue(1));
17207 SDValue Ops[] = { swapInH.getValue(0),
17209 swapInH.getValue(1) };
17210 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17211 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17212 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17213 X86ISD::LCMPXCHG8_DAG;
17214 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17215 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17216 Regs64bit ? X86::RAX : X86::EAX,
17217 HalfT, Result.getValue(1));
17218 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17219 Regs64bit ? X86::RDX : X86::EDX,
17220 HalfT, cpOutL.getValue(2));
17221 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17223 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17224 MVT::i32, cpOutH.getValue(2));
17226 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17227 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17228 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17230 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17231 Results.push_back(Success);
17232 Results.push_back(EFLAGS.getValue(1));
17235 case ISD::ATOMIC_SWAP:
17236 case ISD::ATOMIC_LOAD_ADD:
17237 case ISD::ATOMIC_LOAD_SUB:
17238 case ISD::ATOMIC_LOAD_AND:
17239 case ISD::ATOMIC_LOAD_OR:
17240 case ISD::ATOMIC_LOAD_XOR:
17241 case ISD::ATOMIC_LOAD_NAND:
17242 case ISD::ATOMIC_LOAD_MIN:
17243 case ISD::ATOMIC_LOAD_MAX:
17244 case ISD::ATOMIC_LOAD_UMIN:
17245 case ISD::ATOMIC_LOAD_UMAX:
17246 case ISD::ATOMIC_LOAD: {
17247 // Delegate to generic TypeLegalization. Situations we can really handle
17248 // should have already been dealt with by AtomicExpandPass.cpp.
17251 case ISD::BITCAST: {
17252 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17253 EVT DstVT = N->getValueType(0);
17254 EVT SrcVT = N->getOperand(0)->getValueType(0);
17256 if (SrcVT != MVT::f64 ||
17257 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17260 unsigned NumElts = DstVT.getVectorNumElements();
17261 EVT SVT = DstVT.getVectorElementType();
17262 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17263 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17264 MVT::v2f64, N->getOperand(0));
17265 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17267 if (ExperimentalVectorWideningLegalization) {
17268 // If we are legalizing vectors by widening, we already have the desired
17269 // legal vector type, just return it.
17270 Results.push_back(ToVecInt);
17274 SmallVector<SDValue, 8> Elts;
17275 for (unsigned i = 0, e = NumElts; i != e; ++i)
17276 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17277 ToVecInt, DAG.getIntPtrConstant(i)));
17279 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17284 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17286 default: return nullptr;
17287 case X86ISD::BSF: return "X86ISD::BSF";
17288 case X86ISD::BSR: return "X86ISD::BSR";
17289 case X86ISD::SHLD: return "X86ISD::SHLD";
17290 case X86ISD::SHRD: return "X86ISD::SHRD";
17291 case X86ISD::FAND: return "X86ISD::FAND";
17292 case X86ISD::FANDN: return "X86ISD::FANDN";
17293 case X86ISD::FOR: return "X86ISD::FOR";
17294 case X86ISD::FXOR: return "X86ISD::FXOR";
17295 case X86ISD::FSRL: return "X86ISD::FSRL";
17296 case X86ISD::FILD: return "X86ISD::FILD";
17297 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17298 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17299 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17300 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17301 case X86ISD::FLD: return "X86ISD::FLD";
17302 case X86ISD::FST: return "X86ISD::FST";
17303 case X86ISD::CALL: return "X86ISD::CALL";
17304 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17305 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17306 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17307 case X86ISD::BT: return "X86ISD::BT";
17308 case X86ISD::CMP: return "X86ISD::CMP";
17309 case X86ISD::COMI: return "X86ISD::COMI";
17310 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17311 case X86ISD::CMPM: return "X86ISD::CMPM";
17312 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17313 case X86ISD::SETCC: return "X86ISD::SETCC";
17314 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17315 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17316 case X86ISD::CMOV: return "X86ISD::CMOV";
17317 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17318 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17319 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17320 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17321 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17322 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17323 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17324 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17325 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17326 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17327 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17328 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17329 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17330 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17331 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17332 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17333 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17334 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17335 case X86ISD::HADD: return "X86ISD::HADD";
17336 case X86ISD::HSUB: return "X86ISD::HSUB";
17337 case X86ISD::FHADD: return "X86ISD::FHADD";
17338 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17339 case X86ISD::UMAX: return "X86ISD::UMAX";
17340 case X86ISD::UMIN: return "X86ISD::UMIN";
17341 case X86ISD::SMAX: return "X86ISD::SMAX";
17342 case X86ISD::SMIN: return "X86ISD::SMIN";
17343 case X86ISD::FMAX: return "X86ISD::FMAX";
17344 case X86ISD::FMIN: return "X86ISD::FMIN";
17345 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17346 case X86ISD::FMINC: return "X86ISD::FMINC";
17347 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17348 case X86ISD::FRCP: return "X86ISD::FRCP";
17349 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17350 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17351 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17352 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17353 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17354 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17355 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17356 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17357 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17358 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17359 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17360 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17361 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17362 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17363 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17364 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17365 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17366 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17367 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17368 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17369 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17370 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17371 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17372 case X86ISD::VSHL: return "X86ISD::VSHL";
17373 case X86ISD::VSRL: return "X86ISD::VSRL";
17374 case X86ISD::VSRA: return "X86ISD::VSRA";
17375 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17376 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17377 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17378 case X86ISD::CMPP: return "X86ISD::CMPP";
17379 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17380 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17381 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17382 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17383 case X86ISD::ADD: return "X86ISD::ADD";
17384 case X86ISD::SUB: return "X86ISD::SUB";
17385 case X86ISD::ADC: return "X86ISD::ADC";
17386 case X86ISD::SBB: return "X86ISD::SBB";
17387 case X86ISD::SMUL: return "X86ISD::SMUL";
17388 case X86ISD::UMUL: return "X86ISD::UMUL";
17389 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17390 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17391 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17392 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17393 case X86ISD::INC: return "X86ISD::INC";
17394 case X86ISD::DEC: return "X86ISD::DEC";
17395 case X86ISD::OR: return "X86ISD::OR";
17396 case X86ISD::XOR: return "X86ISD::XOR";
17397 case X86ISD::AND: return "X86ISD::AND";
17398 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17399 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17400 case X86ISD::PTEST: return "X86ISD::PTEST";
17401 case X86ISD::TESTP: return "X86ISD::TESTP";
17402 case X86ISD::TESTM: return "X86ISD::TESTM";
17403 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17404 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17405 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17406 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17407 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17408 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17409 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17410 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17411 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17412 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17413 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17414 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17415 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17416 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17417 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17418 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17419 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17420 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17421 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17422 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17423 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17424 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17425 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17426 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17427 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17428 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17429 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17430 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17431 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17432 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17433 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17434 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17435 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17436 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17437 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17438 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17439 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17440 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17441 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17442 case X86ISD::SAHF: return "X86ISD::SAHF";
17443 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17444 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17445 case X86ISD::FMADD: return "X86ISD::FMADD";
17446 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17447 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17448 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17449 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17450 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17451 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17452 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17453 case X86ISD::XTEST: return "X86ISD::XTEST";
17454 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17455 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17456 case X86ISD::SELECT: return "X86ISD::SELECT";
17457 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17458 case X86ISD::RCP28: return "X86ISD::RCP28";
17459 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17460 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17461 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17462 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17463 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17467 // isLegalAddressingMode - Return true if the addressing mode represented
17468 // by AM is legal for this target, for a load/store of the specified type.
17469 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17471 // X86 supports extremely general addressing modes.
17472 CodeModel::Model M = getTargetMachine().getCodeModel();
17473 Reloc::Model R = getTargetMachine().getRelocationModel();
17475 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17476 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17481 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17483 // If a reference to this global requires an extra load, we can't fold it.
17484 if (isGlobalStubReference(GVFlags))
17487 // If BaseGV requires a register for the PIC base, we cannot also have a
17488 // BaseReg specified.
17489 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17492 // If lower 4G is not available, then we must use rip-relative addressing.
17493 if ((M != CodeModel::Small || R != Reloc::Static) &&
17494 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17498 switch (AM.Scale) {
17504 // These scales always work.
17509 // These scales are formed with basereg+scalereg. Only accept if there is
17514 default: // Other stuff never works.
17521 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17522 unsigned Bits = Ty->getScalarSizeInBits();
17524 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17525 // particularly cheaper than those without.
17529 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17530 // variable shifts just as cheap as scalar ones.
17531 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17534 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17535 // fully general vector.
17539 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17540 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17542 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17543 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17544 return NumBits1 > NumBits2;
17547 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17548 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17551 if (!isTypeLegal(EVT::getEVT(Ty1)))
17554 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17556 // Assuming the caller doesn't have a zeroext or signext return parameter,
17557 // truncation all the way down to i1 is valid.
17561 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17562 return isInt<32>(Imm);
17565 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17566 // Can also use sub to handle negated immediates.
17567 return isInt<32>(Imm);
17570 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17571 if (!VT1.isInteger() || !VT2.isInteger())
17573 unsigned NumBits1 = VT1.getSizeInBits();
17574 unsigned NumBits2 = VT2.getSizeInBits();
17575 return NumBits1 > NumBits2;
17578 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17579 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17580 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17583 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17584 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17585 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17588 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17589 EVT VT1 = Val.getValueType();
17590 if (isZExtFree(VT1, VT2))
17593 if (Val.getOpcode() != ISD::LOAD)
17596 if (!VT1.isSimple() || !VT1.isInteger() ||
17597 !VT2.isSimple() || !VT2.isInteger())
17600 switch (VT1.getSimpleVT().SimpleTy) {
17605 // X86 has 8, 16, and 32-bit zero-extending loads.
17612 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17615 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17616 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17619 VT = VT.getScalarType();
17621 if (!VT.isSimple())
17624 switch (VT.getSimpleVT().SimpleTy) {
17635 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17636 // i16 instructions are longer (0x66 prefix) and potentially slower.
17637 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17640 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17641 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17642 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17643 /// are assumed to be legal.
17645 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17647 if (!VT.isSimple())
17650 // Very little shuffling can be done for 64-bit vectors right now.
17651 if (VT.getSizeInBits() == 64)
17654 // We only care that the types being shuffled are legal. The lowering can
17655 // handle any possible shuffle mask that results.
17656 return isTypeLegal(VT.getSimpleVT());
17660 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17662 // Just delegate to the generic legality, clear masks aren't special.
17663 return isShuffleMaskLegal(Mask, VT);
17666 //===----------------------------------------------------------------------===//
17667 // X86 Scheduler Hooks
17668 //===----------------------------------------------------------------------===//
17670 /// Utility function to emit xbegin specifying the start of an RTM region.
17671 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17672 const TargetInstrInfo *TII) {
17673 DebugLoc DL = MI->getDebugLoc();
17675 const BasicBlock *BB = MBB->getBasicBlock();
17676 MachineFunction::iterator I = MBB;
17679 // For the v = xbegin(), we generate
17690 MachineBasicBlock *thisMBB = MBB;
17691 MachineFunction *MF = MBB->getParent();
17692 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17693 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17694 MF->insert(I, mainMBB);
17695 MF->insert(I, sinkMBB);
17697 // Transfer the remainder of BB and its successor edges to sinkMBB.
17698 sinkMBB->splice(sinkMBB->begin(), MBB,
17699 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17700 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17704 // # fallthrough to mainMBB
17705 // # abortion to sinkMBB
17706 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17707 thisMBB->addSuccessor(mainMBB);
17708 thisMBB->addSuccessor(sinkMBB);
17712 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17713 mainMBB->addSuccessor(sinkMBB);
17716 // EAX is live into the sinkMBB
17717 sinkMBB->addLiveIn(X86::EAX);
17718 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17719 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17722 MI->eraseFromParent();
17726 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17727 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17728 // in the .td file.
17729 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17730 const TargetInstrInfo *TII) {
17732 switch (MI->getOpcode()) {
17733 default: llvm_unreachable("illegal opcode!");
17734 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17735 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17736 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17737 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17738 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17739 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17740 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17741 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17744 DebugLoc dl = MI->getDebugLoc();
17745 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17747 unsigned NumArgs = MI->getNumOperands();
17748 for (unsigned i = 1; i < NumArgs; ++i) {
17749 MachineOperand &Op = MI->getOperand(i);
17750 if (!(Op.isReg() && Op.isImplicit()))
17751 MIB.addOperand(Op);
17753 if (MI->hasOneMemOperand())
17754 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17756 BuildMI(*BB, MI, dl,
17757 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17758 .addReg(X86::XMM0);
17760 MI->eraseFromParent();
17764 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17765 // defs in an instruction pattern
17766 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17767 const TargetInstrInfo *TII) {
17769 switch (MI->getOpcode()) {
17770 default: llvm_unreachable("illegal opcode!");
17771 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17772 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17773 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17774 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17775 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17776 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17777 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17778 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17781 DebugLoc dl = MI->getDebugLoc();
17782 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17784 unsigned NumArgs = MI->getNumOperands(); // remove the results
17785 for (unsigned i = 1; i < NumArgs; ++i) {
17786 MachineOperand &Op = MI->getOperand(i);
17787 if (!(Op.isReg() && Op.isImplicit()))
17788 MIB.addOperand(Op);
17790 if (MI->hasOneMemOperand())
17791 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17793 BuildMI(*BB, MI, dl,
17794 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17797 MI->eraseFromParent();
17801 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17802 const X86Subtarget *Subtarget) {
17803 DebugLoc dl = MI->getDebugLoc();
17804 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17805 // Address into RAX/EAX, other two args into ECX, EDX.
17806 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17807 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17808 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17809 for (int i = 0; i < X86::AddrNumOperands; ++i)
17810 MIB.addOperand(MI->getOperand(i));
17812 unsigned ValOps = X86::AddrNumOperands;
17813 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17814 .addReg(MI->getOperand(ValOps).getReg());
17815 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17816 .addReg(MI->getOperand(ValOps+1).getReg());
17818 // The instruction doesn't actually take any operands though.
17819 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17821 MI->eraseFromParent(); // The pseudo is gone now.
17825 MachineBasicBlock *
17826 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
17827 MachineBasicBlock *MBB) const {
17828 // Emit va_arg instruction on X86-64.
17830 // Operands to this pseudo-instruction:
17831 // 0 ) Output : destination address (reg)
17832 // 1-5) Input : va_list address (addr, i64mem)
17833 // 6 ) ArgSize : Size (in bytes) of vararg type
17834 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17835 // 8 ) Align : Alignment of type
17836 // 9 ) EFLAGS (implicit-def)
17838 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17839 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17841 unsigned DestReg = MI->getOperand(0).getReg();
17842 MachineOperand &Base = MI->getOperand(1);
17843 MachineOperand &Scale = MI->getOperand(2);
17844 MachineOperand &Index = MI->getOperand(3);
17845 MachineOperand &Disp = MI->getOperand(4);
17846 MachineOperand &Segment = MI->getOperand(5);
17847 unsigned ArgSize = MI->getOperand(6).getImm();
17848 unsigned ArgMode = MI->getOperand(7).getImm();
17849 unsigned Align = MI->getOperand(8).getImm();
17851 // Memory Reference
17852 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17853 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17854 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17856 // Machine Information
17857 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17858 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17859 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17860 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17861 DebugLoc DL = MI->getDebugLoc();
17863 // struct va_list {
17866 // i64 overflow_area (address)
17867 // i64 reg_save_area (address)
17869 // sizeof(va_list) = 24
17870 // alignment(va_list) = 8
17872 unsigned TotalNumIntRegs = 6;
17873 unsigned TotalNumXMMRegs = 8;
17874 bool UseGPOffset = (ArgMode == 1);
17875 bool UseFPOffset = (ArgMode == 2);
17876 unsigned MaxOffset = TotalNumIntRegs * 8 +
17877 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17879 /* Align ArgSize to a multiple of 8 */
17880 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17881 bool NeedsAlign = (Align > 8);
17883 MachineBasicBlock *thisMBB = MBB;
17884 MachineBasicBlock *overflowMBB;
17885 MachineBasicBlock *offsetMBB;
17886 MachineBasicBlock *endMBB;
17888 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17889 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17890 unsigned OffsetReg = 0;
17892 if (!UseGPOffset && !UseFPOffset) {
17893 // If we only pull from the overflow region, we don't create a branch.
17894 // We don't need to alter control flow.
17895 OffsetDestReg = 0; // unused
17896 OverflowDestReg = DestReg;
17898 offsetMBB = nullptr;
17899 overflowMBB = thisMBB;
17902 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17903 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17904 // If not, pull from overflow_area. (branch to overflowMBB)
17909 // offsetMBB overflowMBB
17914 // Registers for the PHI in endMBB
17915 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17916 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17918 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17919 MachineFunction *MF = MBB->getParent();
17920 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17921 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17922 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17924 MachineFunction::iterator MBBIter = MBB;
17927 // Insert the new basic blocks
17928 MF->insert(MBBIter, offsetMBB);
17929 MF->insert(MBBIter, overflowMBB);
17930 MF->insert(MBBIter, endMBB);
17932 // Transfer the remainder of MBB and its successor edges to endMBB.
17933 endMBB->splice(endMBB->begin(), thisMBB,
17934 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17935 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17937 // Make offsetMBB and overflowMBB successors of thisMBB
17938 thisMBB->addSuccessor(offsetMBB);
17939 thisMBB->addSuccessor(overflowMBB);
17941 // endMBB is a successor of both offsetMBB and overflowMBB
17942 offsetMBB->addSuccessor(endMBB);
17943 overflowMBB->addSuccessor(endMBB);
17945 // Load the offset value into a register
17946 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17947 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17951 .addDisp(Disp, UseFPOffset ? 4 : 0)
17952 .addOperand(Segment)
17953 .setMemRefs(MMOBegin, MMOEnd);
17955 // Check if there is enough room left to pull this argument.
17956 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17958 .addImm(MaxOffset + 8 - ArgSizeA8);
17960 // Branch to "overflowMBB" if offset >= max
17961 // Fall through to "offsetMBB" otherwise
17962 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17963 .addMBB(overflowMBB);
17966 // In offsetMBB, emit code to use the reg_save_area.
17968 assert(OffsetReg != 0);
17970 // Read the reg_save_area address.
17971 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17972 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17977 .addOperand(Segment)
17978 .setMemRefs(MMOBegin, MMOEnd);
17980 // Zero-extend the offset
17981 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17982 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17985 .addImm(X86::sub_32bit);
17987 // Add the offset to the reg_save_area to get the final address.
17988 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17989 .addReg(OffsetReg64)
17990 .addReg(RegSaveReg);
17992 // Compute the offset for the next argument
17993 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17994 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17996 .addImm(UseFPOffset ? 16 : 8);
17998 // Store it back into the va_list.
17999 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18003 .addDisp(Disp, UseFPOffset ? 4 : 0)
18004 .addOperand(Segment)
18005 .addReg(NextOffsetReg)
18006 .setMemRefs(MMOBegin, MMOEnd);
18009 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18014 // Emit code to use overflow area
18017 // Load the overflow_area address into a register.
18018 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18019 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18024 .addOperand(Segment)
18025 .setMemRefs(MMOBegin, MMOEnd);
18027 // If we need to align it, do so. Otherwise, just copy the address
18028 // to OverflowDestReg.
18030 // Align the overflow address
18031 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18032 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18034 // aligned_addr = (addr + (align-1)) & ~(align-1)
18035 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18036 .addReg(OverflowAddrReg)
18039 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18041 .addImm(~(uint64_t)(Align-1));
18043 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18044 .addReg(OverflowAddrReg);
18047 // Compute the next overflow address after this argument.
18048 // (the overflow address should be kept 8-byte aligned)
18049 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18050 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18051 .addReg(OverflowDestReg)
18052 .addImm(ArgSizeA8);
18054 // Store the new overflow address.
18055 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18060 .addOperand(Segment)
18061 .addReg(NextAddrReg)
18062 .setMemRefs(MMOBegin, MMOEnd);
18064 // If we branched, emit the PHI to the front of endMBB.
18066 BuildMI(*endMBB, endMBB->begin(), DL,
18067 TII->get(X86::PHI), DestReg)
18068 .addReg(OffsetDestReg).addMBB(offsetMBB)
18069 .addReg(OverflowDestReg).addMBB(overflowMBB);
18072 // Erase the pseudo instruction
18073 MI->eraseFromParent();
18078 MachineBasicBlock *
18079 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18081 MachineBasicBlock *MBB) const {
18082 // Emit code to save XMM registers to the stack. The ABI says that the
18083 // number of registers to save is given in %al, so it's theoretically
18084 // possible to do an indirect jump trick to avoid saving all of them,
18085 // however this code takes a simpler approach and just executes all
18086 // of the stores if %al is non-zero. It's less code, and it's probably
18087 // easier on the hardware branch predictor, and stores aren't all that
18088 // expensive anyway.
18090 // Create the new basic blocks. One block contains all the XMM stores,
18091 // and one block is the final destination regardless of whether any
18092 // stores were performed.
18093 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18094 MachineFunction *F = MBB->getParent();
18095 MachineFunction::iterator MBBIter = MBB;
18097 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18098 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18099 F->insert(MBBIter, XMMSaveMBB);
18100 F->insert(MBBIter, EndMBB);
18102 // Transfer the remainder of MBB and its successor edges to EndMBB.
18103 EndMBB->splice(EndMBB->begin(), MBB,
18104 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18105 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18107 // The original block will now fall through to the XMM save block.
18108 MBB->addSuccessor(XMMSaveMBB);
18109 // The XMMSaveMBB will fall through to the end block.
18110 XMMSaveMBB->addSuccessor(EndMBB);
18112 // Now add the instructions.
18113 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18114 DebugLoc DL = MI->getDebugLoc();
18116 unsigned CountReg = MI->getOperand(0).getReg();
18117 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18118 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18120 if (!Subtarget->isTargetWin64()) {
18121 // If %al is 0, branch around the XMM save block.
18122 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18123 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18124 MBB->addSuccessor(EndMBB);
18127 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18128 // that was just emitted, but clearly shouldn't be "saved".
18129 assert((MI->getNumOperands() <= 3 ||
18130 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18131 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18132 && "Expected last argument to be EFLAGS");
18133 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18134 // In the XMM save block, save all the XMM argument registers.
18135 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18136 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18137 MachineMemOperand *MMO =
18138 F->getMachineMemOperand(
18139 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18140 MachineMemOperand::MOStore,
18141 /*Size=*/16, /*Align=*/16);
18142 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18143 .addFrameIndex(RegSaveFrameIndex)
18144 .addImm(/*Scale=*/1)
18145 .addReg(/*IndexReg=*/0)
18146 .addImm(/*Disp=*/Offset)
18147 .addReg(/*Segment=*/0)
18148 .addReg(MI->getOperand(i).getReg())
18149 .addMemOperand(MMO);
18152 MI->eraseFromParent(); // The pseudo instruction is gone now.
18157 // The EFLAGS operand of SelectItr might be missing a kill marker
18158 // because there were multiple uses of EFLAGS, and ISel didn't know
18159 // which to mark. Figure out whether SelectItr should have had a
18160 // kill marker, and set it if it should. Returns the correct kill
18162 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18163 MachineBasicBlock* BB,
18164 const TargetRegisterInfo* TRI) {
18165 // Scan forward through BB for a use/def of EFLAGS.
18166 MachineBasicBlock::iterator miI(std::next(SelectItr));
18167 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18168 const MachineInstr& mi = *miI;
18169 if (mi.readsRegister(X86::EFLAGS))
18171 if (mi.definesRegister(X86::EFLAGS))
18172 break; // Should have kill-flag - update below.
18175 // If we hit the end of the block, check whether EFLAGS is live into a
18177 if (miI == BB->end()) {
18178 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18179 sEnd = BB->succ_end();
18180 sItr != sEnd; ++sItr) {
18181 MachineBasicBlock* succ = *sItr;
18182 if (succ->isLiveIn(X86::EFLAGS))
18187 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18188 // out. SelectMI should have a kill flag on EFLAGS.
18189 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18193 MachineBasicBlock *
18194 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18195 MachineBasicBlock *BB) const {
18196 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18197 DebugLoc DL = MI->getDebugLoc();
18199 // To "insert" a SELECT_CC instruction, we actually have to insert the
18200 // diamond control-flow pattern. The incoming instruction knows the
18201 // destination vreg to set, the condition code register to branch on, the
18202 // true/false values to select between, and a branch opcode to use.
18203 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18204 MachineFunction::iterator It = BB;
18210 // cmpTY ccX, r1, r2
18212 // fallthrough --> copy0MBB
18213 MachineBasicBlock *thisMBB = BB;
18214 MachineFunction *F = BB->getParent();
18216 // We also lower double CMOVs:
18217 // (CMOV (CMOV F, T, cc1), T, cc2)
18218 // to two successives branches. For that, we look for another CMOV as the
18219 // following instruction.
18221 // Without this, we would add a PHI between the two jumps, which ends up
18222 // creating a few copies all around. For instance, for
18224 // (sitofp (zext (fcmp une)))
18226 // we would generate:
18228 // ucomiss %xmm1, %xmm0
18229 // movss <1.0f>, %xmm0
18230 // movaps %xmm0, %xmm1
18232 // xorps %xmm1, %xmm1
18235 // movaps %xmm1, %xmm0
18239 // because this custom-inserter would have generated:
18251 // A: X = ...; Y = ...
18253 // C: Z = PHI [X, A], [Y, B]
18255 // E: PHI [X, C], [Z, D]
18257 // If we lower both CMOVs in a single step, we can instead generate:
18269 // A: X = ...; Y = ...
18271 // E: PHI [X, A], [X, C], [Y, D]
18273 // Which, in our sitofp/fcmp example, gives us something like:
18275 // ucomiss %xmm1, %xmm0
18276 // movss <1.0f>, %xmm0
18279 // xorps %xmm0, %xmm0
18283 MachineInstr *NextCMOV = nullptr;
18284 MachineBasicBlock::iterator NextMIIt =
18285 std::next(MachineBasicBlock::iterator(MI));
18286 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18287 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18288 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18289 NextCMOV = &*NextMIIt;
18291 MachineBasicBlock *jcc1MBB = nullptr;
18293 // If we have a double CMOV, we lower it to two successive branches to
18294 // the same block. EFLAGS is used by both, so mark it as live in the second.
18296 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18297 F->insert(It, jcc1MBB);
18298 jcc1MBB->addLiveIn(X86::EFLAGS);
18301 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18302 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18303 F->insert(It, copy0MBB);
18304 F->insert(It, sinkMBB);
18306 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18307 // live into the sink and copy blocks.
18308 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18310 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18311 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18312 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18313 copy0MBB->addLiveIn(X86::EFLAGS);
18314 sinkMBB->addLiveIn(X86::EFLAGS);
18317 // Transfer the remainder of BB and its successor edges to sinkMBB.
18318 sinkMBB->splice(sinkMBB->begin(), BB,
18319 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18320 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18322 // Add the true and fallthrough blocks as its successors.
18324 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18325 BB->addSuccessor(jcc1MBB);
18327 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18328 // jump to the sinkMBB.
18329 jcc1MBB->addSuccessor(copy0MBB);
18330 jcc1MBB->addSuccessor(sinkMBB);
18332 BB->addSuccessor(copy0MBB);
18335 // The true block target of the first (or only) branch is always sinkMBB.
18336 BB->addSuccessor(sinkMBB);
18338 // Create the conditional branch instruction.
18340 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18341 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18344 unsigned Opc2 = X86::GetCondBranchFromCond(
18345 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18346 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18350 // %FalseValue = ...
18351 // # fallthrough to sinkMBB
18352 copy0MBB->addSuccessor(sinkMBB);
18355 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18357 MachineInstrBuilder MIB =
18358 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18359 MI->getOperand(0).getReg())
18360 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18361 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18363 // If we have a double CMOV, the second Jcc provides the same incoming
18364 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18366 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18367 // Copy the PHI result to the register defined by the second CMOV.
18368 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18369 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18370 .addReg(MI->getOperand(0).getReg());
18371 NextCMOV->eraseFromParent();
18374 MI->eraseFromParent(); // The pseudo instruction is gone now.
18378 MachineBasicBlock *
18379 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18380 MachineBasicBlock *BB) const {
18381 MachineFunction *MF = BB->getParent();
18382 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18383 DebugLoc DL = MI->getDebugLoc();
18384 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18386 assert(MF->shouldSplitStack());
18388 const bool Is64Bit = Subtarget->is64Bit();
18389 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18391 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18392 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18395 // ... [Till the alloca]
18396 // If stacklet is not large enough, jump to mallocMBB
18399 // Allocate by subtracting from RSP
18400 // Jump to continueMBB
18403 // Allocate by call to runtime
18407 // [rest of original BB]
18410 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18411 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18412 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18414 MachineRegisterInfo &MRI = MF->getRegInfo();
18415 const TargetRegisterClass *AddrRegClass =
18416 getRegClassFor(getPointerTy());
18418 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18419 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18420 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18421 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18422 sizeVReg = MI->getOperand(1).getReg(),
18423 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18425 MachineFunction::iterator MBBIter = BB;
18428 MF->insert(MBBIter, bumpMBB);
18429 MF->insert(MBBIter, mallocMBB);
18430 MF->insert(MBBIter, continueMBB);
18432 continueMBB->splice(continueMBB->begin(), BB,
18433 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18434 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18436 // Add code to the main basic block to check if the stack limit has been hit,
18437 // and if so, jump to mallocMBB otherwise to bumpMBB.
18438 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18439 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18440 .addReg(tmpSPVReg).addReg(sizeVReg);
18441 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18442 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18443 .addReg(SPLimitVReg);
18444 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18446 // bumpMBB simply decreases the stack pointer, since we know the current
18447 // stacklet has enough space.
18448 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18449 .addReg(SPLimitVReg);
18450 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18451 .addReg(SPLimitVReg);
18452 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18454 // Calls into a routine in libgcc to allocate more space from the heap.
18455 const uint32_t *RegMask =
18456 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18458 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18460 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18461 .addExternalSymbol("__morestack_allocate_stack_space")
18462 .addRegMask(RegMask)
18463 .addReg(X86::RDI, RegState::Implicit)
18464 .addReg(X86::RAX, RegState::ImplicitDefine);
18465 } else if (Is64Bit) {
18466 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18468 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18469 .addExternalSymbol("__morestack_allocate_stack_space")
18470 .addRegMask(RegMask)
18471 .addReg(X86::EDI, RegState::Implicit)
18472 .addReg(X86::EAX, RegState::ImplicitDefine);
18474 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18476 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18477 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18478 .addExternalSymbol("__morestack_allocate_stack_space")
18479 .addRegMask(RegMask)
18480 .addReg(X86::EAX, RegState::ImplicitDefine);
18484 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18487 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18488 .addReg(IsLP64 ? X86::RAX : X86::EAX);
18489 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18491 // Set up the CFG correctly.
18492 BB->addSuccessor(bumpMBB);
18493 BB->addSuccessor(mallocMBB);
18494 mallocMBB->addSuccessor(continueMBB);
18495 bumpMBB->addSuccessor(continueMBB);
18497 // Take care of the PHI nodes.
18498 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18499 MI->getOperand(0).getReg())
18500 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18501 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18503 // Delete the original pseudo instruction.
18504 MI->eraseFromParent();
18507 return continueMBB;
18510 MachineBasicBlock *
18511 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18512 MachineBasicBlock *BB) const {
18513 DebugLoc DL = MI->getDebugLoc();
18515 assert(!Subtarget->isTargetMachO());
18517 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18519 MI->eraseFromParent(); // The pseudo instruction is gone now.
18523 MachineBasicBlock *
18524 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18525 MachineBasicBlock *BB) const {
18526 // This is pretty easy. We're taking the value that we received from
18527 // our load from the relocation, sticking it in either RDI (x86-64)
18528 // or EAX and doing an indirect call. The return value will then
18529 // be in the normal return register.
18530 MachineFunction *F = BB->getParent();
18531 const X86InstrInfo *TII = Subtarget->getInstrInfo();
18532 DebugLoc DL = MI->getDebugLoc();
18534 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18535 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18537 // Get a register mask for the lowered call.
18538 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18539 // proper register mask.
18540 const uint32_t *RegMask =
18541 Subtarget->getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18542 if (Subtarget->is64Bit()) {
18543 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18544 TII->get(X86::MOV64rm), X86::RDI)
18546 .addImm(0).addReg(0)
18547 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18548 MI->getOperand(3).getTargetFlags())
18550 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18551 addDirectMem(MIB, X86::RDI);
18552 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18553 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18554 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18555 TII->get(X86::MOV32rm), X86::EAX)
18557 .addImm(0).addReg(0)
18558 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18559 MI->getOperand(3).getTargetFlags())
18561 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18562 addDirectMem(MIB, X86::EAX);
18563 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18565 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18566 TII->get(X86::MOV32rm), X86::EAX)
18567 .addReg(TII->getGlobalBaseReg(F))
18568 .addImm(0).addReg(0)
18569 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18570 MI->getOperand(3).getTargetFlags())
18572 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18573 addDirectMem(MIB, X86::EAX);
18574 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18577 MI->eraseFromParent(); // The pseudo instruction is gone now.
18581 MachineBasicBlock *
18582 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18583 MachineBasicBlock *MBB) const {
18584 DebugLoc DL = MI->getDebugLoc();
18585 MachineFunction *MF = MBB->getParent();
18586 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18587 MachineRegisterInfo &MRI = MF->getRegInfo();
18589 const BasicBlock *BB = MBB->getBasicBlock();
18590 MachineFunction::iterator I = MBB;
18593 // Memory Reference
18594 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18595 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18598 unsigned MemOpndSlot = 0;
18600 unsigned CurOp = 0;
18602 DstReg = MI->getOperand(CurOp++).getReg();
18603 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18604 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18605 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18606 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18608 MemOpndSlot = CurOp;
18610 MVT PVT = getPointerTy();
18611 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18612 "Invalid Pointer Size!");
18614 // For v = setjmp(buf), we generate
18617 // buf[LabelOffset] = restoreMBB
18618 // SjLjSetup restoreMBB
18624 // v = phi(main, restore)
18627 // if base pointer being used, load it from frame
18630 MachineBasicBlock *thisMBB = MBB;
18631 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18632 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18633 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18634 MF->insert(I, mainMBB);
18635 MF->insert(I, sinkMBB);
18636 MF->push_back(restoreMBB);
18638 MachineInstrBuilder MIB;
18640 // Transfer the remainder of BB and its successor edges to sinkMBB.
18641 sinkMBB->splice(sinkMBB->begin(), MBB,
18642 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18643 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18646 unsigned PtrStoreOpc = 0;
18647 unsigned LabelReg = 0;
18648 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18649 Reloc::Model RM = MF->getTarget().getRelocationModel();
18650 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18651 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18653 // Prepare IP either in reg or imm.
18654 if (!UseImmLabel) {
18655 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18656 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18657 LabelReg = MRI.createVirtualRegister(PtrRC);
18658 if (Subtarget->is64Bit()) {
18659 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18663 .addMBB(restoreMBB)
18666 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18667 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18668 .addReg(XII->getGlobalBaseReg(MF))
18671 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18675 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18677 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18678 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18679 if (i == X86::AddrDisp)
18680 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18682 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18685 MIB.addReg(LabelReg);
18687 MIB.addMBB(restoreMBB);
18688 MIB.setMemRefs(MMOBegin, MMOEnd);
18690 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18691 .addMBB(restoreMBB);
18693 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18694 MIB.addRegMask(RegInfo->getNoPreservedMask());
18695 thisMBB->addSuccessor(mainMBB);
18696 thisMBB->addSuccessor(restoreMBB);
18700 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18701 mainMBB->addSuccessor(sinkMBB);
18704 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18705 TII->get(X86::PHI), DstReg)
18706 .addReg(mainDstReg).addMBB(mainMBB)
18707 .addReg(restoreDstReg).addMBB(restoreMBB);
18710 if (RegInfo->hasBasePointer(*MF)) {
18711 const bool Uses64BitFramePtr =
18712 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
18713 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
18714 X86FI->setRestoreBasePointer(MF);
18715 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
18716 unsigned BasePtr = RegInfo->getBaseRegister();
18717 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
18718 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
18719 FramePtr, true, X86FI->getRestoreBasePointerOffset())
18720 .setMIFlag(MachineInstr::FrameSetup);
18722 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18723 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
18724 restoreMBB->addSuccessor(sinkMBB);
18726 MI->eraseFromParent();
18730 MachineBasicBlock *
18731 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18732 MachineBasicBlock *MBB) const {
18733 DebugLoc DL = MI->getDebugLoc();
18734 MachineFunction *MF = MBB->getParent();
18735 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18736 MachineRegisterInfo &MRI = MF->getRegInfo();
18738 // Memory Reference
18739 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18740 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18742 MVT PVT = getPointerTy();
18743 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18744 "Invalid Pointer Size!");
18746 const TargetRegisterClass *RC =
18747 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18748 unsigned Tmp = MRI.createVirtualRegister(RC);
18749 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18750 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
18751 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18752 unsigned SP = RegInfo->getStackRegister();
18754 MachineInstrBuilder MIB;
18756 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18757 const int64_t SPOffset = 2 * PVT.getStoreSize();
18759 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18760 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18763 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18764 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18765 MIB.addOperand(MI->getOperand(i));
18766 MIB.setMemRefs(MMOBegin, MMOEnd);
18768 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18769 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18770 if (i == X86::AddrDisp)
18771 MIB.addDisp(MI->getOperand(i), LabelOffset);
18773 MIB.addOperand(MI->getOperand(i));
18775 MIB.setMemRefs(MMOBegin, MMOEnd);
18777 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18778 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18779 if (i == X86::AddrDisp)
18780 MIB.addDisp(MI->getOperand(i), SPOffset);
18782 MIB.addOperand(MI->getOperand(i));
18784 MIB.setMemRefs(MMOBegin, MMOEnd);
18786 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18788 MI->eraseFromParent();
18792 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18793 // accumulator loops. Writing back to the accumulator allows the coalescer
18794 // to remove extra copies in the loop.
18795 MachineBasicBlock *
18796 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18797 MachineBasicBlock *MBB) const {
18798 MachineOperand &AddendOp = MI->getOperand(3);
18800 // Bail out early if the addend isn't a register - we can't switch these.
18801 if (!AddendOp.isReg())
18804 MachineFunction &MF = *MBB->getParent();
18805 MachineRegisterInfo &MRI = MF.getRegInfo();
18807 // Check whether the addend is defined by a PHI:
18808 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18809 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18810 if (!AddendDef.isPHI())
18813 // Look for the following pattern:
18815 // %addend = phi [%entry, 0], [%loop, %result]
18817 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18821 // %addend = phi [%entry, 0], [%loop, %result]
18823 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18825 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18826 assert(AddendDef.getOperand(i).isReg());
18827 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18828 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18829 if (&PHISrcInst == MI) {
18830 // Found a matching instruction.
18831 unsigned NewFMAOpc = 0;
18832 switch (MI->getOpcode()) {
18833 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18834 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18835 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18836 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18837 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18838 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18839 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18840 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18841 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18842 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18843 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18844 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18845 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18846 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18847 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18848 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18849 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
18850 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
18851 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
18852 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
18854 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18855 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18856 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18857 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18858 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18859 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18860 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18861 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18862 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
18863 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
18864 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
18865 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
18866 default: llvm_unreachable("Unrecognized FMA variant.");
18869 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
18870 MachineInstrBuilder MIB =
18871 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18872 .addOperand(MI->getOperand(0))
18873 .addOperand(MI->getOperand(3))
18874 .addOperand(MI->getOperand(2))
18875 .addOperand(MI->getOperand(1));
18876 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18877 MI->eraseFromParent();
18884 MachineBasicBlock *
18885 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18886 MachineBasicBlock *BB) const {
18887 switch (MI->getOpcode()) {
18888 default: llvm_unreachable("Unexpected instr type to insert");
18889 case X86::TAILJMPd64:
18890 case X86::TAILJMPr64:
18891 case X86::TAILJMPm64:
18892 case X86::TAILJMPd64_REX:
18893 case X86::TAILJMPr64_REX:
18894 case X86::TAILJMPm64_REX:
18895 llvm_unreachable("TAILJMP64 would not be touched here.");
18896 case X86::TCRETURNdi64:
18897 case X86::TCRETURNri64:
18898 case X86::TCRETURNmi64:
18900 case X86::WIN_ALLOCA:
18901 return EmitLoweredWinAlloca(MI, BB);
18902 case X86::SEG_ALLOCA_32:
18903 case X86::SEG_ALLOCA_64:
18904 return EmitLoweredSegAlloca(MI, BB);
18905 case X86::TLSCall_32:
18906 case X86::TLSCall_64:
18907 return EmitLoweredTLSCall(MI, BB);
18908 case X86::CMOV_GR8:
18909 case X86::CMOV_FR32:
18910 case X86::CMOV_FR64:
18911 case X86::CMOV_V4F32:
18912 case X86::CMOV_V2F64:
18913 case X86::CMOV_V2I64:
18914 case X86::CMOV_V8F32:
18915 case X86::CMOV_V4F64:
18916 case X86::CMOV_V4I64:
18917 case X86::CMOV_V16F32:
18918 case X86::CMOV_V8F64:
18919 case X86::CMOV_V8I64:
18920 case X86::CMOV_GR16:
18921 case X86::CMOV_GR32:
18922 case X86::CMOV_RFP32:
18923 case X86::CMOV_RFP64:
18924 case X86::CMOV_RFP80:
18925 return EmitLoweredSelect(MI, BB);
18927 case X86::FP32_TO_INT16_IN_MEM:
18928 case X86::FP32_TO_INT32_IN_MEM:
18929 case X86::FP32_TO_INT64_IN_MEM:
18930 case X86::FP64_TO_INT16_IN_MEM:
18931 case X86::FP64_TO_INT32_IN_MEM:
18932 case X86::FP64_TO_INT64_IN_MEM:
18933 case X86::FP80_TO_INT16_IN_MEM:
18934 case X86::FP80_TO_INT32_IN_MEM:
18935 case X86::FP80_TO_INT64_IN_MEM: {
18936 MachineFunction *F = BB->getParent();
18937 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18938 DebugLoc DL = MI->getDebugLoc();
18940 // Change the floating point control register to use "round towards zero"
18941 // mode when truncating to an integer value.
18942 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18943 addFrameReference(BuildMI(*BB, MI, DL,
18944 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18946 // Load the old value of the high byte of the control word...
18948 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18949 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18952 // Set the high part to be round to zero...
18953 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18956 // Reload the modified control word now...
18957 addFrameReference(BuildMI(*BB, MI, DL,
18958 TII->get(X86::FLDCW16m)), CWFrameIdx);
18960 // Restore the memory image of control word to original value
18961 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18964 // Get the X86 opcode to use.
18966 switch (MI->getOpcode()) {
18967 default: llvm_unreachable("illegal opcode!");
18968 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18969 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18970 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18971 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18972 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18973 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18974 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18975 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18976 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18980 MachineOperand &Op = MI->getOperand(0);
18982 AM.BaseType = X86AddressMode::RegBase;
18983 AM.Base.Reg = Op.getReg();
18985 AM.BaseType = X86AddressMode::FrameIndexBase;
18986 AM.Base.FrameIndex = Op.getIndex();
18988 Op = MI->getOperand(1);
18990 AM.Scale = Op.getImm();
18991 Op = MI->getOperand(2);
18993 AM.IndexReg = Op.getImm();
18994 Op = MI->getOperand(3);
18995 if (Op.isGlobal()) {
18996 AM.GV = Op.getGlobal();
18998 AM.Disp = Op.getImm();
19000 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19001 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19003 // Reload the original control word now.
19004 addFrameReference(BuildMI(*BB, MI, DL,
19005 TII->get(X86::FLDCW16m)), CWFrameIdx);
19007 MI->eraseFromParent(); // The pseudo instruction is gone now.
19010 // String/text processing lowering.
19011 case X86::PCMPISTRM128REG:
19012 case X86::VPCMPISTRM128REG:
19013 case X86::PCMPISTRM128MEM:
19014 case X86::VPCMPISTRM128MEM:
19015 case X86::PCMPESTRM128REG:
19016 case X86::VPCMPESTRM128REG:
19017 case X86::PCMPESTRM128MEM:
19018 case X86::VPCMPESTRM128MEM:
19019 assert(Subtarget->hasSSE42() &&
19020 "Target must have SSE4.2 or AVX features enabled");
19021 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19023 // String/text processing lowering.
19024 case X86::PCMPISTRIREG:
19025 case X86::VPCMPISTRIREG:
19026 case X86::PCMPISTRIMEM:
19027 case X86::VPCMPISTRIMEM:
19028 case X86::PCMPESTRIREG:
19029 case X86::VPCMPESTRIREG:
19030 case X86::PCMPESTRIMEM:
19031 case X86::VPCMPESTRIMEM:
19032 assert(Subtarget->hasSSE42() &&
19033 "Target must have SSE4.2 or AVX features enabled");
19034 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19036 // Thread synchronization.
19038 return EmitMonitor(MI, BB, Subtarget);
19042 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19044 case X86::VASTART_SAVE_XMM_REGS:
19045 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19047 case X86::VAARG_64:
19048 return EmitVAARG64WithCustomInserter(MI, BB);
19050 case X86::EH_SjLj_SetJmp32:
19051 case X86::EH_SjLj_SetJmp64:
19052 return emitEHSjLjSetJmp(MI, BB);
19054 case X86::EH_SjLj_LongJmp32:
19055 case X86::EH_SjLj_LongJmp64:
19056 return emitEHSjLjLongJmp(MI, BB);
19058 case TargetOpcode::STATEPOINT:
19059 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19060 // this point in the process. We diverge later.
19061 return emitPatchPoint(MI, BB);
19063 case TargetOpcode::STACKMAP:
19064 case TargetOpcode::PATCHPOINT:
19065 return emitPatchPoint(MI, BB);
19067 case X86::VFMADDPDr213r:
19068 case X86::VFMADDPSr213r:
19069 case X86::VFMADDSDr213r:
19070 case X86::VFMADDSSr213r:
19071 case X86::VFMSUBPDr213r:
19072 case X86::VFMSUBPSr213r:
19073 case X86::VFMSUBSDr213r:
19074 case X86::VFMSUBSSr213r:
19075 case X86::VFNMADDPDr213r:
19076 case X86::VFNMADDPSr213r:
19077 case X86::VFNMADDSDr213r:
19078 case X86::VFNMADDSSr213r:
19079 case X86::VFNMSUBPDr213r:
19080 case X86::VFNMSUBPSr213r:
19081 case X86::VFNMSUBSDr213r:
19082 case X86::VFNMSUBSSr213r:
19083 case X86::VFMADDSUBPDr213r:
19084 case X86::VFMADDSUBPSr213r:
19085 case X86::VFMSUBADDPDr213r:
19086 case X86::VFMSUBADDPSr213r:
19087 case X86::VFMADDPDr213rY:
19088 case X86::VFMADDPSr213rY:
19089 case X86::VFMSUBPDr213rY:
19090 case X86::VFMSUBPSr213rY:
19091 case X86::VFNMADDPDr213rY:
19092 case X86::VFNMADDPSr213rY:
19093 case X86::VFNMSUBPDr213rY:
19094 case X86::VFNMSUBPSr213rY:
19095 case X86::VFMADDSUBPDr213rY:
19096 case X86::VFMADDSUBPSr213rY:
19097 case X86::VFMSUBADDPDr213rY:
19098 case X86::VFMSUBADDPSr213rY:
19099 return emitFMA3Instr(MI, BB);
19103 //===----------------------------------------------------------------------===//
19104 // X86 Optimization Hooks
19105 //===----------------------------------------------------------------------===//
19107 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19110 const SelectionDAG &DAG,
19111 unsigned Depth) const {
19112 unsigned BitWidth = KnownZero.getBitWidth();
19113 unsigned Opc = Op.getOpcode();
19114 assert((Opc >= ISD::BUILTIN_OP_END ||
19115 Opc == ISD::INTRINSIC_WO_CHAIN ||
19116 Opc == ISD::INTRINSIC_W_CHAIN ||
19117 Opc == ISD::INTRINSIC_VOID) &&
19118 "Should use MaskedValueIsZero if you don't know whether Op"
19119 " is a target node!");
19121 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19135 // These nodes' second result is a boolean.
19136 if (Op.getResNo() == 0)
19139 case X86ISD::SETCC:
19140 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19142 case ISD::INTRINSIC_WO_CHAIN: {
19143 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19144 unsigned NumLoBits = 0;
19147 case Intrinsic::x86_sse_movmsk_ps:
19148 case Intrinsic::x86_avx_movmsk_ps_256:
19149 case Intrinsic::x86_sse2_movmsk_pd:
19150 case Intrinsic::x86_avx_movmsk_pd_256:
19151 case Intrinsic::x86_mmx_pmovmskb:
19152 case Intrinsic::x86_sse2_pmovmskb_128:
19153 case Intrinsic::x86_avx2_pmovmskb: {
19154 // High bits of movmskp{s|d}, pmovmskb are known zero.
19156 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19157 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19158 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19159 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19160 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19161 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19162 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19163 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19165 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19174 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19176 const SelectionDAG &,
19177 unsigned Depth) const {
19178 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19179 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19180 return Op.getValueType().getScalarType().getSizeInBits();
19186 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19187 /// node is a GlobalAddress + offset.
19188 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19189 const GlobalValue* &GA,
19190 int64_t &Offset) const {
19191 if (N->getOpcode() == X86ISD::Wrapper) {
19192 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19193 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19194 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19198 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19201 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19202 /// same as extracting the high 128-bit part of 256-bit vector and then
19203 /// inserting the result into the low part of a new 256-bit vector
19204 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19205 EVT VT = SVOp->getValueType(0);
19206 unsigned NumElems = VT.getVectorNumElements();
19208 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19209 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19210 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19211 SVOp->getMaskElt(j) >= 0)
19217 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19218 /// same as extracting the low 128-bit part of 256-bit vector and then
19219 /// inserting the result into the high part of a new 256-bit vector
19220 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19221 EVT VT = SVOp->getValueType(0);
19222 unsigned NumElems = VT.getVectorNumElements();
19224 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19225 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19226 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19227 SVOp->getMaskElt(j) >= 0)
19233 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19234 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19235 TargetLowering::DAGCombinerInfo &DCI,
19236 const X86Subtarget* Subtarget) {
19238 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19239 SDValue V1 = SVOp->getOperand(0);
19240 SDValue V2 = SVOp->getOperand(1);
19241 EVT VT = SVOp->getValueType(0);
19242 unsigned NumElems = VT.getVectorNumElements();
19244 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19245 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19249 // V UNDEF BUILD_VECTOR UNDEF
19251 // CONCAT_VECTOR CONCAT_VECTOR
19254 // RESULT: V + zero extended
19256 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19257 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19258 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19261 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19264 // To match the shuffle mask, the first half of the mask should
19265 // be exactly the first vector, and all the rest a splat with the
19266 // first element of the second one.
19267 for (unsigned i = 0; i != NumElems/2; ++i)
19268 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19269 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19272 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19273 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19274 if (Ld->hasNUsesOfValue(1, 0)) {
19275 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19276 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19278 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19280 Ld->getPointerInfo(),
19281 Ld->getAlignment(),
19282 false/*isVolatile*/, true/*ReadMem*/,
19283 false/*WriteMem*/);
19285 // Make sure the newly-created LOAD is in the same position as Ld in
19286 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19287 // and update uses of Ld's output chain to use the TokenFactor.
19288 if (Ld->hasAnyUseOfValue(1)) {
19289 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19290 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19291 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19292 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19293 SDValue(ResNode.getNode(), 1));
19296 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19300 // Emit a zeroed vector and insert the desired subvector on its
19302 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19303 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19304 return DCI.CombineTo(N, InsV);
19307 //===--------------------------------------------------------------------===//
19308 // Combine some shuffles into subvector extracts and inserts:
19311 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19312 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19313 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19314 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19315 return DCI.CombineTo(N, InsV);
19318 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19319 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19320 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19321 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19322 return DCI.CombineTo(N, InsV);
19328 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19331 /// This is the leaf of the recursive combinine below. When we have found some
19332 /// chain of single-use x86 shuffle instructions and accumulated the combined
19333 /// shuffle mask represented by them, this will try to pattern match that mask
19334 /// into either a single instruction if there is a special purpose instruction
19335 /// for this operation, or into a PSHUFB instruction which is a fully general
19336 /// instruction but should only be used to replace chains over a certain depth.
19337 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19338 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19339 TargetLowering::DAGCombinerInfo &DCI,
19340 const X86Subtarget *Subtarget) {
19341 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19343 // Find the operand that enters the chain. Note that multiple uses are OK
19344 // here, we're not going to remove the operand we find.
19345 SDValue Input = Op.getOperand(0);
19346 while (Input.getOpcode() == ISD::BITCAST)
19347 Input = Input.getOperand(0);
19349 MVT VT = Input.getSimpleValueType();
19350 MVT RootVT = Root.getSimpleValueType();
19353 // Just remove no-op shuffle masks.
19354 if (Mask.size() == 1) {
19355 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19360 // Use the float domain if the operand type is a floating point type.
19361 bool FloatDomain = VT.isFloatingPoint();
19363 // For floating point shuffles, we don't have free copies in the shuffle
19364 // instructions or the ability to load as part of the instruction, so
19365 // canonicalize their shuffles to UNPCK or MOV variants.
19367 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19368 // vectors because it can have a load folded into it that UNPCK cannot. This
19369 // doesn't preclude something switching to the shorter encoding post-RA.
19371 // FIXME: Should teach these routines about AVX vector widths.
19372 if (FloatDomain && VT.getSizeInBits() == 128) {
19373 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19374 bool Lo = Mask.equals({0, 0});
19377 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19378 // is no slower than UNPCKLPD but has the option to fold the input operand
19379 // into even an unaligned memory load.
19380 if (Lo && Subtarget->hasSSE3()) {
19381 Shuffle = X86ISD::MOVDDUP;
19382 ShuffleVT = MVT::v2f64;
19384 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19385 // than the UNPCK variants.
19386 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19387 ShuffleVT = MVT::v4f32;
19389 if (Depth == 1 && Root->getOpcode() == Shuffle)
19390 return false; // Nothing to do!
19391 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19392 DCI.AddToWorklist(Op.getNode());
19393 if (Shuffle == X86ISD::MOVDDUP)
19394 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19396 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19397 DCI.AddToWorklist(Op.getNode());
19398 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19402 if (Subtarget->hasSSE3() &&
19403 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19404 bool Lo = Mask.equals({0, 0, 2, 2});
19405 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19406 MVT ShuffleVT = MVT::v4f32;
19407 if (Depth == 1 && Root->getOpcode() == Shuffle)
19408 return false; // Nothing to do!
19409 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19410 DCI.AddToWorklist(Op.getNode());
19411 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19412 DCI.AddToWorklist(Op.getNode());
19413 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19417 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19418 bool Lo = Mask.equals({0, 0, 1, 1});
19419 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19420 MVT ShuffleVT = MVT::v4f32;
19421 if (Depth == 1 && Root->getOpcode() == Shuffle)
19422 return false; // Nothing to do!
19423 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19424 DCI.AddToWorklist(Op.getNode());
19425 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19426 DCI.AddToWorklist(Op.getNode());
19427 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19433 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19434 // variants as none of these have single-instruction variants that are
19435 // superior to the UNPCK formulation.
19436 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19437 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19438 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19439 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19441 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19442 bool Lo = Mask[0] == 0;
19443 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19444 if (Depth == 1 && Root->getOpcode() == Shuffle)
19445 return false; // Nothing to do!
19447 switch (Mask.size()) {
19449 ShuffleVT = MVT::v8i16;
19452 ShuffleVT = MVT::v16i8;
19455 llvm_unreachable("Impossible mask size!");
19457 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19458 DCI.AddToWorklist(Op.getNode());
19459 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19460 DCI.AddToWorklist(Op.getNode());
19461 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19466 // Don't try to re-form single instruction chains under any circumstances now
19467 // that we've done encoding canonicalization for them.
19471 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19472 // can replace them with a single PSHUFB instruction profitably. Intel's
19473 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19474 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19475 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19476 SmallVector<SDValue, 16> PSHUFBMask;
19477 int NumBytes = VT.getSizeInBits() / 8;
19478 int Ratio = NumBytes / Mask.size();
19479 for (int i = 0; i < NumBytes; ++i) {
19480 if (Mask[i / Ratio] == SM_SentinelUndef) {
19481 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19484 int M = Mask[i / Ratio] != SM_SentinelZero
19485 ? Ratio * Mask[i / Ratio] + i % Ratio
19487 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19489 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19490 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19491 DCI.AddToWorklist(Op.getNode());
19492 SDValue PSHUFBMaskOp =
19493 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19494 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19495 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19496 DCI.AddToWorklist(Op.getNode());
19497 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19502 // Failed to find any combines.
19506 /// \brief Fully generic combining of x86 shuffle instructions.
19508 /// This should be the last combine run over the x86 shuffle instructions. Once
19509 /// they have been fully optimized, this will recursively consider all chains
19510 /// of single-use shuffle instructions, build a generic model of the cumulative
19511 /// shuffle operation, and check for simpler instructions which implement this
19512 /// operation. We use this primarily for two purposes:
19514 /// 1) Collapse generic shuffles to specialized single instructions when
19515 /// equivalent. In most cases, this is just an encoding size win, but
19516 /// sometimes we will collapse multiple generic shuffles into a single
19517 /// special-purpose shuffle.
19518 /// 2) Look for sequences of shuffle instructions with 3 or more total
19519 /// instructions, and replace them with the slightly more expensive SSSE3
19520 /// PSHUFB instruction if available. We do this as the last combining step
19521 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19522 /// a suitable short sequence of other instructions. The PHUFB will either
19523 /// use a register or have to read from memory and so is slightly (but only
19524 /// slightly) more expensive than the other shuffle instructions.
19526 /// Because this is inherently a quadratic operation (for each shuffle in
19527 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19528 /// This should never be an issue in practice as the shuffle lowering doesn't
19529 /// produce sequences of more than 8 instructions.
19531 /// FIXME: We will currently miss some cases where the redundant shuffling
19532 /// would simplify under the threshold for PSHUFB formation because of
19533 /// combine-ordering. To fix this, we should do the redundant instruction
19534 /// combining in this recursive walk.
19535 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19536 ArrayRef<int> RootMask,
19537 int Depth, bool HasPSHUFB,
19539 TargetLowering::DAGCombinerInfo &DCI,
19540 const X86Subtarget *Subtarget) {
19541 // Bound the depth of our recursive combine because this is ultimately
19542 // quadratic in nature.
19546 // Directly rip through bitcasts to find the underlying operand.
19547 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19548 Op = Op.getOperand(0);
19550 MVT VT = Op.getSimpleValueType();
19551 if (!VT.isVector())
19552 return false; // Bail if we hit a non-vector.
19554 assert(Root.getSimpleValueType().isVector() &&
19555 "Shuffles operate on vector types!");
19556 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19557 "Can only combine shuffles of the same vector register size.");
19559 if (!isTargetShuffle(Op.getOpcode()))
19561 SmallVector<int, 16> OpMask;
19563 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19564 // We only can combine unary shuffles which we can decode the mask for.
19565 if (!HaveMask || !IsUnary)
19568 assert(VT.getVectorNumElements() == OpMask.size() &&
19569 "Different mask size from vector size!");
19570 assert(((RootMask.size() > OpMask.size() &&
19571 RootMask.size() % OpMask.size() == 0) ||
19572 (OpMask.size() > RootMask.size() &&
19573 OpMask.size() % RootMask.size() == 0) ||
19574 OpMask.size() == RootMask.size()) &&
19575 "The smaller number of elements must divide the larger.");
19576 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19577 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19578 assert(((RootRatio == 1 && OpRatio == 1) ||
19579 (RootRatio == 1) != (OpRatio == 1)) &&
19580 "Must not have a ratio for both incoming and op masks!");
19582 SmallVector<int, 16> Mask;
19583 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19585 // Merge this shuffle operation's mask into our accumulated mask. Note that
19586 // this shuffle's mask will be the first applied to the input, followed by the
19587 // root mask to get us all the way to the root value arrangement. The reason
19588 // for this order is that we are recursing up the operation chain.
19589 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19590 int RootIdx = i / RootRatio;
19591 if (RootMask[RootIdx] < 0) {
19592 // This is a zero or undef lane, we're done.
19593 Mask.push_back(RootMask[RootIdx]);
19597 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19598 int OpIdx = RootMaskedIdx / OpRatio;
19599 if (OpMask[OpIdx] < 0) {
19600 // The incoming lanes are zero or undef, it doesn't matter which ones we
19602 Mask.push_back(OpMask[OpIdx]);
19606 // Ok, we have non-zero lanes, map them through.
19607 Mask.push_back(OpMask[OpIdx] * OpRatio +
19608 RootMaskedIdx % OpRatio);
19611 // See if we can recurse into the operand to combine more things.
19612 switch (Op.getOpcode()) {
19613 case X86ISD::PSHUFB:
19615 case X86ISD::PSHUFD:
19616 case X86ISD::PSHUFHW:
19617 case X86ISD::PSHUFLW:
19618 if (Op.getOperand(0).hasOneUse() &&
19619 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19620 HasPSHUFB, DAG, DCI, Subtarget))
19624 case X86ISD::UNPCKL:
19625 case X86ISD::UNPCKH:
19626 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19627 // We can't check for single use, we have to check that this shuffle is the only user.
19628 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19629 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19630 HasPSHUFB, DAG, DCI, Subtarget))
19635 // Minor canonicalization of the accumulated shuffle mask to make it easier
19636 // to match below. All this does is detect masks with squential pairs of
19637 // elements, and shrink them to the half-width mask. It does this in a loop
19638 // so it will reduce the size of the mask to the minimal width mask which
19639 // performs an equivalent shuffle.
19640 SmallVector<int, 16> WidenedMask;
19641 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19642 Mask = std::move(WidenedMask);
19643 WidenedMask.clear();
19646 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19650 /// \brief Get the PSHUF-style mask from PSHUF node.
19652 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19653 /// PSHUF-style masks that can be reused with such instructions.
19654 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19655 MVT VT = N.getSimpleValueType();
19656 SmallVector<int, 4> Mask;
19658 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
19662 // If we have more than 128-bits, only the low 128-bits of shuffle mask
19663 // matter. Check that the upper masks are repeats and remove them.
19664 if (VT.getSizeInBits() > 128) {
19665 int LaneElts = 128 / VT.getScalarSizeInBits();
19667 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
19668 for (int j = 0; j < LaneElts; ++j)
19669 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
19670 "Mask doesn't repeat in high 128-bit lanes!");
19672 Mask.resize(LaneElts);
19675 switch (N.getOpcode()) {
19676 case X86ISD::PSHUFD:
19678 case X86ISD::PSHUFLW:
19681 case X86ISD::PSHUFHW:
19682 Mask.erase(Mask.begin(), Mask.begin() + 4);
19683 for (int &M : Mask)
19687 llvm_unreachable("No valid shuffle instruction found!");
19691 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19693 /// We walk up the chain and look for a combinable shuffle, skipping over
19694 /// shuffles that we could hoist this shuffle's transformation past without
19695 /// altering anything.
19697 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19699 TargetLowering::DAGCombinerInfo &DCI) {
19700 assert(N.getOpcode() == X86ISD::PSHUFD &&
19701 "Called with something other than an x86 128-bit half shuffle!");
19704 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19705 // of the shuffles in the chain so that we can form a fresh chain to replace
19707 SmallVector<SDValue, 8> Chain;
19708 SDValue V = N.getOperand(0);
19709 for (; V.hasOneUse(); V = V.getOperand(0)) {
19710 switch (V.getOpcode()) {
19712 return SDValue(); // Nothing combined!
19715 // Skip bitcasts as we always know the type for the target specific
19719 case X86ISD::PSHUFD:
19720 // Found another dword shuffle.
19723 case X86ISD::PSHUFLW:
19724 // Check that the low words (being shuffled) are the identity in the
19725 // dword shuffle, and the high words are self-contained.
19726 if (Mask[0] != 0 || Mask[1] != 1 ||
19727 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19730 Chain.push_back(V);
19733 case X86ISD::PSHUFHW:
19734 // Check that the high words (being shuffled) are the identity in the
19735 // dword shuffle, and the low words are self-contained.
19736 if (Mask[2] != 2 || Mask[3] != 3 ||
19737 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19740 Chain.push_back(V);
19743 case X86ISD::UNPCKL:
19744 case X86ISD::UNPCKH:
19745 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19746 // shuffle into a preceding word shuffle.
19747 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
19748 V.getSimpleValueType().getScalarType() != MVT::i16)
19751 // Search for a half-shuffle which we can combine with.
19752 unsigned CombineOp =
19753 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19754 if (V.getOperand(0) != V.getOperand(1) ||
19755 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19757 Chain.push_back(V);
19758 V = V.getOperand(0);
19760 switch (V.getOpcode()) {
19762 return SDValue(); // Nothing to combine.
19764 case X86ISD::PSHUFLW:
19765 case X86ISD::PSHUFHW:
19766 if (V.getOpcode() == CombineOp)
19769 Chain.push_back(V);
19773 V = V.getOperand(0);
19777 } while (V.hasOneUse());
19780 // Break out of the loop if we break out of the switch.
19784 if (!V.hasOneUse())
19785 // We fell out of the loop without finding a viable combining instruction.
19788 // Merge this node's mask and our incoming mask.
19789 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19790 for (int &M : Mask)
19792 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19793 getV4X86ShuffleImm8ForMask(Mask, DAG));
19795 // Rebuild the chain around this new shuffle.
19796 while (!Chain.empty()) {
19797 SDValue W = Chain.pop_back_val();
19799 if (V.getValueType() != W.getOperand(0).getValueType())
19800 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19802 switch (W.getOpcode()) {
19804 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19806 case X86ISD::UNPCKL:
19807 case X86ISD::UNPCKH:
19808 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19811 case X86ISD::PSHUFD:
19812 case X86ISD::PSHUFLW:
19813 case X86ISD::PSHUFHW:
19814 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19818 if (V.getValueType() != N.getValueType())
19819 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19821 // Return the new chain to replace N.
19825 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19827 /// We walk up the chain, skipping shuffles of the other half and looking
19828 /// through shuffles which switch halves trying to find a shuffle of the same
19829 /// pair of dwords.
19830 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19832 TargetLowering::DAGCombinerInfo &DCI) {
19834 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19835 "Called with something other than an x86 128-bit half shuffle!");
19837 unsigned CombineOpcode = N.getOpcode();
19839 // Walk up a single-use chain looking for a combinable shuffle.
19840 SDValue V = N.getOperand(0);
19841 for (; V.hasOneUse(); V = V.getOperand(0)) {
19842 switch (V.getOpcode()) {
19844 return false; // Nothing combined!
19847 // Skip bitcasts as we always know the type for the target specific
19851 case X86ISD::PSHUFLW:
19852 case X86ISD::PSHUFHW:
19853 if (V.getOpcode() == CombineOpcode)
19856 // Other-half shuffles are no-ops.
19859 // Break out of the loop if we break out of the switch.
19863 if (!V.hasOneUse())
19864 // We fell out of the loop without finding a viable combining instruction.
19867 // Combine away the bottom node as its shuffle will be accumulated into
19868 // a preceding shuffle.
19869 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19871 // Record the old value.
19874 // Merge this node's mask and our incoming mask (adjusted to account for all
19875 // the pshufd instructions encountered).
19876 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19877 for (int &M : Mask)
19879 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19880 getV4X86ShuffleImm8ForMask(Mask, DAG));
19882 // Check that the shuffles didn't cancel each other out. If not, we need to
19883 // combine to the new one.
19885 // Replace the combinable shuffle with the combined one, updating all users
19886 // so that we re-evaluate the chain here.
19887 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19892 /// \brief Try to combine x86 target specific shuffles.
19893 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19894 TargetLowering::DAGCombinerInfo &DCI,
19895 const X86Subtarget *Subtarget) {
19897 MVT VT = N.getSimpleValueType();
19898 SmallVector<int, 4> Mask;
19900 switch (N.getOpcode()) {
19901 case X86ISD::PSHUFD:
19902 case X86ISD::PSHUFLW:
19903 case X86ISD::PSHUFHW:
19904 Mask = getPSHUFShuffleMask(N);
19905 assert(Mask.size() == 4);
19911 // Nuke no-op shuffles that show up after combining.
19912 if (isNoopShuffleMask(Mask))
19913 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19915 // Look for simplifications involving one or two shuffle instructions.
19916 SDValue V = N.getOperand(0);
19917 switch (N.getOpcode()) {
19920 case X86ISD::PSHUFLW:
19921 case X86ISD::PSHUFHW:
19922 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
19924 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19925 return SDValue(); // We combined away this shuffle, so we're done.
19927 // See if this reduces to a PSHUFD which is no more expensive and can
19928 // combine with more operations. Note that it has to at least flip the
19929 // dwords as otherwise it would have been removed as a no-op.
19930 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
19931 int DMask[] = {0, 1, 2, 3};
19932 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19933 DMask[DOffset + 0] = DOffset + 1;
19934 DMask[DOffset + 1] = DOffset + 0;
19935 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
19936 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
19937 DCI.AddToWorklist(V.getNode());
19938 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
19939 getV4X86ShuffleImm8ForMask(DMask, DAG));
19940 DCI.AddToWorklist(V.getNode());
19941 return DAG.getNode(ISD::BITCAST, DL, VT, V);
19944 // Look for shuffle patterns which can be implemented as a single unpack.
19945 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19946 // only works when we have a PSHUFD followed by two half-shuffles.
19947 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19948 (V.getOpcode() == X86ISD::PSHUFLW ||
19949 V.getOpcode() == X86ISD::PSHUFHW) &&
19950 V.getOpcode() != N.getOpcode() &&
19952 SDValue D = V.getOperand(0);
19953 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19954 D = D.getOperand(0);
19955 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19956 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19957 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19958 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19959 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19961 for (int i = 0; i < 4; ++i) {
19962 WordMask[i + NOffset] = Mask[i] + NOffset;
19963 WordMask[i + VOffset] = VMask[i] + VOffset;
19965 // Map the word mask through the DWord mask.
19967 for (int i = 0; i < 8; ++i)
19968 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19969 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19970 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
19971 // We can replace all three shuffles with an unpack.
19972 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
19973 DCI.AddToWorklist(V.getNode());
19974 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19983 case X86ISD::PSHUFD:
19984 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19993 /// \brief Try to combine a shuffle into a target-specific add-sub node.
19995 /// We combine this directly on the abstract vector shuffle nodes so it is
19996 /// easier to generically match. We also insert dummy vector shuffle nodes for
19997 /// the operands which explicitly discard the lanes which are unused by this
19998 /// operation to try to flow through the rest of the combiner the fact that
19999 /// they're unused.
20000 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20002 EVT VT = N->getValueType(0);
20004 // We only handle target-independent shuffles.
20005 // FIXME: It would be easy and harmless to use the target shuffle mask
20006 // extraction tool to support more.
20007 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20010 auto *SVN = cast<ShuffleVectorSDNode>(N);
20011 ArrayRef<int> Mask = SVN->getMask();
20012 SDValue V1 = N->getOperand(0);
20013 SDValue V2 = N->getOperand(1);
20015 // We require the first shuffle operand to be the SUB node, and the second to
20016 // be the ADD node.
20017 // FIXME: We should support the commuted patterns.
20018 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20021 // If there are other uses of these operations we can't fold them.
20022 if (!V1->hasOneUse() || !V2->hasOneUse())
20025 // Ensure that both operations have the same operands. Note that we can
20026 // commute the FADD operands.
20027 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20028 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20029 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20032 // We're looking for blends between FADD and FSUB nodes. We insist on these
20033 // nodes being lined up in a specific expected pattern.
20034 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20035 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20036 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20039 // Only specific types are legal at this point, assert so we notice if and
20040 // when these change.
20041 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20042 VT == MVT::v4f64) &&
20043 "Unknown vector type encountered!");
20045 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20048 /// PerformShuffleCombine - Performs several different shuffle combines.
20049 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20050 TargetLowering::DAGCombinerInfo &DCI,
20051 const X86Subtarget *Subtarget) {
20053 SDValue N0 = N->getOperand(0);
20054 SDValue N1 = N->getOperand(1);
20055 EVT VT = N->getValueType(0);
20057 // Don't create instructions with illegal types after legalize types has run.
20058 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20059 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20062 // If we have legalized the vector types, look for blends of FADD and FSUB
20063 // nodes that we can fuse into an ADDSUB node.
20064 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20065 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20068 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20069 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20070 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20071 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20073 // During Type Legalization, when promoting illegal vector types,
20074 // the backend might introduce new shuffle dag nodes and bitcasts.
20076 // This code performs the following transformation:
20077 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20078 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20080 // We do this only if both the bitcast and the BINOP dag nodes have
20081 // one use. Also, perform this transformation only if the new binary
20082 // operation is legal. This is to avoid introducing dag nodes that
20083 // potentially need to be further expanded (or custom lowered) into a
20084 // less optimal sequence of dag nodes.
20085 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20086 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20087 N0.getOpcode() == ISD::BITCAST) {
20088 SDValue BC0 = N0.getOperand(0);
20089 EVT SVT = BC0.getValueType();
20090 unsigned Opcode = BC0.getOpcode();
20091 unsigned NumElts = VT.getVectorNumElements();
20093 if (BC0.hasOneUse() && SVT.isVector() &&
20094 SVT.getVectorNumElements() * 2 == NumElts &&
20095 TLI.isOperationLegal(Opcode, VT)) {
20096 bool CanFold = false;
20108 unsigned SVTNumElts = SVT.getVectorNumElements();
20109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20110 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20111 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20112 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20113 CanFold = SVOp->getMaskElt(i) < 0;
20116 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20117 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20118 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20119 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20124 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20125 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20126 // consecutive, non-overlapping, and in the right order.
20127 SmallVector<SDValue, 16> Elts;
20128 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20129 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20131 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20135 if (isTargetShuffle(N->getOpcode())) {
20137 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20138 if (Shuffle.getNode())
20141 // Try recursively combining arbitrary sequences of x86 shuffle
20142 // instructions into higher-order shuffles. We do this after combining
20143 // specific PSHUF instruction sequences into their minimal form so that we
20144 // can evaluate how many specialized shuffle instructions are involved in
20145 // a particular chain.
20146 SmallVector<int, 1> NonceMask; // Just a placeholder.
20147 NonceMask.push_back(0);
20148 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20149 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20151 return SDValue(); // This routine will use CombineTo to replace N.
20157 /// PerformTruncateCombine - Converts truncate operation to
20158 /// a sequence of vector shuffle operations.
20159 /// It is possible when we truncate 256-bit vector to 128-bit vector
20160 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20161 TargetLowering::DAGCombinerInfo &DCI,
20162 const X86Subtarget *Subtarget) {
20166 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20167 /// specific shuffle of a load can be folded into a single element load.
20168 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20169 /// shuffles have been custom lowered so we need to handle those here.
20170 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20171 TargetLowering::DAGCombinerInfo &DCI) {
20172 if (DCI.isBeforeLegalizeOps())
20175 SDValue InVec = N->getOperand(0);
20176 SDValue EltNo = N->getOperand(1);
20178 if (!isa<ConstantSDNode>(EltNo))
20181 EVT OriginalVT = InVec.getValueType();
20183 if (InVec.getOpcode() == ISD::BITCAST) {
20184 // Don't duplicate a load with other uses.
20185 if (!InVec.hasOneUse())
20187 EVT BCVT = InVec.getOperand(0).getValueType();
20188 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20190 InVec = InVec.getOperand(0);
20193 EVT CurrentVT = InVec.getValueType();
20195 if (!isTargetShuffle(InVec.getOpcode()))
20198 // Don't duplicate a load with other uses.
20199 if (!InVec.hasOneUse())
20202 SmallVector<int, 16> ShuffleMask;
20204 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20205 ShuffleMask, UnaryShuffle))
20208 // Select the input vector, guarding against out of range extract vector.
20209 unsigned NumElems = CurrentVT.getVectorNumElements();
20210 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20211 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20212 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20213 : InVec.getOperand(1);
20215 // If inputs to shuffle are the same for both ops, then allow 2 uses
20216 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20217 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20219 if (LdNode.getOpcode() == ISD::BITCAST) {
20220 // Don't duplicate a load with other uses.
20221 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20224 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20225 LdNode = LdNode.getOperand(0);
20228 if (!ISD::isNormalLoad(LdNode.getNode()))
20231 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20233 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20236 EVT EltVT = N->getValueType(0);
20237 // If there's a bitcast before the shuffle, check if the load type and
20238 // alignment is valid.
20239 unsigned Align = LN0->getAlignment();
20240 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20241 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20242 EltVT.getTypeForEVT(*DAG.getContext()));
20244 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20247 // All checks match so transform back to vector_shuffle so that DAG combiner
20248 // can finish the job
20251 // Create shuffle node taking into account the case that its a unary shuffle
20252 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20253 : InVec.getOperand(1);
20254 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20255 InVec.getOperand(0), Shuffle,
20257 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20258 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20262 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20263 /// special and don't usually play with other vector types, it's better to
20264 /// handle them early to be sure we emit efficient code by avoiding
20265 /// store-load conversions.
20266 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20267 if (N->getValueType(0) != MVT::x86mmx ||
20268 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20269 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20272 SDValue V = N->getOperand(0);
20273 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20274 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20275 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20276 N->getValueType(0), V.getOperand(0));
20281 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20282 /// generation and convert it from being a bunch of shuffles and extracts
20283 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20284 /// storing the value and loading scalars back, while for x64 we should
20285 /// use 64-bit extracts and shifts.
20286 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20287 TargetLowering::DAGCombinerInfo &DCI) {
20288 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20289 if (NewOp.getNode())
20292 SDValue InputVector = N->getOperand(0);
20294 // Detect mmx to i32 conversion through a v2i32 elt extract.
20295 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20296 N->getValueType(0) == MVT::i32 &&
20297 InputVector.getValueType() == MVT::v2i32) {
20299 // The bitcast source is a direct mmx result.
20300 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20301 if (MMXSrc.getValueType() == MVT::x86mmx)
20302 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20303 N->getValueType(0),
20304 InputVector.getNode()->getOperand(0));
20306 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20307 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20308 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20309 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20310 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20311 MMXSrcOp.getValueType() == MVT::v1i64 &&
20312 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20313 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20314 N->getValueType(0),
20315 MMXSrcOp.getOperand(0));
20318 // Only operate on vectors of 4 elements, where the alternative shuffling
20319 // gets to be more expensive.
20320 if (InputVector.getValueType() != MVT::v4i32)
20323 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20324 // single use which is a sign-extend or zero-extend, and all elements are
20326 SmallVector<SDNode *, 4> Uses;
20327 unsigned ExtractedElements = 0;
20328 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20329 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20330 if (UI.getUse().getResNo() != InputVector.getResNo())
20333 SDNode *Extract = *UI;
20334 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20337 if (Extract->getValueType(0) != MVT::i32)
20339 if (!Extract->hasOneUse())
20341 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20342 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20344 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20347 // Record which element was extracted.
20348 ExtractedElements |=
20349 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20351 Uses.push_back(Extract);
20354 // If not all the elements were used, this may not be worthwhile.
20355 if (ExtractedElements != 15)
20358 // Ok, we've now decided to do the transformation.
20359 // If 64-bit shifts are legal, use the extract-shift sequence,
20360 // otherwise bounce the vector off the cache.
20361 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20363 SDLoc dl(InputVector);
20365 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20366 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20367 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20368 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20369 DAG.getConstant(0, VecIdxTy));
20370 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20371 DAG.getConstant(1, VecIdxTy));
20373 SDValue ShAmt = DAG.getConstant(32,
20374 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20375 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20376 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20377 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20378 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20379 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20380 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20382 // Store the value to a temporary stack slot.
20383 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20384 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20385 MachinePointerInfo(), false, false, 0);
20387 EVT ElementType = InputVector.getValueType().getVectorElementType();
20388 unsigned EltSize = ElementType.getSizeInBits() / 8;
20390 // Replace each use (extract) with a load of the appropriate element.
20391 for (unsigned i = 0; i < 4; ++i) {
20392 uint64_t Offset = EltSize * i;
20393 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20395 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20396 StackPtr, OffsetVal);
20398 // Load the scalar.
20399 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20400 ScalarAddr, MachinePointerInfo(),
20401 false, false, false, 0);
20406 // Replace the extracts
20407 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20408 UE = Uses.end(); UI != UE; ++UI) {
20409 SDNode *Extract = *UI;
20411 SDValue Idx = Extract->getOperand(1);
20412 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20413 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20416 // The replacement was made in place; don't return anything.
20420 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20421 static std::pair<unsigned, bool>
20422 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20423 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20424 if (!VT.isVector())
20425 return std::make_pair(0, false);
20427 bool NeedSplit = false;
20428 switch (VT.getSimpleVT().SimpleTy) {
20429 default: return std::make_pair(0, false);
20432 if (!Subtarget->hasVLX())
20433 return std::make_pair(0, false);
20437 if (!Subtarget->hasBWI())
20438 return std::make_pair(0, false);
20442 if (!Subtarget->hasAVX512())
20443 return std::make_pair(0, false);
20448 if (!Subtarget->hasAVX2())
20450 if (!Subtarget->hasAVX())
20451 return std::make_pair(0, false);
20456 if (!Subtarget->hasSSE2())
20457 return std::make_pair(0, false);
20460 // SSE2 has only a small subset of the operations.
20461 bool hasUnsigned = Subtarget->hasSSE41() ||
20462 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20463 bool hasSigned = Subtarget->hasSSE41() ||
20464 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20466 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20469 // Check for x CC y ? x : y.
20470 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20471 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20476 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20479 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20482 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20485 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20487 // Check for x CC y ? y : x -- a min/max with reversed arms.
20488 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20489 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20494 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20497 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20500 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20503 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20507 return std::make_pair(Opc, NeedSplit);
20511 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20512 const X86Subtarget *Subtarget) {
20514 SDValue Cond = N->getOperand(0);
20515 SDValue LHS = N->getOperand(1);
20516 SDValue RHS = N->getOperand(2);
20518 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20519 SDValue CondSrc = Cond->getOperand(0);
20520 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20521 Cond = CondSrc->getOperand(0);
20524 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20527 // A vselect where all conditions and data are constants can be optimized into
20528 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20529 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20530 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20533 unsigned MaskValue = 0;
20534 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20537 MVT VT = N->getSimpleValueType(0);
20538 unsigned NumElems = VT.getVectorNumElements();
20539 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20540 for (unsigned i = 0; i < NumElems; ++i) {
20541 // Be sure we emit undef where we can.
20542 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20543 ShuffleMask[i] = -1;
20545 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20548 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20549 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20551 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20554 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20556 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20557 TargetLowering::DAGCombinerInfo &DCI,
20558 const X86Subtarget *Subtarget) {
20560 SDValue Cond = N->getOperand(0);
20561 // Get the LHS/RHS of the select.
20562 SDValue LHS = N->getOperand(1);
20563 SDValue RHS = N->getOperand(2);
20564 EVT VT = LHS.getValueType();
20565 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20567 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20568 // instructions match the semantics of the common C idiom x<y?x:y but not
20569 // x<=y?x:y, because of how they handle negative zero (which can be
20570 // ignored in unsafe-math mode).
20571 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20572 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20573 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20574 (Subtarget->hasSSE2() ||
20575 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20576 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20578 unsigned Opcode = 0;
20579 // Check for x CC y ? x : y.
20580 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20581 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20585 // Converting this to a min would handle NaNs incorrectly, and swapping
20586 // the operands would cause it to handle comparisons between positive
20587 // and negative zero incorrectly.
20588 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20589 if (!DAG.getTarget().Options.UnsafeFPMath &&
20590 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20592 std::swap(LHS, RHS);
20594 Opcode = X86ISD::FMIN;
20597 // Converting this to a min would handle comparisons between positive
20598 // and negative zero incorrectly.
20599 if (!DAG.getTarget().Options.UnsafeFPMath &&
20600 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20602 Opcode = X86ISD::FMIN;
20605 // Converting this to a min would handle both negative zeros and NaNs
20606 // incorrectly, but we can swap the operands to fix both.
20607 std::swap(LHS, RHS);
20611 Opcode = X86ISD::FMIN;
20615 // Converting this to a max would handle comparisons between positive
20616 // and negative zero incorrectly.
20617 if (!DAG.getTarget().Options.UnsafeFPMath &&
20618 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20620 Opcode = X86ISD::FMAX;
20623 // Converting this to a max would handle NaNs incorrectly, and swapping
20624 // the operands would cause it to handle comparisons between positive
20625 // and negative zero incorrectly.
20626 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20627 if (!DAG.getTarget().Options.UnsafeFPMath &&
20628 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20630 std::swap(LHS, RHS);
20632 Opcode = X86ISD::FMAX;
20635 // Converting this to a max would handle both negative zeros and NaNs
20636 // incorrectly, but we can swap the operands to fix both.
20637 std::swap(LHS, RHS);
20641 Opcode = X86ISD::FMAX;
20644 // Check for x CC y ? y : x -- a min/max with reversed arms.
20645 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20646 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20650 // Converting this to a min would handle comparisons between positive
20651 // and negative zero incorrectly, and swapping the operands would
20652 // cause it to handle NaNs incorrectly.
20653 if (!DAG.getTarget().Options.UnsafeFPMath &&
20654 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20655 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20657 std::swap(LHS, RHS);
20659 Opcode = X86ISD::FMIN;
20662 // Converting this to a min would handle NaNs incorrectly.
20663 if (!DAG.getTarget().Options.UnsafeFPMath &&
20664 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20666 Opcode = X86ISD::FMIN;
20669 // Converting this to a min would handle both negative zeros and NaNs
20670 // incorrectly, but we can swap the operands to fix both.
20671 std::swap(LHS, RHS);
20675 Opcode = X86ISD::FMIN;
20679 // Converting this to a max would handle NaNs incorrectly.
20680 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20682 Opcode = X86ISD::FMAX;
20685 // Converting this to a max would handle comparisons between positive
20686 // and negative zero incorrectly, and swapping the operands would
20687 // cause it to handle NaNs incorrectly.
20688 if (!DAG.getTarget().Options.UnsafeFPMath &&
20689 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20690 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20692 std::swap(LHS, RHS);
20694 Opcode = X86ISD::FMAX;
20697 // Converting this to a max would handle both negative zeros and NaNs
20698 // incorrectly, but we can swap the operands to fix both.
20699 std::swap(LHS, RHS);
20703 Opcode = X86ISD::FMAX;
20709 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20712 EVT CondVT = Cond.getValueType();
20713 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20714 CondVT.getVectorElementType() == MVT::i1) {
20715 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20716 // lowering on KNL. In this case we convert it to
20717 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20718 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20719 // Since SKX these selects have a proper lowering.
20720 EVT OpVT = LHS.getValueType();
20721 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20722 (OpVT.getVectorElementType() == MVT::i8 ||
20723 OpVT.getVectorElementType() == MVT::i16) &&
20724 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20725 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20726 DCI.AddToWorklist(Cond.getNode());
20727 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20730 // If this is a select between two integer constants, try to do some
20732 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20733 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20734 // Don't do this for crazy integer types.
20735 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20736 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20737 // so that TrueC (the true value) is larger than FalseC.
20738 bool NeedsCondInvert = false;
20740 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20741 // Efficiently invertible.
20742 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20743 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20744 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20745 NeedsCondInvert = true;
20746 std::swap(TrueC, FalseC);
20749 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20750 if (FalseC->getAPIntValue() == 0 &&
20751 TrueC->getAPIntValue().isPowerOf2()) {
20752 if (NeedsCondInvert) // Invert the condition if needed.
20753 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20754 DAG.getConstant(1, Cond.getValueType()));
20756 // Zero extend the condition if needed.
20757 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20759 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20760 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20761 DAG.getConstant(ShAmt, MVT::i8));
20764 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20765 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20766 if (NeedsCondInvert) // Invert the condition if needed.
20767 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20768 DAG.getConstant(1, Cond.getValueType()));
20770 // Zero extend the condition if needed.
20771 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20772 FalseC->getValueType(0), Cond);
20773 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20774 SDValue(FalseC, 0));
20777 // Optimize cases that will turn into an LEA instruction. This requires
20778 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20779 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20780 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20781 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20783 bool isFastMultiplier = false;
20785 switch ((unsigned char)Diff) {
20787 case 1: // result = add base, cond
20788 case 2: // result = lea base( , cond*2)
20789 case 3: // result = lea base(cond, cond*2)
20790 case 4: // result = lea base( , cond*4)
20791 case 5: // result = lea base(cond, cond*4)
20792 case 8: // result = lea base( , cond*8)
20793 case 9: // result = lea base(cond, cond*8)
20794 isFastMultiplier = true;
20799 if (isFastMultiplier) {
20800 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20801 if (NeedsCondInvert) // Invert the condition if needed.
20802 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20803 DAG.getConstant(1, Cond.getValueType()));
20805 // Zero extend the condition if needed.
20806 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20808 // Scale the condition by the difference.
20810 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20811 DAG.getConstant(Diff, Cond.getValueType()));
20813 // Add the base if non-zero.
20814 if (FalseC->getAPIntValue() != 0)
20815 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20816 SDValue(FalseC, 0));
20823 // Canonicalize max and min:
20824 // (x > y) ? x : y -> (x >= y) ? x : y
20825 // (x < y) ? x : y -> (x <= y) ? x : y
20826 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20827 // the need for an extra compare
20828 // against zero. e.g.
20829 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20831 // testl %edi, %edi
20833 // cmovgl %edi, %eax
20837 // cmovsl %eax, %edi
20838 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20839 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20840 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20841 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20846 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20847 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20848 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20849 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20854 // Early exit check
20855 if (!TLI.isTypeLegal(VT))
20858 // Match VSELECTs into subs with unsigned saturation.
20859 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20860 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20861 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20862 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20863 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20865 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20866 // left side invert the predicate to simplify logic below.
20868 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20870 CC = ISD::getSetCCInverse(CC, true);
20871 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20875 if (Other.getNode() && Other->getNumOperands() == 2 &&
20876 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20877 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20878 SDValue CondRHS = Cond->getOperand(1);
20880 // Look for a general sub with unsigned saturation first.
20881 // x >= y ? x-y : 0 --> subus x, y
20882 // x > y ? x-y : 0 --> subus x, y
20883 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20884 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20885 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20887 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20888 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20889 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20890 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20891 // If the RHS is a constant we have to reverse the const
20892 // canonicalization.
20893 // x > C-1 ? x+-C : 0 --> subus x, C
20894 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20895 CondRHSConst->getAPIntValue() ==
20896 (-OpRHSConst->getAPIntValue() - 1))
20897 return DAG.getNode(
20898 X86ISD::SUBUS, DL, VT, OpLHS,
20899 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20901 // Another special case: If C was a sign bit, the sub has been
20902 // canonicalized into a xor.
20903 // FIXME: Would it be better to use computeKnownBits to determine
20904 // whether it's safe to decanonicalize the xor?
20905 // x s< 0 ? x^C : 0 --> subus x, C
20906 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20907 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20908 OpRHSConst->getAPIntValue().isSignBit())
20909 // Note that we have to rebuild the RHS constant here to ensure we
20910 // don't rely on particular values of undef lanes.
20911 return DAG.getNode(
20912 X86ISD::SUBUS, DL, VT, OpLHS,
20913 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20918 // Try to match a min/max vector operation.
20919 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20920 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20921 unsigned Opc = ret.first;
20922 bool NeedSplit = ret.second;
20924 if (Opc && NeedSplit) {
20925 unsigned NumElems = VT.getVectorNumElements();
20926 // Extract the LHS vectors
20927 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20928 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20930 // Extract the RHS vectors
20931 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20932 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20934 // Create min/max for each subvector
20935 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20936 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20938 // Merge the result
20939 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20941 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20944 // Simplify vector selection if condition value type matches vselect
20946 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
20947 assert(Cond.getValueType().isVector() &&
20948 "vector select expects a vector selector!");
20950 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20951 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20953 // Try invert the condition if true value is not all 1s and false value
20955 if (!TValIsAllOnes && !FValIsAllZeros &&
20956 // Check if the selector will be produced by CMPP*/PCMP*
20957 Cond.getOpcode() == ISD::SETCC &&
20958 // Check if SETCC has already been promoted
20959 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
20960 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20961 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20963 if (TValIsAllZeros || FValIsAllOnes) {
20964 SDValue CC = Cond.getOperand(2);
20965 ISD::CondCode NewCC =
20966 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20967 Cond.getOperand(0).getValueType().isInteger());
20968 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20969 std::swap(LHS, RHS);
20970 TValIsAllOnes = FValIsAllOnes;
20971 FValIsAllZeros = TValIsAllZeros;
20975 if (TValIsAllOnes || FValIsAllZeros) {
20978 if (TValIsAllOnes && FValIsAllZeros)
20980 else if (TValIsAllOnes)
20981 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20982 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20983 else if (FValIsAllZeros)
20984 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20985 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20987 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20991 // We should generate an X86ISD::BLENDI from a vselect if its argument
20992 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20993 // constants. This specific pattern gets generated when we split a
20994 // selector for a 512 bit vector in a machine without AVX512 (but with
20995 // 256-bit vectors), during legalization:
20997 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20999 // Iff we find this pattern and the build_vectors are built from
21000 // constants, we translate the vselect into a shuffle_vector that we
21001 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21002 if ((N->getOpcode() == ISD::VSELECT ||
21003 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21004 !DCI.isBeforeLegalize()) {
21005 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21006 if (Shuffle.getNode())
21010 // If this is a *dynamic* select (non-constant condition) and we can match
21011 // this node with one of the variable blend instructions, restructure the
21012 // condition so that the blends can use the high bit of each element and use
21013 // SimplifyDemandedBits to simplify the condition operand.
21014 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21015 !DCI.isBeforeLegalize() &&
21016 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21017 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21019 // Don't optimize vector selects that map to mask-registers.
21023 // We can only handle the cases where VSELECT is directly legal on the
21024 // subtarget. We custom lower VSELECT nodes with constant conditions and
21025 // this makes it hard to see whether a dynamic VSELECT will correctly
21026 // lower, so we both check the operation's status and explicitly handle the
21027 // cases where a *dynamic* blend will fail even though a constant-condition
21028 // blend could be custom lowered.
21029 // FIXME: We should find a better way to handle this class of problems.
21030 // Potentially, we should combine constant-condition vselect nodes
21031 // pre-legalization into shuffles and not mark as many types as custom
21033 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21035 // FIXME: We don't support i16-element blends currently. We could and
21036 // should support them by making *all* the bits in the condition be set
21037 // rather than just the high bit and using an i8-element blend.
21038 if (VT.getScalarType() == MVT::i16)
21040 // Dynamic blending was only available from SSE4.1 onward.
21041 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21043 // Byte blends are only available in AVX2
21044 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21045 !Subtarget->hasAVX2())
21048 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21049 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21051 APInt KnownZero, KnownOne;
21052 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21053 DCI.isBeforeLegalizeOps());
21054 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21055 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21057 // If we changed the computation somewhere in the DAG, this change
21058 // will affect all users of Cond.
21059 // Make sure it is fine and update all the nodes so that we do not
21060 // use the generic VSELECT anymore. Otherwise, we may perform
21061 // wrong optimizations as we messed up with the actual expectation
21062 // for the vector boolean values.
21063 if (Cond != TLO.Old) {
21064 // Check all uses of that condition operand to check whether it will be
21065 // consumed by non-BLEND instructions, which may depend on all bits are
21067 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21069 if (I->getOpcode() != ISD::VSELECT)
21070 // TODO: Add other opcodes eventually lowered into BLEND.
21073 // Update all the users of the condition, before committing the change,
21074 // so that the VSELECT optimizations that expect the correct vector
21075 // boolean value will not be triggered.
21076 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21078 DAG.ReplaceAllUsesOfValueWith(
21080 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21081 Cond, I->getOperand(1), I->getOperand(2)));
21082 DCI.CommitTargetLoweringOpt(TLO);
21085 // At this point, only Cond is changed. Change the condition
21086 // just for N to keep the opportunity to optimize all other
21087 // users their own way.
21088 DAG.ReplaceAllUsesOfValueWith(
21090 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21091 TLO.New, N->getOperand(1), N->getOperand(2)));
21099 // Check whether a boolean test is testing a boolean value generated by
21100 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21103 // Simplify the following patterns:
21104 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21105 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21106 // to (Op EFLAGS Cond)
21108 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21109 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21110 // to (Op EFLAGS !Cond)
21112 // where Op could be BRCOND or CMOV.
21114 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21115 // Quit if not CMP and SUB with its value result used.
21116 if (Cmp.getOpcode() != X86ISD::CMP &&
21117 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21120 // Quit if not used as a boolean value.
21121 if (CC != X86::COND_E && CC != X86::COND_NE)
21124 // Check CMP operands. One of them should be 0 or 1 and the other should be
21125 // an SetCC or extended from it.
21126 SDValue Op1 = Cmp.getOperand(0);
21127 SDValue Op2 = Cmp.getOperand(1);
21130 const ConstantSDNode* C = nullptr;
21131 bool needOppositeCond = (CC == X86::COND_E);
21132 bool checkAgainstTrue = false; // Is it a comparison against 1?
21134 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21136 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21138 else // Quit if all operands are not constants.
21141 if (C->getZExtValue() == 1) {
21142 needOppositeCond = !needOppositeCond;
21143 checkAgainstTrue = true;
21144 } else if (C->getZExtValue() != 0)
21145 // Quit if the constant is neither 0 or 1.
21148 bool truncatedToBoolWithAnd = false;
21149 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21150 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21151 SetCC.getOpcode() == ISD::TRUNCATE ||
21152 SetCC.getOpcode() == ISD::AND) {
21153 if (SetCC.getOpcode() == ISD::AND) {
21155 ConstantSDNode *CS;
21156 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21157 CS->getZExtValue() == 1)
21159 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21160 CS->getZExtValue() == 1)
21164 SetCC = SetCC.getOperand(OpIdx);
21165 truncatedToBoolWithAnd = true;
21167 SetCC = SetCC.getOperand(0);
21170 switch (SetCC.getOpcode()) {
21171 case X86ISD::SETCC_CARRY:
21172 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21173 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21174 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21175 // truncated to i1 using 'and'.
21176 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21178 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21179 "Invalid use of SETCC_CARRY!");
21181 case X86ISD::SETCC:
21182 // Set the condition code or opposite one if necessary.
21183 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21184 if (needOppositeCond)
21185 CC = X86::GetOppositeBranchCondition(CC);
21186 return SetCC.getOperand(1);
21187 case X86ISD::CMOV: {
21188 // Check whether false/true value has canonical one, i.e. 0 or 1.
21189 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21190 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21191 // Quit if true value is not a constant.
21194 // Quit if false value is not a constant.
21196 SDValue Op = SetCC.getOperand(0);
21197 // Skip 'zext' or 'trunc' node.
21198 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21199 Op.getOpcode() == ISD::TRUNCATE)
21200 Op = Op.getOperand(0);
21201 // A special case for rdrand/rdseed, where 0 is set if false cond is
21203 if ((Op.getOpcode() != X86ISD::RDRAND &&
21204 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21207 // Quit if false value is not the constant 0 or 1.
21208 bool FValIsFalse = true;
21209 if (FVal && FVal->getZExtValue() != 0) {
21210 if (FVal->getZExtValue() != 1)
21212 // If FVal is 1, opposite cond is needed.
21213 needOppositeCond = !needOppositeCond;
21214 FValIsFalse = false;
21216 // Quit if TVal is not the constant opposite of FVal.
21217 if (FValIsFalse && TVal->getZExtValue() != 1)
21219 if (!FValIsFalse && TVal->getZExtValue() != 0)
21221 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21222 if (needOppositeCond)
21223 CC = X86::GetOppositeBranchCondition(CC);
21224 return SetCC.getOperand(3);
21231 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21233 /// (X86or (X86setcc) (X86setcc))
21234 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21235 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21236 X86::CondCode &CC1, SDValue &Flags,
21238 if (Cond->getOpcode() == X86ISD::CMP) {
21239 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21240 if (!CondOp1C || !CondOp1C->isNullValue())
21243 Cond = Cond->getOperand(0);
21248 SDValue SetCC0, SetCC1;
21249 switch (Cond->getOpcode()) {
21250 default: return false;
21257 SetCC0 = Cond->getOperand(0);
21258 SetCC1 = Cond->getOperand(1);
21262 // Make sure we have SETCC nodes, using the same flags value.
21263 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21264 SetCC1.getOpcode() != X86ISD::SETCC ||
21265 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21268 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21269 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21270 Flags = SetCC0->getOperand(1);
21274 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21275 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21276 TargetLowering::DAGCombinerInfo &DCI,
21277 const X86Subtarget *Subtarget) {
21280 // If the flag operand isn't dead, don't touch this CMOV.
21281 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21284 SDValue FalseOp = N->getOperand(0);
21285 SDValue TrueOp = N->getOperand(1);
21286 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21287 SDValue Cond = N->getOperand(3);
21289 if (CC == X86::COND_E || CC == X86::COND_NE) {
21290 switch (Cond.getOpcode()) {
21294 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21295 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21296 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21302 Flags = checkBoolTestSetCCCombine(Cond, CC);
21303 if (Flags.getNode() &&
21304 // Extra check as FCMOV only supports a subset of X86 cond.
21305 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21306 SDValue Ops[] = { FalseOp, TrueOp,
21307 DAG.getConstant(CC, MVT::i8), Flags };
21308 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21311 // If this is a select between two integer constants, try to do some
21312 // optimizations. Note that the operands are ordered the opposite of SELECT
21314 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21315 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21316 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21317 // larger than FalseC (the false value).
21318 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21319 CC = X86::GetOppositeBranchCondition(CC);
21320 std::swap(TrueC, FalseC);
21321 std::swap(TrueOp, FalseOp);
21324 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21325 // This is efficient for any integer data type (including i8/i16) and
21327 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21328 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21329 DAG.getConstant(CC, MVT::i8), Cond);
21331 // Zero extend the condition if needed.
21332 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21334 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21335 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21336 DAG.getConstant(ShAmt, MVT::i8));
21337 if (N->getNumValues() == 2) // Dead flag value?
21338 return DCI.CombineTo(N, Cond, SDValue());
21342 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21343 // for any integer data type, including i8/i16.
21344 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21345 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21346 DAG.getConstant(CC, MVT::i8), Cond);
21348 // Zero extend the condition if needed.
21349 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21350 FalseC->getValueType(0), Cond);
21351 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21352 SDValue(FalseC, 0));
21354 if (N->getNumValues() == 2) // Dead flag value?
21355 return DCI.CombineTo(N, Cond, SDValue());
21359 // Optimize cases that will turn into an LEA instruction. This requires
21360 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21361 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21362 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21363 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21365 bool isFastMultiplier = false;
21367 switch ((unsigned char)Diff) {
21369 case 1: // result = add base, cond
21370 case 2: // result = lea base( , cond*2)
21371 case 3: // result = lea base(cond, cond*2)
21372 case 4: // result = lea base( , cond*4)
21373 case 5: // result = lea base(cond, cond*4)
21374 case 8: // result = lea base( , cond*8)
21375 case 9: // result = lea base(cond, cond*8)
21376 isFastMultiplier = true;
21381 if (isFastMultiplier) {
21382 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21383 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21384 DAG.getConstant(CC, MVT::i8), Cond);
21385 // Zero extend the condition if needed.
21386 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21388 // Scale the condition by the difference.
21390 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21391 DAG.getConstant(Diff, Cond.getValueType()));
21393 // Add the base if non-zero.
21394 if (FalseC->getAPIntValue() != 0)
21395 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21396 SDValue(FalseC, 0));
21397 if (N->getNumValues() == 2) // Dead flag value?
21398 return DCI.CombineTo(N, Cond, SDValue());
21405 // Handle these cases:
21406 // (select (x != c), e, c) -> select (x != c), e, x),
21407 // (select (x == c), c, e) -> select (x == c), x, e)
21408 // where the c is an integer constant, and the "select" is the combination
21409 // of CMOV and CMP.
21411 // The rationale for this change is that the conditional-move from a constant
21412 // needs two instructions, however, conditional-move from a register needs
21413 // only one instruction.
21415 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21416 // some instruction-combining opportunities. This opt needs to be
21417 // postponed as late as possible.
21419 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21420 // the DCI.xxxx conditions are provided to postpone the optimization as
21421 // late as possible.
21423 ConstantSDNode *CmpAgainst = nullptr;
21424 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21425 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21426 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21428 if (CC == X86::COND_NE &&
21429 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21430 CC = X86::GetOppositeBranchCondition(CC);
21431 std::swap(TrueOp, FalseOp);
21434 if (CC == X86::COND_E &&
21435 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21436 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21437 DAG.getConstant(CC, MVT::i8), Cond };
21438 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21443 // Fold and/or of setcc's to double CMOV:
21444 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21445 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21447 // This combine lets us generate:
21448 // cmovcc1 (jcc1 if we don't have CMOV)
21454 // cmovne (jne if we don't have CMOV)
21455 // When we can't use the CMOV instruction, it might increase branch
21457 // When we can use CMOV, or when there is no mispredict, this improves
21458 // throughput and reduces register pressure.
21460 if (CC == X86::COND_NE) {
21462 X86::CondCode CC0, CC1;
21464 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21466 std::swap(FalseOp, TrueOp);
21467 CC0 = X86::GetOppositeBranchCondition(CC0);
21468 CC1 = X86::GetOppositeBranchCondition(CC1);
21471 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21473 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21474 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21475 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21476 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21484 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21485 const X86Subtarget *Subtarget) {
21486 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21488 default: return SDValue();
21489 // SSE/AVX/AVX2 blend intrinsics.
21490 case Intrinsic::x86_avx2_pblendvb:
21491 // Don't try to simplify this intrinsic if we don't have AVX2.
21492 if (!Subtarget->hasAVX2())
21495 case Intrinsic::x86_avx_blendv_pd_256:
21496 case Intrinsic::x86_avx_blendv_ps_256:
21497 // Don't try to simplify this intrinsic if we don't have AVX.
21498 if (!Subtarget->hasAVX())
21501 case Intrinsic::x86_sse41_blendvps:
21502 case Intrinsic::x86_sse41_blendvpd:
21503 case Intrinsic::x86_sse41_pblendvb: {
21504 SDValue Op0 = N->getOperand(1);
21505 SDValue Op1 = N->getOperand(2);
21506 SDValue Mask = N->getOperand(3);
21508 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21509 if (!Subtarget->hasSSE41())
21512 // fold (blend A, A, Mask) -> A
21515 // fold (blend A, B, allZeros) -> A
21516 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21518 // fold (blend A, B, allOnes) -> B
21519 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21522 // Simplify the case where the mask is a constant i32 value.
21523 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21524 if (C->isNullValue())
21526 if (C->isAllOnesValue())
21533 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21534 case Intrinsic::x86_sse2_psrai_w:
21535 case Intrinsic::x86_sse2_psrai_d:
21536 case Intrinsic::x86_avx2_psrai_w:
21537 case Intrinsic::x86_avx2_psrai_d:
21538 case Intrinsic::x86_sse2_psra_w:
21539 case Intrinsic::x86_sse2_psra_d:
21540 case Intrinsic::x86_avx2_psra_w:
21541 case Intrinsic::x86_avx2_psra_d: {
21542 SDValue Op0 = N->getOperand(1);
21543 SDValue Op1 = N->getOperand(2);
21544 EVT VT = Op0.getValueType();
21545 assert(VT.isVector() && "Expected a vector type!");
21547 if (isa<BuildVectorSDNode>(Op1))
21548 Op1 = Op1.getOperand(0);
21550 if (!isa<ConstantSDNode>(Op1))
21553 EVT SVT = VT.getVectorElementType();
21554 unsigned SVTBits = SVT.getSizeInBits();
21556 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21557 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21558 uint64_t ShAmt = C.getZExtValue();
21560 // Don't try to convert this shift into a ISD::SRA if the shift
21561 // count is bigger than or equal to the element size.
21562 if (ShAmt >= SVTBits)
21565 // Trivial case: if the shift count is zero, then fold this
21566 // into the first operand.
21570 // Replace this packed shift intrinsic with a target independent
21572 SDValue Splat = DAG.getConstant(C, VT);
21573 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21578 /// PerformMulCombine - Optimize a single multiply with constant into two
21579 /// in order to implement it with two cheaper instructions, e.g.
21580 /// LEA + SHL, LEA + LEA.
21581 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21582 TargetLowering::DAGCombinerInfo &DCI) {
21583 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21586 EVT VT = N->getValueType(0);
21587 if (VT != MVT::i64 && VT != MVT::i32)
21590 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21593 uint64_t MulAmt = C->getZExtValue();
21594 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21597 uint64_t MulAmt1 = 0;
21598 uint64_t MulAmt2 = 0;
21599 if ((MulAmt % 9) == 0) {
21601 MulAmt2 = MulAmt / 9;
21602 } else if ((MulAmt % 5) == 0) {
21604 MulAmt2 = MulAmt / 5;
21605 } else if ((MulAmt % 3) == 0) {
21607 MulAmt2 = MulAmt / 3;
21610 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21613 if (isPowerOf2_64(MulAmt2) &&
21614 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21615 // If second multiplifer is pow2, issue it first. We want the multiply by
21616 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21618 std::swap(MulAmt1, MulAmt2);
21621 if (isPowerOf2_64(MulAmt1))
21622 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21623 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21625 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21626 DAG.getConstant(MulAmt1, VT));
21628 if (isPowerOf2_64(MulAmt2))
21629 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21630 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21632 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21633 DAG.getConstant(MulAmt2, VT));
21635 // Do not add new nodes to DAG combiner worklist.
21636 DCI.CombineTo(N, NewMul, false);
21641 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21642 SDValue N0 = N->getOperand(0);
21643 SDValue N1 = N->getOperand(1);
21644 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21645 EVT VT = N0.getValueType();
21647 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21648 // since the result of setcc_c is all zero's or all ones.
21649 if (VT.isInteger() && !VT.isVector() &&
21650 N1C && N0.getOpcode() == ISD::AND &&
21651 N0.getOperand(1).getOpcode() == ISD::Constant) {
21652 SDValue N00 = N0.getOperand(0);
21653 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21654 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21655 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21656 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21657 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21658 APInt ShAmt = N1C->getAPIntValue();
21659 Mask = Mask.shl(ShAmt);
21661 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21662 N00, DAG.getConstant(Mask, VT));
21666 // Hardware support for vector shifts is sparse which makes us scalarize the
21667 // vector operations in many cases. Also, on sandybridge ADD is faster than
21669 // (shl V, 1) -> add V,V
21670 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21671 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21672 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21673 // We shift all of the values by one. In many cases we do not have
21674 // hardware support for this operation. This is better expressed as an ADD
21676 if (N1SplatC->getZExtValue() == 1)
21677 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21683 /// \brief Returns a vector of 0s if the node in input is a vector logical
21684 /// shift by a constant amount which is known to be bigger than or equal
21685 /// to the vector element size in bits.
21686 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21687 const X86Subtarget *Subtarget) {
21688 EVT VT = N->getValueType(0);
21690 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21691 (!Subtarget->hasInt256() ||
21692 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21695 SDValue Amt = N->getOperand(1);
21697 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21698 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21699 APInt ShiftAmt = AmtSplat->getAPIntValue();
21700 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21702 // SSE2/AVX2 logical shifts always return a vector of 0s
21703 // if the shift amount is bigger than or equal to
21704 // the element size. The constant shift amount will be
21705 // encoded as a 8-bit immediate.
21706 if (ShiftAmt.trunc(8).uge(MaxAmount))
21707 return getZeroVector(VT, Subtarget, DAG, DL);
21713 /// PerformShiftCombine - Combine shifts.
21714 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21715 TargetLowering::DAGCombinerInfo &DCI,
21716 const X86Subtarget *Subtarget) {
21717 if (N->getOpcode() == ISD::SHL) {
21718 SDValue V = PerformSHLCombine(N, DAG);
21719 if (V.getNode()) return V;
21722 if (N->getOpcode() != ISD::SRA) {
21723 // Try to fold this logical shift into a zero vector.
21724 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21725 if (V.getNode()) return V;
21731 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21732 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21733 // and friends. Likewise for OR -> CMPNEQSS.
21734 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21735 TargetLowering::DAGCombinerInfo &DCI,
21736 const X86Subtarget *Subtarget) {
21739 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21740 // we're requiring SSE2 for both.
21741 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21742 SDValue N0 = N->getOperand(0);
21743 SDValue N1 = N->getOperand(1);
21744 SDValue CMP0 = N0->getOperand(1);
21745 SDValue CMP1 = N1->getOperand(1);
21748 // The SETCCs should both refer to the same CMP.
21749 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21752 SDValue CMP00 = CMP0->getOperand(0);
21753 SDValue CMP01 = CMP0->getOperand(1);
21754 EVT VT = CMP00.getValueType();
21756 if (VT == MVT::f32 || VT == MVT::f64) {
21757 bool ExpectingFlags = false;
21758 // Check for any users that want flags:
21759 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21760 !ExpectingFlags && UI != UE; ++UI)
21761 switch (UI->getOpcode()) {
21766 ExpectingFlags = true;
21768 case ISD::CopyToReg:
21769 case ISD::SIGN_EXTEND:
21770 case ISD::ZERO_EXTEND:
21771 case ISD::ANY_EXTEND:
21775 if (!ExpectingFlags) {
21776 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21777 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21779 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21780 X86::CondCode tmp = cc0;
21785 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21786 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21787 // FIXME: need symbolic constants for these magic numbers.
21788 // See X86ATTInstPrinter.cpp:printSSECC().
21789 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21790 if (Subtarget->hasAVX512()) {
21791 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21792 CMP01, DAG.getConstant(x86cc, MVT::i8));
21793 if (N->getValueType(0) != MVT::i1)
21794 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21798 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21799 CMP00.getValueType(), CMP00, CMP01,
21800 DAG.getConstant(x86cc, MVT::i8));
21802 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21803 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21805 if (is64BitFP && !Subtarget->is64Bit()) {
21806 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21807 // 64-bit integer, since that's not a legal type. Since
21808 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21809 // bits, but can do this little dance to extract the lowest 32 bits
21810 // and work with those going forward.
21811 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21813 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21815 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21816 Vector32, DAG.getIntPtrConstant(0));
21820 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21821 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21822 DAG.getConstant(1, IntVT));
21823 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21824 return OneBitOfTruth;
21832 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21833 /// so it can be folded inside ANDNP.
21834 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21835 EVT VT = N->getValueType(0);
21837 // Match direct AllOnes for 128 and 256-bit vectors
21838 if (ISD::isBuildVectorAllOnes(N))
21841 // Look through a bit convert.
21842 if (N->getOpcode() == ISD::BITCAST)
21843 N = N->getOperand(0).getNode();
21845 // Sometimes the operand may come from a insert_subvector building a 256-bit
21847 if (VT.is256BitVector() &&
21848 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21849 SDValue V1 = N->getOperand(0);
21850 SDValue V2 = N->getOperand(1);
21852 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21853 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21854 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21855 ISD::isBuildVectorAllOnes(V2.getNode()))
21862 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21863 // register. In most cases we actually compare or select YMM-sized registers
21864 // and mixing the two types creates horrible code. This method optimizes
21865 // some of the transition sequences.
21866 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21867 TargetLowering::DAGCombinerInfo &DCI,
21868 const X86Subtarget *Subtarget) {
21869 EVT VT = N->getValueType(0);
21870 if (!VT.is256BitVector())
21873 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21874 N->getOpcode() == ISD::ZERO_EXTEND ||
21875 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21877 SDValue Narrow = N->getOperand(0);
21878 EVT NarrowVT = Narrow->getValueType(0);
21879 if (!NarrowVT.is128BitVector())
21882 if (Narrow->getOpcode() != ISD::XOR &&
21883 Narrow->getOpcode() != ISD::AND &&
21884 Narrow->getOpcode() != ISD::OR)
21887 SDValue N0 = Narrow->getOperand(0);
21888 SDValue N1 = Narrow->getOperand(1);
21891 // The Left side has to be a trunc.
21892 if (N0.getOpcode() != ISD::TRUNCATE)
21895 // The type of the truncated inputs.
21896 EVT WideVT = N0->getOperand(0)->getValueType(0);
21900 // The right side has to be a 'trunc' or a constant vector.
21901 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21902 ConstantSDNode *RHSConstSplat = nullptr;
21903 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21904 RHSConstSplat = RHSBV->getConstantSplatNode();
21905 if (!RHSTrunc && !RHSConstSplat)
21908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21910 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21913 // Set N0 and N1 to hold the inputs to the new wide operation.
21914 N0 = N0->getOperand(0);
21915 if (RHSConstSplat) {
21916 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21917 SDValue(RHSConstSplat, 0));
21918 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21919 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21920 } else if (RHSTrunc) {
21921 N1 = N1->getOperand(0);
21924 // Generate the wide operation.
21925 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21926 unsigned Opcode = N->getOpcode();
21928 case ISD::ANY_EXTEND:
21930 case ISD::ZERO_EXTEND: {
21931 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21932 APInt Mask = APInt::getAllOnesValue(InBits);
21933 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21934 return DAG.getNode(ISD::AND, DL, VT,
21935 Op, DAG.getConstant(Mask, VT));
21937 case ISD::SIGN_EXTEND:
21938 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21939 Op, DAG.getValueType(NarrowVT));
21941 llvm_unreachable("Unexpected opcode");
21945 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
21946 TargetLowering::DAGCombinerInfo &DCI,
21947 const X86Subtarget *Subtarget) {
21948 SDValue N0 = N->getOperand(0);
21949 SDValue N1 = N->getOperand(1);
21952 // A vector zext_in_reg may be represented as a shuffle,
21953 // feeding into a bitcast (this represents anyext) feeding into
21954 // an and with a mask.
21955 // We'd like to try to combine that into a shuffle with zero
21956 // plus a bitcast, removing the and.
21957 if (N0.getOpcode() != ISD::BITCAST ||
21958 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
21961 // The other side of the AND should be a splat of 2^C, where C
21962 // is the number of bits in the source type.
21963 if (N1.getOpcode() == ISD::BITCAST)
21964 N1 = N1.getOperand(0);
21965 if (N1.getOpcode() != ISD::BUILD_VECTOR)
21967 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
21969 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
21970 EVT SrcType = Shuffle->getValueType(0);
21972 // We expect a single-source shuffle
21973 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
21976 unsigned SrcSize = SrcType.getScalarSizeInBits();
21978 APInt SplatValue, SplatUndef;
21979 unsigned SplatBitSize;
21981 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
21982 SplatBitSize, HasAnyUndefs))
21985 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
21986 // Make sure the splat matches the mask we expect
21987 if (SplatBitSize > ResSize ||
21988 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
21991 // Make sure the input and output size make sense
21992 if (SrcSize >= ResSize || ResSize % SrcSize)
21995 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
21996 // The number of u's between each two values depends on the ratio between
21997 // the source and dest type.
21998 unsigned ZextRatio = ResSize / SrcSize;
21999 bool IsZext = true;
22000 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22001 if (i % ZextRatio) {
22002 if (Shuffle->getMaskElt(i) > 0) {
22008 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22009 // Expected element number
22019 // Ok, perform the transformation - replace the shuffle with
22020 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22021 // (instead of undef) where the k elements come from the zero vector.
22022 SmallVector<int, 8> Mask;
22023 unsigned NumElems = SrcType.getVectorNumElements();
22024 for (unsigned i = 0; i < NumElems; ++i)
22026 Mask.push_back(NumElems);
22028 Mask.push_back(i / ZextRatio);
22030 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22031 Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22032 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22035 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22036 TargetLowering::DAGCombinerInfo &DCI,
22037 const X86Subtarget *Subtarget) {
22038 if (DCI.isBeforeLegalizeOps())
22041 SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget);
22042 if (Zext.getNode())
22045 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22049 EVT VT = N->getValueType(0);
22050 SDValue N0 = N->getOperand(0);
22051 SDValue N1 = N->getOperand(1);
22054 // Create BEXTR instructions
22055 // BEXTR is ((X >> imm) & (2**size-1))
22056 if (VT == MVT::i32 || VT == MVT::i64) {
22057 // Check for BEXTR.
22058 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22059 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22060 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22061 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22062 if (MaskNode && ShiftNode) {
22063 uint64_t Mask = MaskNode->getZExtValue();
22064 uint64_t Shift = ShiftNode->getZExtValue();
22065 if (isMask_64(Mask)) {
22066 uint64_t MaskSize = countPopulation(Mask);
22067 if (Shift + MaskSize <= VT.getSizeInBits())
22068 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22069 DAG.getConstant(Shift | (MaskSize << 8), VT));
22077 // Want to form ANDNP nodes:
22078 // 1) In the hopes of then easily combining them with OR and AND nodes
22079 // to form PBLEND/PSIGN.
22080 // 2) To match ANDN packed intrinsics
22081 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22084 // Check LHS for vnot
22085 if (N0.getOpcode() == ISD::XOR &&
22086 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22087 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22088 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22090 // Check RHS for vnot
22091 if (N1.getOpcode() == ISD::XOR &&
22092 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22093 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22094 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22099 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22100 TargetLowering::DAGCombinerInfo &DCI,
22101 const X86Subtarget *Subtarget) {
22102 if (DCI.isBeforeLegalizeOps())
22105 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22109 SDValue N0 = N->getOperand(0);
22110 SDValue N1 = N->getOperand(1);
22111 EVT VT = N->getValueType(0);
22113 // look for psign/blend
22114 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22115 if (!Subtarget->hasSSSE3() ||
22116 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22119 // Canonicalize pandn to RHS
22120 if (N0.getOpcode() == X86ISD::ANDNP)
22122 // or (and (m, y), (pandn m, x))
22123 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22124 SDValue Mask = N1.getOperand(0);
22125 SDValue X = N1.getOperand(1);
22127 if (N0.getOperand(0) == Mask)
22128 Y = N0.getOperand(1);
22129 if (N0.getOperand(1) == Mask)
22130 Y = N0.getOperand(0);
22132 // Check to see if the mask appeared in both the AND and ANDNP and
22136 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22137 // Look through mask bitcast.
22138 if (Mask.getOpcode() == ISD::BITCAST)
22139 Mask = Mask.getOperand(0);
22140 if (X.getOpcode() == ISD::BITCAST)
22141 X = X.getOperand(0);
22142 if (Y.getOpcode() == ISD::BITCAST)
22143 Y = Y.getOperand(0);
22145 EVT MaskVT = Mask.getValueType();
22147 // Validate that the Mask operand is a vector sra node.
22148 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22149 // there is no psrai.b
22150 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22151 unsigned SraAmt = ~0;
22152 if (Mask.getOpcode() == ISD::SRA) {
22153 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22154 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22155 SraAmt = AmtConst->getZExtValue();
22156 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22157 SDValue SraC = Mask.getOperand(1);
22158 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22160 if ((SraAmt + 1) != EltBits)
22165 // Now we know we at least have a plendvb with the mask val. See if
22166 // we can form a psignb/w/d.
22167 // psign = x.type == y.type == mask.type && y = sub(0, x);
22168 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22169 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22170 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22171 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22172 "Unsupported VT for PSIGN");
22173 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22174 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22176 // PBLENDVB only available on SSE 4.1
22177 if (!Subtarget->hasSSE41())
22180 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22182 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22183 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22184 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22185 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22186 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22190 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22193 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22194 MachineFunction &MF = DAG.getMachineFunction();
22196 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22198 // SHLD/SHRD instructions have lower register pressure, but on some
22199 // platforms they have higher latency than the equivalent
22200 // series of shifts/or that would otherwise be generated.
22201 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22202 // have higher latencies and we are not optimizing for size.
22203 if (!OptForSize && Subtarget->isSHLDSlow())
22206 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22208 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22210 if (!N0.hasOneUse() || !N1.hasOneUse())
22213 SDValue ShAmt0 = N0.getOperand(1);
22214 if (ShAmt0.getValueType() != MVT::i8)
22216 SDValue ShAmt1 = N1.getOperand(1);
22217 if (ShAmt1.getValueType() != MVT::i8)
22219 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22220 ShAmt0 = ShAmt0.getOperand(0);
22221 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22222 ShAmt1 = ShAmt1.getOperand(0);
22225 unsigned Opc = X86ISD::SHLD;
22226 SDValue Op0 = N0.getOperand(0);
22227 SDValue Op1 = N1.getOperand(0);
22228 if (ShAmt0.getOpcode() == ISD::SUB) {
22229 Opc = X86ISD::SHRD;
22230 std::swap(Op0, Op1);
22231 std::swap(ShAmt0, ShAmt1);
22234 unsigned Bits = VT.getSizeInBits();
22235 if (ShAmt1.getOpcode() == ISD::SUB) {
22236 SDValue Sum = ShAmt1.getOperand(0);
22237 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22238 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22239 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22240 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22241 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22242 return DAG.getNode(Opc, DL, VT,
22244 DAG.getNode(ISD::TRUNCATE, DL,
22247 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22248 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22250 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22251 return DAG.getNode(Opc, DL, VT,
22252 N0.getOperand(0), N1.getOperand(0),
22253 DAG.getNode(ISD::TRUNCATE, DL,
22260 // Generate NEG and CMOV for integer abs.
22261 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22262 EVT VT = N->getValueType(0);
22264 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22265 // 8-bit integer abs to NEG and CMOV.
22266 if (VT.isInteger() && VT.getSizeInBits() == 8)
22269 SDValue N0 = N->getOperand(0);
22270 SDValue N1 = N->getOperand(1);
22273 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22274 // and change it to SUB and CMOV.
22275 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22276 N0.getOpcode() == ISD::ADD &&
22277 N0.getOperand(1) == N1 &&
22278 N1.getOpcode() == ISD::SRA &&
22279 N1.getOperand(0) == N0.getOperand(0))
22280 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22281 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22282 // Generate SUB & CMOV.
22283 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22284 DAG.getConstant(0, VT), N0.getOperand(0));
22286 SDValue Ops[] = { N0.getOperand(0), Neg,
22287 DAG.getConstant(X86::COND_GE, MVT::i8),
22288 SDValue(Neg.getNode(), 1) };
22289 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22294 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22295 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22296 TargetLowering::DAGCombinerInfo &DCI,
22297 const X86Subtarget *Subtarget) {
22298 if (DCI.isBeforeLegalizeOps())
22301 if (Subtarget->hasCMov()) {
22302 SDValue RV = performIntegerAbsCombine(N, DAG);
22310 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22311 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22312 TargetLowering::DAGCombinerInfo &DCI,
22313 const X86Subtarget *Subtarget) {
22314 LoadSDNode *Ld = cast<LoadSDNode>(N);
22315 EVT RegVT = Ld->getValueType(0);
22316 EVT MemVT = Ld->getMemoryVT();
22318 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22320 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22321 // into two 16-byte operations.
22322 ISD::LoadExtType Ext = Ld->getExtensionType();
22323 unsigned Alignment = Ld->getAlignment();
22324 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22325 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22326 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22327 unsigned NumElems = RegVT.getVectorNumElements();
22331 SDValue Ptr = Ld->getBasePtr();
22332 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22334 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22336 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22337 Ld->getPointerInfo(), Ld->isVolatile(),
22338 Ld->isNonTemporal(), Ld->isInvariant(),
22340 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22341 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22342 Ld->getPointerInfo(), Ld->isVolatile(),
22343 Ld->isNonTemporal(), Ld->isInvariant(),
22344 std::min(16U, Alignment));
22345 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22347 Load2.getValue(1));
22349 SDValue NewVec = DAG.getUNDEF(RegVT);
22350 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22351 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22352 return DCI.CombineTo(N, NewVec, TF, true);
22358 /// PerformMLOADCombine - Resolve extending loads
22359 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22360 TargetLowering::DAGCombinerInfo &DCI,
22361 const X86Subtarget *Subtarget) {
22362 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22363 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22366 EVT VT = Mld->getValueType(0);
22367 unsigned NumElems = VT.getVectorNumElements();
22368 EVT LdVT = Mld->getMemoryVT();
22371 assert(LdVT != VT && "Cannot extend to the same type");
22372 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22373 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22374 // From, To sizes and ElemCount must be pow of two
22375 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22376 "Unexpected size for extending masked load");
22378 unsigned SizeRatio = ToSz / FromSz;
22379 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22381 // Create a type on which we perform the shuffle
22382 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22383 LdVT.getScalarType(), NumElems*SizeRatio);
22384 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22386 // Convert Src0 value
22387 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22388 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22389 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22390 for (unsigned i = 0; i != NumElems; ++i)
22391 ShuffleVec[i] = i * SizeRatio;
22393 // Can't shuffle using an illegal type.
22394 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22395 && "WideVecVT should be legal");
22396 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22397 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22399 // Prepare the new mask
22401 SDValue Mask = Mld->getMask();
22402 if (Mask.getValueType() == VT) {
22403 // Mask and original value have the same type
22404 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22405 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22406 for (unsigned i = 0; i != NumElems; ++i)
22407 ShuffleVec[i] = i * SizeRatio;
22408 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22409 ShuffleVec[i] = NumElems*SizeRatio;
22410 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22411 DAG.getConstant(0, WideVecVT),
22415 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22416 unsigned WidenNumElts = NumElems*SizeRatio;
22417 unsigned MaskNumElts = VT.getVectorNumElements();
22418 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22421 unsigned NumConcat = WidenNumElts / MaskNumElts;
22422 SmallVector<SDValue, 16> Ops(NumConcat);
22423 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22425 for (unsigned i = 1; i != NumConcat; ++i)
22428 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22431 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22432 Mld->getBasePtr(), NewMask, WideSrc0,
22433 Mld->getMemoryVT(), Mld->getMemOperand(),
22435 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22436 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22439 /// PerformMSTORECombine - Resolve truncating stores
22440 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22441 const X86Subtarget *Subtarget) {
22442 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22443 if (!Mst->isTruncatingStore())
22446 EVT VT = Mst->getValue().getValueType();
22447 unsigned NumElems = VT.getVectorNumElements();
22448 EVT StVT = Mst->getMemoryVT();
22451 assert(StVT != VT && "Cannot truncate to the same type");
22452 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22453 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22455 // From, To sizes and ElemCount must be pow of two
22456 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22457 "Unexpected size for truncating masked store");
22458 // We are going to use the original vector elt for storing.
22459 // Accumulated smaller vector elements must be a multiple of the store size.
22460 assert (((NumElems * FromSz) % ToSz) == 0 &&
22461 "Unexpected ratio for truncating masked store");
22463 unsigned SizeRatio = FromSz / ToSz;
22464 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22466 // Create a type on which we perform the shuffle
22467 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22468 StVT.getScalarType(), NumElems*SizeRatio);
22470 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22472 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22473 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22474 for (unsigned i = 0; i != NumElems; ++i)
22475 ShuffleVec[i] = i * SizeRatio;
22477 // Can't shuffle using an illegal type.
22478 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22479 && "WideVecVT should be legal");
22481 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22482 DAG.getUNDEF(WideVecVT),
22486 SDValue Mask = Mst->getMask();
22487 if (Mask.getValueType() == VT) {
22488 // Mask and original value have the same type
22489 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22490 for (unsigned i = 0; i != NumElems; ++i)
22491 ShuffleVec[i] = i * SizeRatio;
22492 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22493 ShuffleVec[i] = NumElems*SizeRatio;
22494 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22495 DAG.getConstant(0, WideVecVT),
22499 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22500 unsigned WidenNumElts = NumElems*SizeRatio;
22501 unsigned MaskNumElts = VT.getVectorNumElements();
22502 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22505 unsigned NumConcat = WidenNumElts / MaskNumElts;
22506 SmallVector<SDValue, 16> Ops(NumConcat);
22507 SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22509 for (unsigned i = 1; i != NumConcat; ++i)
22512 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22515 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22516 NewMask, StVT, Mst->getMemOperand(), false);
22518 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22519 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22520 const X86Subtarget *Subtarget) {
22521 StoreSDNode *St = cast<StoreSDNode>(N);
22522 EVT VT = St->getValue().getValueType();
22523 EVT StVT = St->getMemoryVT();
22525 SDValue StoredVal = St->getOperand(1);
22526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22528 // If we are saving a concatenation of two XMM registers and 32-byte stores
22529 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22530 unsigned Alignment = St->getAlignment();
22531 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22532 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22533 StVT == VT && !IsAligned) {
22534 unsigned NumElems = VT.getVectorNumElements();
22538 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22539 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22541 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22542 SDValue Ptr0 = St->getBasePtr();
22543 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22545 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22546 St->getPointerInfo(), St->isVolatile(),
22547 St->isNonTemporal(), Alignment);
22548 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22549 St->getPointerInfo(), St->isVolatile(),
22550 St->isNonTemporal(),
22551 std::min(16U, Alignment));
22552 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22555 // Optimize trunc store (of multiple scalars) to shuffle and store.
22556 // First, pack all of the elements in one place. Next, store to memory
22557 // in fewer chunks.
22558 if (St->isTruncatingStore() && VT.isVector()) {
22559 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22560 unsigned NumElems = VT.getVectorNumElements();
22561 assert(StVT != VT && "Cannot truncate to the same type");
22562 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22563 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22565 // From, To sizes and ElemCount must be pow of two
22566 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22567 // We are going to use the original vector elt for storing.
22568 // Accumulated smaller vector elements must be a multiple of the store size.
22569 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22571 unsigned SizeRatio = FromSz / ToSz;
22573 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22575 // Create a type on which we perform the shuffle
22576 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22577 StVT.getScalarType(), NumElems*SizeRatio);
22579 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22581 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22582 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22583 for (unsigned i = 0; i != NumElems; ++i)
22584 ShuffleVec[i] = i * SizeRatio;
22586 // Can't shuffle using an illegal type.
22587 if (!TLI.isTypeLegal(WideVecVT))
22590 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22591 DAG.getUNDEF(WideVecVT),
22593 // At this point all of the data is stored at the bottom of the
22594 // register. We now need to save it to mem.
22596 // Find the largest store unit
22597 MVT StoreType = MVT::i8;
22598 for (MVT Tp : MVT::integer_valuetypes()) {
22599 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22603 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22604 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22605 (64 <= NumElems * ToSz))
22606 StoreType = MVT::f64;
22608 // Bitcast the original vector into a vector of store-size units
22609 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22610 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22611 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22612 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22613 SmallVector<SDValue, 8> Chains;
22614 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22615 TLI.getPointerTy());
22616 SDValue Ptr = St->getBasePtr();
22618 // Perform one or more big stores into memory.
22619 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22620 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22621 StoreType, ShuffWide,
22622 DAG.getIntPtrConstant(i));
22623 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22624 St->getPointerInfo(), St->isVolatile(),
22625 St->isNonTemporal(), St->getAlignment());
22626 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22627 Chains.push_back(Ch);
22630 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22633 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22634 // the FP state in cases where an emms may be missing.
22635 // A preferable solution to the general problem is to figure out the right
22636 // places to insert EMMS. This qualifies as a quick hack.
22638 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22639 if (VT.getSizeInBits() != 64)
22642 const Function *F = DAG.getMachineFunction().getFunction();
22643 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22644 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22645 && Subtarget->hasSSE2();
22646 if ((VT.isVector() ||
22647 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22648 isa<LoadSDNode>(St->getValue()) &&
22649 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22650 St->getChain().hasOneUse() && !St->isVolatile()) {
22651 SDNode* LdVal = St->getValue().getNode();
22652 LoadSDNode *Ld = nullptr;
22653 int TokenFactorIndex = -1;
22654 SmallVector<SDValue, 8> Ops;
22655 SDNode* ChainVal = St->getChain().getNode();
22656 // Must be a store of a load. We currently handle two cases: the load
22657 // is a direct child, and it's under an intervening TokenFactor. It is
22658 // possible to dig deeper under nested TokenFactors.
22659 if (ChainVal == LdVal)
22660 Ld = cast<LoadSDNode>(St->getChain());
22661 else if (St->getValue().hasOneUse() &&
22662 ChainVal->getOpcode() == ISD::TokenFactor) {
22663 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22664 if (ChainVal->getOperand(i).getNode() == LdVal) {
22665 TokenFactorIndex = i;
22666 Ld = cast<LoadSDNode>(St->getValue());
22668 Ops.push_back(ChainVal->getOperand(i));
22672 if (!Ld || !ISD::isNormalLoad(Ld))
22675 // If this is not the MMX case, i.e. we are just turning i64 load/store
22676 // into f64 load/store, avoid the transformation if there are multiple
22677 // uses of the loaded value.
22678 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22683 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22684 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22686 if (Subtarget->is64Bit() || F64IsLegal) {
22687 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22688 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22689 Ld->getPointerInfo(), Ld->isVolatile(),
22690 Ld->isNonTemporal(), Ld->isInvariant(),
22691 Ld->getAlignment());
22692 SDValue NewChain = NewLd.getValue(1);
22693 if (TokenFactorIndex != -1) {
22694 Ops.push_back(NewChain);
22695 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22697 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22698 St->getPointerInfo(),
22699 St->isVolatile(), St->isNonTemporal(),
22700 St->getAlignment());
22703 // Otherwise, lower to two pairs of 32-bit loads / stores.
22704 SDValue LoAddr = Ld->getBasePtr();
22705 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22706 DAG.getConstant(4, MVT::i32));
22708 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22709 Ld->getPointerInfo(),
22710 Ld->isVolatile(), Ld->isNonTemporal(),
22711 Ld->isInvariant(), Ld->getAlignment());
22712 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22713 Ld->getPointerInfo().getWithOffset(4),
22714 Ld->isVolatile(), Ld->isNonTemporal(),
22716 MinAlign(Ld->getAlignment(), 4));
22718 SDValue NewChain = LoLd.getValue(1);
22719 if (TokenFactorIndex != -1) {
22720 Ops.push_back(LoLd);
22721 Ops.push_back(HiLd);
22722 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22725 LoAddr = St->getBasePtr();
22726 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22727 DAG.getConstant(4, MVT::i32));
22729 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22730 St->getPointerInfo(),
22731 St->isVolatile(), St->isNonTemporal(),
22732 St->getAlignment());
22733 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22734 St->getPointerInfo().getWithOffset(4),
22736 St->isNonTemporal(),
22737 MinAlign(St->getAlignment(), 4));
22738 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22743 /// Return 'true' if this vector operation is "horizontal"
22744 /// and return the operands for the horizontal operation in LHS and RHS. A
22745 /// horizontal operation performs the binary operation on successive elements
22746 /// of its first operand, then on successive elements of its second operand,
22747 /// returning the resulting values in a vector. For example, if
22748 /// A = < float a0, float a1, float a2, float a3 >
22750 /// B = < float b0, float b1, float b2, float b3 >
22751 /// then the result of doing a horizontal operation on A and B is
22752 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22753 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22754 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22755 /// set to A, RHS to B, and the routine returns 'true'.
22756 /// Note that the binary operation should have the property that if one of the
22757 /// operands is UNDEF then the result is UNDEF.
22758 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22759 // Look for the following pattern: if
22760 // A = < float a0, float a1, float a2, float a3 >
22761 // B = < float b0, float b1, float b2, float b3 >
22763 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22764 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22765 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22766 // which is A horizontal-op B.
22768 // At least one of the operands should be a vector shuffle.
22769 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22770 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22773 MVT VT = LHS.getSimpleValueType();
22775 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22776 "Unsupported vector type for horizontal add/sub");
22778 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22779 // operate independently on 128-bit lanes.
22780 unsigned NumElts = VT.getVectorNumElements();
22781 unsigned NumLanes = VT.getSizeInBits()/128;
22782 unsigned NumLaneElts = NumElts / NumLanes;
22783 assert((NumLaneElts % 2 == 0) &&
22784 "Vector type should have an even number of elements in each lane");
22785 unsigned HalfLaneElts = NumLaneElts/2;
22787 // View LHS in the form
22788 // LHS = VECTOR_SHUFFLE A, B, LMask
22789 // If LHS is not a shuffle then pretend it is the shuffle
22790 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22791 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22794 SmallVector<int, 16> LMask(NumElts);
22795 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22796 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22797 A = LHS.getOperand(0);
22798 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22799 B = LHS.getOperand(1);
22800 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22801 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22803 if (LHS.getOpcode() != ISD::UNDEF)
22805 for (unsigned i = 0; i != NumElts; ++i)
22809 // Likewise, view RHS in the form
22810 // RHS = VECTOR_SHUFFLE C, D, RMask
22812 SmallVector<int, 16> RMask(NumElts);
22813 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22814 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22815 C = RHS.getOperand(0);
22816 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22817 D = RHS.getOperand(1);
22818 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22819 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22821 if (RHS.getOpcode() != ISD::UNDEF)
22823 for (unsigned i = 0; i != NumElts; ++i)
22827 // Check that the shuffles are both shuffling the same vectors.
22828 if (!(A == C && B == D) && !(A == D && B == C))
22831 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22832 if (!A.getNode() && !B.getNode())
22835 // If A and B occur in reverse order in RHS, then "swap" them (which means
22836 // rewriting the mask).
22838 ShuffleVectorSDNode::commuteMask(RMask);
22840 // At this point LHS and RHS are equivalent to
22841 // LHS = VECTOR_SHUFFLE A, B, LMask
22842 // RHS = VECTOR_SHUFFLE A, B, RMask
22843 // Check that the masks correspond to performing a horizontal operation.
22844 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22845 for (unsigned i = 0; i != NumLaneElts; ++i) {
22846 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22848 // Ignore any UNDEF components.
22849 if (LIdx < 0 || RIdx < 0 ||
22850 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22851 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22854 // Check that successive elements are being operated on. If not, this is
22855 // not a horizontal operation.
22856 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22857 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22858 if (!(LIdx == Index && RIdx == Index + 1) &&
22859 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22864 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22865 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22869 /// Do target-specific dag combines on floating point adds.
22870 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22871 const X86Subtarget *Subtarget) {
22872 EVT VT = N->getValueType(0);
22873 SDValue LHS = N->getOperand(0);
22874 SDValue RHS = N->getOperand(1);
22876 // Try to synthesize horizontal adds from adds of shuffles.
22877 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22878 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22879 isHorizontalBinOp(LHS, RHS, true))
22880 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22884 /// Do target-specific dag combines on floating point subs.
22885 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22886 const X86Subtarget *Subtarget) {
22887 EVT VT = N->getValueType(0);
22888 SDValue LHS = N->getOperand(0);
22889 SDValue RHS = N->getOperand(1);
22891 // Try to synthesize horizontal subs from subs of shuffles.
22892 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22893 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22894 isHorizontalBinOp(LHS, RHS, false))
22895 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22899 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
22900 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22901 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22903 // F[X]OR(0.0, x) -> x
22904 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22905 if (C->getValueAPF().isPosZero())
22906 return N->getOperand(1);
22908 // F[X]OR(x, 0.0) -> x
22909 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22910 if (C->getValueAPF().isPosZero())
22911 return N->getOperand(0);
22915 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
22916 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22917 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22919 // Only perform optimizations if UnsafeMath is used.
22920 if (!DAG.getTarget().Options.UnsafeFPMath)
22923 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22924 // into FMINC and FMAXC, which are Commutative operations.
22925 unsigned NewOp = 0;
22926 switch (N->getOpcode()) {
22927 default: llvm_unreachable("unknown opcode");
22928 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22929 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22932 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22933 N->getOperand(0), N->getOperand(1));
22936 /// Do target-specific dag combines on X86ISD::FAND nodes.
22937 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22938 // FAND(0.0, x) -> 0.0
22939 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22940 if (C->getValueAPF().isPosZero())
22941 return N->getOperand(0);
22943 // FAND(x, 0.0) -> 0.0
22944 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22945 if (C->getValueAPF().isPosZero())
22946 return N->getOperand(1);
22951 /// Do target-specific dag combines on X86ISD::FANDN nodes
22952 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22953 // FANDN(0.0, x) -> x
22954 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22955 if (C->getValueAPF().isPosZero())
22956 return N->getOperand(1);
22958 // FANDN(x, 0.0) -> 0.0
22959 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22960 if (C->getValueAPF().isPosZero())
22961 return N->getOperand(1);
22966 static SDValue PerformBTCombine(SDNode *N,
22968 TargetLowering::DAGCombinerInfo &DCI) {
22969 // BT ignores high bits in the bit index operand.
22970 SDValue Op1 = N->getOperand(1);
22971 if (Op1.hasOneUse()) {
22972 unsigned BitWidth = Op1.getValueSizeInBits();
22973 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22974 APInt KnownZero, KnownOne;
22975 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22976 !DCI.isBeforeLegalizeOps());
22977 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22978 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22979 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22980 DCI.CommitTargetLoweringOpt(TLO);
22985 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22986 SDValue Op = N->getOperand(0);
22987 if (Op.getOpcode() == ISD::BITCAST)
22988 Op = Op.getOperand(0);
22989 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22990 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22991 VT.getVectorElementType().getSizeInBits() ==
22992 OpVT.getVectorElementType().getSizeInBits()) {
22993 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22998 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22999 const X86Subtarget *Subtarget) {
23000 EVT VT = N->getValueType(0);
23001 if (!VT.isVector())
23004 SDValue N0 = N->getOperand(0);
23005 SDValue N1 = N->getOperand(1);
23006 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23009 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23010 // both SSE and AVX2 since there is no sign-extended shift right
23011 // operation on a vector with 64-bit elements.
23012 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23013 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23014 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23015 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23016 SDValue N00 = N0.getOperand(0);
23018 // EXTLOAD has a better solution on AVX2,
23019 // it may be replaced with X86ISD::VSEXT node.
23020 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23021 if (!ISD::isNormalLoad(N00.getNode()))
23024 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23025 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23027 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23033 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23034 TargetLowering::DAGCombinerInfo &DCI,
23035 const X86Subtarget *Subtarget) {
23036 SDValue N0 = N->getOperand(0);
23037 EVT VT = N->getValueType(0);
23039 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23040 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23041 // This exposes the sext to the sdivrem lowering, so that it directly extends
23042 // from AH (which we otherwise need to do contortions to access).
23043 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23044 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23046 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23047 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23048 N0.getOperand(0), N0.getOperand(1));
23049 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23050 return R.getValue(1);
23053 if (!DCI.isBeforeLegalizeOps())
23056 if (!Subtarget->hasFp256())
23059 if (VT.isVector() && VT.getSizeInBits() == 256) {
23060 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23068 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23069 const X86Subtarget* Subtarget) {
23071 EVT VT = N->getValueType(0);
23073 // Let legalize expand this if it isn't a legal type yet.
23074 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23077 EVT ScalarVT = VT.getScalarType();
23078 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23079 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23082 SDValue A = N->getOperand(0);
23083 SDValue B = N->getOperand(1);
23084 SDValue C = N->getOperand(2);
23086 bool NegA = (A.getOpcode() == ISD::FNEG);
23087 bool NegB = (B.getOpcode() == ISD::FNEG);
23088 bool NegC = (C.getOpcode() == ISD::FNEG);
23090 // Negative multiplication when NegA xor NegB
23091 bool NegMul = (NegA != NegB);
23093 A = A.getOperand(0);
23095 B = B.getOperand(0);
23097 C = C.getOperand(0);
23101 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23103 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23105 return DAG.getNode(Opcode, dl, VT, A, B, C);
23108 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23109 TargetLowering::DAGCombinerInfo &DCI,
23110 const X86Subtarget *Subtarget) {
23111 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23112 // (and (i32 x86isd::setcc_carry), 1)
23113 // This eliminates the zext. This transformation is necessary because
23114 // ISD::SETCC is always legalized to i8.
23116 SDValue N0 = N->getOperand(0);
23117 EVT VT = N->getValueType(0);
23119 if (N0.getOpcode() == ISD::AND &&
23121 N0.getOperand(0).hasOneUse()) {
23122 SDValue N00 = N0.getOperand(0);
23123 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23124 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23125 if (!C || C->getZExtValue() != 1)
23127 return DAG.getNode(ISD::AND, dl, VT,
23128 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23129 N00.getOperand(0), N00.getOperand(1)),
23130 DAG.getConstant(1, VT));
23134 if (N0.getOpcode() == ISD::TRUNCATE &&
23136 N0.getOperand(0).hasOneUse()) {
23137 SDValue N00 = N0.getOperand(0);
23138 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23139 return DAG.getNode(ISD::AND, dl, VT,
23140 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23141 N00.getOperand(0), N00.getOperand(1)),
23142 DAG.getConstant(1, VT));
23145 if (VT.is256BitVector()) {
23146 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23151 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23152 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23153 // This exposes the zext to the udivrem lowering, so that it directly extends
23154 // from AH (which we otherwise need to do contortions to access).
23155 if (N0.getOpcode() == ISD::UDIVREM &&
23156 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23157 (VT == MVT::i32 || VT == MVT::i64)) {
23158 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23159 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23160 N0.getOperand(0), N0.getOperand(1));
23161 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23162 return R.getValue(1);
23168 // Optimize x == -y --> x+y == 0
23169 // x != -y --> x+y != 0
23170 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23171 const X86Subtarget* Subtarget) {
23172 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23173 SDValue LHS = N->getOperand(0);
23174 SDValue RHS = N->getOperand(1);
23175 EVT VT = N->getValueType(0);
23178 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23180 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23181 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23182 LHS.getValueType(), RHS, LHS.getOperand(1));
23183 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23184 addV, DAG.getConstant(0, addV.getValueType()), CC);
23186 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23187 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23188 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23189 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23190 RHS.getValueType(), LHS, RHS.getOperand(1));
23191 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23192 addV, DAG.getConstant(0, addV.getValueType()), CC);
23195 if (VT.getScalarType() == MVT::i1) {
23196 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23197 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23198 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
23199 if (!IsSEXT0 && !IsVZero0)
23201 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
23202 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23203 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23205 if (!IsSEXT1 && !IsVZero1)
23208 if (IsSEXT0 && IsVZero1) {
23209 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
23210 if (CC == ISD::SETEQ)
23211 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23212 return LHS.getOperand(0);
23214 if (IsSEXT1 && IsVZero0) {
23215 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
23216 if (CC == ISD::SETEQ)
23217 return DAG.getNOT(DL, RHS.getOperand(0), VT);
23218 return RHS.getOperand(0);
23225 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23226 SelectionDAG &DAG) {
23228 MVT VT = Load->getSimpleValueType(0);
23229 MVT EVT = VT.getVectorElementType();
23230 SDValue Addr = Load->getOperand(1);
23231 SDValue NewAddr = DAG.getNode(
23232 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23233 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23236 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23237 DAG.getMachineFunction().getMachineMemOperand(
23238 Load->getMemOperand(), 0, EVT.getStoreSize()));
23242 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23243 const X86Subtarget *Subtarget) {
23245 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23246 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23247 "X86insertps is only defined for v4x32");
23249 SDValue Ld = N->getOperand(1);
23250 if (MayFoldLoad(Ld)) {
23251 // Extract the countS bits from the immediate so we can get the proper
23252 // address when narrowing the vector load to a specific element.
23253 // When the second source op is a memory address, insertps doesn't use
23254 // countS and just gets an f32 from that address.
23255 unsigned DestIndex =
23256 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23258 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23260 // Create this as a scalar to vector to match the instruction pattern.
23261 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23262 // countS bits are ignored when loading from memory on insertps, which
23263 // means we don't need to explicitly set them to 0.
23264 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23265 LoadScalarToVector, N->getOperand(2));
23270 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23271 SDValue V0 = N->getOperand(0);
23272 SDValue V1 = N->getOperand(1);
23274 EVT VT = N->getValueType(0);
23276 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23277 // operands and changing the mask to 1. This saves us a bunch of
23278 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23279 // x86InstrInfo knows how to commute this back after instruction selection
23280 // if it would help register allocation.
23282 // TODO: If optimizing for size or a processor that doesn't suffer from
23283 // partial register update stalls, this should be transformed into a MOVSD
23284 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23286 if (VT == MVT::v2f64)
23287 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23288 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23289 SDValue NewMask = DAG.getConstant(1, MVT::i8);
23290 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23296 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23297 // as "sbb reg,reg", since it can be extended without zext and produces
23298 // an all-ones bit which is more useful than 0/1 in some cases.
23299 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23302 return DAG.getNode(ISD::AND, DL, VT,
23303 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23304 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23305 DAG.getConstant(1, VT));
23306 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23307 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23308 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23309 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23312 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23313 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23314 TargetLowering::DAGCombinerInfo &DCI,
23315 const X86Subtarget *Subtarget) {
23317 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23318 SDValue EFLAGS = N->getOperand(1);
23320 if (CC == X86::COND_A) {
23321 // Try to convert COND_A into COND_B in an attempt to facilitate
23322 // materializing "setb reg".
23324 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23325 // cannot take an immediate as its first operand.
23327 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23328 EFLAGS.getValueType().isInteger() &&
23329 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23330 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23331 EFLAGS.getNode()->getVTList(),
23332 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23333 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23334 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23338 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23339 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23341 if (CC == X86::COND_B)
23342 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23346 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23347 if (Flags.getNode()) {
23348 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23349 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23355 // Optimize branch condition evaluation.
23357 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23358 TargetLowering::DAGCombinerInfo &DCI,
23359 const X86Subtarget *Subtarget) {
23361 SDValue Chain = N->getOperand(0);
23362 SDValue Dest = N->getOperand(1);
23363 SDValue EFLAGS = N->getOperand(3);
23364 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23368 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23369 if (Flags.getNode()) {
23370 SDValue Cond = DAG.getConstant(CC, MVT::i8);
23371 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23378 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23379 SelectionDAG &DAG) {
23380 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23381 // optimize away operation when it's from a constant.
23383 // The general transformation is:
23384 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23385 // AND(VECTOR_CMP(x,y), constant2)
23386 // constant2 = UNARYOP(constant)
23388 // Early exit if this isn't a vector operation, the operand of the
23389 // unary operation isn't a bitwise AND, or if the sizes of the operations
23390 // aren't the same.
23391 EVT VT = N->getValueType(0);
23392 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23393 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23394 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23397 // Now check that the other operand of the AND is a constant. We could
23398 // make the transformation for non-constant splats as well, but it's unclear
23399 // that would be a benefit as it would not eliminate any operations, just
23400 // perform one more step in scalar code before moving to the vector unit.
23401 if (BuildVectorSDNode *BV =
23402 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23403 // Bail out if the vector isn't a constant.
23404 if (!BV->isConstant())
23407 // Everything checks out. Build up the new and improved node.
23409 EVT IntVT = BV->getValueType(0);
23410 // Create a new constant of the appropriate type for the transformed
23412 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23413 // The AND node needs bitcasts to/from an integer vector type around it.
23414 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23415 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23416 N->getOperand(0)->getOperand(0), MaskConst);
23417 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23424 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23425 const X86Subtarget *Subtarget) {
23426 // First try to optimize away the conversion entirely when it's
23427 // conditionally from a constant. Vectors only.
23428 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23429 if (Res != SDValue())
23432 // Now move on to more general possibilities.
23433 SDValue Op0 = N->getOperand(0);
23434 EVT InVT = Op0->getValueType(0);
23436 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23437 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23439 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23440 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23441 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23444 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23445 // a 32-bit target where SSE doesn't support i64->FP operations.
23446 if (Op0.getOpcode() == ISD::LOAD) {
23447 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23448 EVT VT = Ld->getValueType(0);
23449 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23450 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23451 !Subtarget->is64Bit() && VT == MVT::i64) {
23452 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23453 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23454 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23461 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23462 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23463 X86TargetLowering::DAGCombinerInfo &DCI) {
23464 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23465 // the result is either zero or one (depending on the input carry bit).
23466 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23467 if (X86::isZeroNode(N->getOperand(0)) &&
23468 X86::isZeroNode(N->getOperand(1)) &&
23469 // We don't have a good way to replace an EFLAGS use, so only do this when
23471 SDValue(N, 1).use_empty()) {
23473 EVT VT = N->getValueType(0);
23474 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23475 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23476 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23477 DAG.getConstant(X86::COND_B,MVT::i8),
23479 DAG.getConstant(1, VT));
23480 return DCI.CombineTo(N, Res1, CarryOut);
23486 // fold (add Y, (sete X, 0)) -> adc 0, Y
23487 // (add Y, (setne X, 0)) -> sbb -1, Y
23488 // (sub (sete X, 0), Y) -> sbb 0, Y
23489 // (sub (setne X, 0), Y) -> adc -1, Y
23490 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23493 // Look through ZExts.
23494 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23495 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23498 SDValue SetCC = Ext.getOperand(0);
23499 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23502 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23503 if (CC != X86::COND_E && CC != X86::COND_NE)
23506 SDValue Cmp = SetCC.getOperand(1);
23507 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23508 !X86::isZeroNode(Cmp.getOperand(1)) ||
23509 !Cmp.getOperand(0).getValueType().isInteger())
23512 SDValue CmpOp0 = Cmp.getOperand(0);
23513 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23514 DAG.getConstant(1, CmpOp0.getValueType()));
23516 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23517 if (CC == X86::COND_NE)
23518 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23519 DL, OtherVal.getValueType(), OtherVal,
23520 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23521 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23522 DL, OtherVal.getValueType(), OtherVal,
23523 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23526 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23527 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23528 const X86Subtarget *Subtarget) {
23529 EVT VT = N->getValueType(0);
23530 SDValue Op0 = N->getOperand(0);
23531 SDValue Op1 = N->getOperand(1);
23533 // Try to synthesize horizontal adds from adds of shuffles.
23534 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23535 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23536 isHorizontalBinOp(Op0, Op1, true))
23537 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23539 return OptimizeConditionalInDecrement(N, DAG);
23542 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23543 const X86Subtarget *Subtarget) {
23544 SDValue Op0 = N->getOperand(0);
23545 SDValue Op1 = N->getOperand(1);
23547 // X86 can't encode an immediate LHS of a sub. See if we can push the
23548 // negation into a preceding instruction.
23549 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23550 // If the RHS of the sub is a XOR with one use and a constant, invert the
23551 // immediate. Then add one to the LHS of the sub so we can turn
23552 // X-Y -> X+~Y+1, saving one register.
23553 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23554 isa<ConstantSDNode>(Op1.getOperand(1))) {
23555 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23556 EVT VT = Op0.getValueType();
23557 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23559 DAG.getConstant(~XorC, VT));
23560 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23561 DAG.getConstant(C->getAPIntValue()+1, VT));
23565 // Try to synthesize horizontal adds from adds of shuffles.
23566 EVT VT = N->getValueType(0);
23567 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23568 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23569 isHorizontalBinOp(Op0, Op1, true))
23570 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23572 return OptimizeConditionalInDecrement(N, DAG);
23575 /// performVZEXTCombine - Performs build vector combines
23576 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23577 TargetLowering::DAGCombinerInfo &DCI,
23578 const X86Subtarget *Subtarget) {
23580 MVT VT = N->getSimpleValueType(0);
23581 SDValue Op = N->getOperand(0);
23582 MVT OpVT = Op.getSimpleValueType();
23583 MVT OpEltVT = OpVT.getVectorElementType();
23584 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23586 // (vzext (bitcast (vzext (x)) -> (vzext x)
23588 while (V.getOpcode() == ISD::BITCAST)
23589 V = V.getOperand(0);
23591 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23592 MVT InnerVT = V.getSimpleValueType();
23593 MVT InnerEltVT = InnerVT.getVectorElementType();
23595 // If the element sizes match exactly, we can just do one larger vzext. This
23596 // is always an exact type match as vzext operates on integer types.
23597 if (OpEltVT == InnerEltVT) {
23598 assert(OpVT == InnerVT && "Types must match for vzext!");
23599 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23602 // The only other way we can combine them is if only a single element of the
23603 // inner vzext is used in the input to the outer vzext.
23604 if (InnerEltVT.getSizeInBits() < InputBits)
23607 // In this case, the inner vzext is completely dead because we're going to
23608 // only look at bits inside of the low element. Just do the outer vzext on
23609 // a bitcast of the input to the inner.
23610 return DAG.getNode(X86ISD::VZEXT, DL, VT,
23611 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23614 // Check if we can bypass extracting and re-inserting an element of an input
23615 // vector. Essentialy:
23616 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23617 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
23618 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
23619 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
23620 SDValue ExtractedV = V.getOperand(0);
23621 SDValue OrigV = ExtractedV.getOperand(0);
23622 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
23623 if (ExtractIdx->getZExtValue() == 0) {
23624 MVT OrigVT = OrigV.getSimpleValueType();
23625 // Extract a subvector if necessary...
23626 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
23627 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
23628 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
23629 OrigVT.getVectorNumElements() / Ratio);
23630 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
23631 DAG.getIntPtrConstant(0));
23633 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
23634 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
23641 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23642 DAGCombinerInfo &DCI) const {
23643 SelectionDAG &DAG = DCI.DAG;
23644 switch (N->getOpcode()) {
23646 case ISD::EXTRACT_VECTOR_ELT:
23647 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23650 case X86ISD::SHRUNKBLEND:
23651 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23652 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
23653 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23654 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23655 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23656 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23657 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23660 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23661 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23662 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23663 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23664 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23665 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
23666 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23667 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
23668 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
23669 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23670 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23672 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23674 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23675 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23676 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23677 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23678 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23679 case ISD::ANY_EXTEND:
23680 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23681 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23682 case ISD::SIGN_EXTEND_INREG:
23683 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23684 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23685 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23686 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23687 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23688 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23689 case X86ISD::SHUFP: // Handle all target specific shuffles
23690 case X86ISD::PALIGNR:
23691 case X86ISD::UNPCKH:
23692 case X86ISD::UNPCKL:
23693 case X86ISD::MOVHLPS:
23694 case X86ISD::MOVLHPS:
23695 case X86ISD::PSHUFB:
23696 case X86ISD::PSHUFD:
23697 case X86ISD::PSHUFHW:
23698 case X86ISD::PSHUFLW:
23699 case X86ISD::MOVSS:
23700 case X86ISD::MOVSD:
23701 case X86ISD::VPERMILPI:
23702 case X86ISD::VPERM2X128:
23703 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23704 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23705 case ISD::INTRINSIC_WO_CHAIN:
23706 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23707 case X86ISD::INSERTPS: {
23708 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
23709 return PerformINSERTPSCombine(N, DAG, Subtarget);
23712 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
23713 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23719 /// isTypeDesirableForOp - Return true if the target has native support for
23720 /// the specified value type and it is 'desirable' to use the type for the
23721 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23722 /// instruction encodings are longer and some i16 instructions are slow.
23723 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23724 if (!isTypeLegal(VT))
23726 if (VT != MVT::i16)
23733 case ISD::SIGN_EXTEND:
23734 case ISD::ZERO_EXTEND:
23735 case ISD::ANY_EXTEND:
23748 /// IsDesirableToPromoteOp - This method query the target whether it is
23749 /// beneficial for dag combiner to promote the specified node. If true, it
23750 /// should return the desired promotion type by reference.
23751 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23752 EVT VT = Op.getValueType();
23753 if (VT != MVT::i16)
23756 bool Promote = false;
23757 bool Commute = false;
23758 switch (Op.getOpcode()) {
23761 LoadSDNode *LD = cast<LoadSDNode>(Op);
23762 // If the non-extending load has a single use and it's not live out, then it
23763 // might be folded.
23764 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23765 Op.hasOneUse()*/) {
23766 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23767 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23768 // The only case where we'd want to promote LOAD (rather then it being
23769 // promoted as an operand is when it's only use is liveout.
23770 if (UI->getOpcode() != ISD::CopyToReg)
23777 case ISD::SIGN_EXTEND:
23778 case ISD::ZERO_EXTEND:
23779 case ISD::ANY_EXTEND:
23784 SDValue N0 = Op.getOperand(0);
23785 // Look out for (store (shl (load), x)).
23786 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23799 SDValue N0 = Op.getOperand(0);
23800 SDValue N1 = Op.getOperand(1);
23801 if (!Commute && MayFoldLoad(N1))
23803 // Avoid disabling potential load folding opportunities.
23804 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23806 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23816 //===----------------------------------------------------------------------===//
23817 // X86 Inline Assembly Support
23818 //===----------------------------------------------------------------------===//
23820 // Helper to match a string separated by whitespace.
23821 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
23822 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
23824 for (StringRef Piece : Pieces) {
23825 if (!S.startswith(Piece)) // Check if the piece matches.
23828 S = S.substr(Piece.size());
23829 StringRef::size_type Pos = S.find_first_not_of(" \t");
23830 if (Pos == 0) // We matched a prefix.
23839 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23841 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23842 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23843 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23844 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23846 if (AsmPieces.size() == 3)
23848 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23855 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23856 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23858 std::string AsmStr = IA->getAsmString();
23860 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23861 if (!Ty || Ty->getBitWidth() % 16 != 0)
23864 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23865 SmallVector<StringRef, 4> AsmPieces;
23866 SplitString(AsmStr, AsmPieces, ";\n");
23868 switch (AsmPieces.size()) {
23869 default: return false;
23871 // FIXME: this should verify that we are targeting a 486 or better. If not,
23872 // we will turn this bswap into something that will be lowered to logical
23873 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23874 // lower so don't worry about this.
23876 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
23877 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
23878 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
23879 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
23880 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
23881 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
23882 // No need to check constraints, nothing other than the equivalent of
23883 // "=r,0" would be valid here.
23884 return IntrinsicLowering::LowerToByteSwap(CI);
23887 // rorw $$8, ${0:w} --> llvm.bswap.i16
23888 if (CI->getType()->isIntegerTy(16) &&
23889 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23890 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
23891 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
23893 const std::string &ConstraintsStr = IA->getConstraintString();
23894 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23895 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23896 if (clobbersFlagRegisters(AsmPieces))
23897 return IntrinsicLowering::LowerToByteSwap(CI);
23901 if (CI->getType()->isIntegerTy(32) &&
23902 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23903 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
23904 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
23905 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
23907 const std::string &ConstraintsStr = IA->getConstraintString();
23908 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23909 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23910 if (clobbersFlagRegisters(AsmPieces))
23911 return IntrinsicLowering::LowerToByteSwap(CI);
23914 if (CI->getType()->isIntegerTy(64)) {
23915 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23916 if (Constraints.size() >= 2 &&
23917 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23918 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23919 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23920 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
23921 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
23922 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
23923 return IntrinsicLowering::LowerToByteSwap(CI);
23931 /// getConstraintType - Given a constraint letter, return the type of
23932 /// constraint it is for this target.
23933 X86TargetLowering::ConstraintType
23934 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23935 if (Constraint.size() == 1) {
23936 switch (Constraint[0]) {
23947 return C_RegisterClass;
23971 return TargetLowering::getConstraintType(Constraint);
23974 /// Examine constraint type and operand type and determine a weight value.
23975 /// This object must already have been set up with the operand type
23976 /// and the current alternative constraint selected.
23977 TargetLowering::ConstraintWeight
23978 X86TargetLowering::getSingleConstraintMatchWeight(
23979 AsmOperandInfo &info, const char *constraint) const {
23980 ConstraintWeight weight = CW_Invalid;
23981 Value *CallOperandVal = info.CallOperandVal;
23982 // If we don't have a value, we can't do a match,
23983 // but allow it at the lowest weight.
23984 if (!CallOperandVal)
23986 Type *type = CallOperandVal->getType();
23987 // Look at the constraint type.
23988 switch (*constraint) {
23990 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24001 if (CallOperandVal->getType()->isIntegerTy())
24002 weight = CW_SpecificReg;
24007 if (type->isFloatingPointTy())
24008 weight = CW_SpecificReg;
24011 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24012 weight = CW_SpecificReg;
24016 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24017 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24018 weight = CW_Register;
24021 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24022 if (C->getZExtValue() <= 31)
24023 weight = CW_Constant;
24027 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24028 if (C->getZExtValue() <= 63)
24029 weight = CW_Constant;
24033 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24034 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24035 weight = CW_Constant;
24039 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24040 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24041 weight = CW_Constant;
24045 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24046 if (C->getZExtValue() <= 3)
24047 weight = CW_Constant;
24051 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24052 if (C->getZExtValue() <= 0xff)
24053 weight = CW_Constant;
24058 if (dyn_cast<ConstantFP>(CallOperandVal)) {
24059 weight = CW_Constant;
24063 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24064 if ((C->getSExtValue() >= -0x80000000LL) &&
24065 (C->getSExtValue() <= 0x7fffffffLL))
24066 weight = CW_Constant;
24070 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24071 if (C->getZExtValue() <= 0xffffffff)
24072 weight = CW_Constant;
24079 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24080 /// with another that has more specific requirements based on the type of the
24081 /// corresponding operand.
24082 const char *X86TargetLowering::
24083 LowerXConstraint(EVT ConstraintVT) const {
24084 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24085 // 'f' like normal targets.
24086 if (ConstraintVT.isFloatingPoint()) {
24087 if (Subtarget->hasSSE2())
24089 if (Subtarget->hasSSE1())
24093 return TargetLowering::LowerXConstraint(ConstraintVT);
24096 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24097 /// vector. If it is invalid, don't add anything to Ops.
24098 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24099 std::string &Constraint,
24100 std::vector<SDValue>&Ops,
24101 SelectionDAG &DAG) const {
24104 // Only support length 1 constraints for now.
24105 if (Constraint.length() > 1) return;
24107 char ConstraintLetter = Constraint[0];
24108 switch (ConstraintLetter) {
24111 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24112 if (C->getZExtValue() <= 31) {
24113 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24120 if (C->getZExtValue() <= 63) {
24121 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24127 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24128 if (isInt<8>(C->getSExtValue())) {
24129 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24135 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24136 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24137 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24138 Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24144 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24145 if (C->getZExtValue() <= 3) {
24146 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24153 if (C->getZExtValue() <= 255) {
24154 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24160 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24161 if (C->getZExtValue() <= 127) {
24162 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24168 // 32-bit signed value
24169 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24170 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24171 C->getSExtValue())) {
24172 // Widen to 64 bits here to get it sign extended.
24173 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24176 // FIXME gcc accepts some relocatable values here too, but only in certain
24177 // memory models; it's complicated.
24182 // 32-bit unsigned value
24183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24184 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24185 C->getZExtValue())) {
24186 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24190 // FIXME gcc accepts some relocatable values here too, but only in certain
24191 // memory models; it's complicated.
24195 // Literal immediates are always ok.
24196 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24197 // Widen to 64 bits here to get it sign extended.
24198 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24202 // In any sort of PIC mode addresses need to be computed at runtime by
24203 // adding in a register or some sort of table lookup. These can't
24204 // be used as immediates.
24205 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24208 // If we are in non-pic codegen mode, we allow the address of a global (with
24209 // an optional displacement) to be used with 'i'.
24210 GlobalAddressSDNode *GA = nullptr;
24211 int64_t Offset = 0;
24213 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24215 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24216 Offset += GA->getOffset();
24218 } else if (Op.getOpcode() == ISD::ADD) {
24219 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24220 Offset += C->getZExtValue();
24221 Op = Op.getOperand(0);
24224 } else if (Op.getOpcode() == ISD::SUB) {
24225 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24226 Offset += -C->getZExtValue();
24227 Op = Op.getOperand(0);
24232 // Otherwise, this isn't something we can handle, reject it.
24236 const GlobalValue *GV = GA->getGlobal();
24237 // If we require an extra load to get this address, as in PIC mode, we
24238 // can't accept it.
24239 if (isGlobalStubReference(
24240 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24243 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24244 GA->getValueType(0), Offset);
24249 if (Result.getNode()) {
24250 Ops.push_back(Result);
24253 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24256 std::pair<unsigned, const TargetRegisterClass *>
24257 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24258 const std::string &Constraint,
24260 // First, see if this is a constraint that directly corresponds to an LLVM
24262 if (Constraint.size() == 1) {
24263 // GCC Constraint Letters
24264 switch (Constraint[0]) {
24266 // TODO: Slight differences here in allocation order and leaving
24267 // RIP in the class. Do they matter any more here than they do
24268 // in the normal allocation?
24269 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24270 if (Subtarget->is64Bit()) {
24271 if (VT == MVT::i32 || VT == MVT::f32)
24272 return std::make_pair(0U, &X86::GR32RegClass);
24273 if (VT == MVT::i16)
24274 return std::make_pair(0U, &X86::GR16RegClass);
24275 if (VT == MVT::i8 || VT == MVT::i1)
24276 return std::make_pair(0U, &X86::GR8RegClass);
24277 if (VT == MVT::i64 || VT == MVT::f64)
24278 return std::make_pair(0U, &X86::GR64RegClass);
24281 // 32-bit fallthrough
24282 case 'Q': // Q_REGS
24283 if (VT == MVT::i32 || VT == MVT::f32)
24284 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24285 if (VT == MVT::i16)
24286 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24287 if (VT == MVT::i8 || VT == MVT::i1)
24288 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24289 if (VT == MVT::i64)
24290 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24292 case 'r': // GENERAL_REGS
24293 case 'l': // INDEX_REGS
24294 if (VT == MVT::i8 || VT == MVT::i1)
24295 return std::make_pair(0U, &X86::GR8RegClass);
24296 if (VT == MVT::i16)
24297 return std::make_pair(0U, &X86::GR16RegClass);
24298 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24299 return std::make_pair(0U, &X86::GR32RegClass);
24300 return std::make_pair(0U, &X86::GR64RegClass);
24301 case 'R': // LEGACY_REGS
24302 if (VT == MVT::i8 || VT == MVT::i1)
24303 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24304 if (VT == MVT::i16)
24305 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24306 if (VT == MVT::i32 || !Subtarget->is64Bit())
24307 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24308 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24309 case 'f': // FP Stack registers.
24310 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24311 // value to the correct fpstack register class.
24312 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24313 return std::make_pair(0U, &X86::RFP32RegClass);
24314 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24315 return std::make_pair(0U, &X86::RFP64RegClass);
24316 return std::make_pair(0U, &X86::RFP80RegClass);
24317 case 'y': // MMX_REGS if MMX allowed.
24318 if (!Subtarget->hasMMX()) break;
24319 return std::make_pair(0U, &X86::VR64RegClass);
24320 case 'Y': // SSE_REGS if SSE2 allowed
24321 if (!Subtarget->hasSSE2()) break;
24323 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24324 if (!Subtarget->hasSSE1()) break;
24326 switch (VT.SimpleTy) {
24328 // Scalar SSE types.
24331 return std::make_pair(0U, &X86::FR32RegClass);
24334 return std::make_pair(0U, &X86::FR64RegClass);
24342 return std::make_pair(0U, &X86::VR128RegClass);
24350 return std::make_pair(0U, &X86::VR256RegClass);
24355 return std::make_pair(0U, &X86::VR512RegClass);
24361 // Use the default implementation in TargetLowering to convert the register
24362 // constraint into a member of a register class.
24363 std::pair<unsigned, const TargetRegisterClass*> Res;
24364 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24366 // Not found as a standard register?
24368 // Map st(0) -> st(7) -> ST0
24369 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24370 tolower(Constraint[1]) == 's' &&
24371 tolower(Constraint[2]) == 't' &&
24372 Constraint[3] == '(' &&
24373 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24374 Constraint[5] == ')' &&
24375 Constraint[6] == '}') {
24377 Res.first = X86::FP0+Constraint[4]-'0';
24378 Res.second = &X86::RFP80RegClass;
24382 // GCC allows "st(0)" to be called just plain "st".
24383 if (StringRef("{st}").equals_lower(Constraint)) {
24384 Res.first = X86::FP0;
24385 Res.second = &X86::RFP80RegClass;
24390 if (StringRef("{flags}").equals_lower(Constraint)) {
24391 Res.first = X86::EFLAGS;
24392 Res.second = &X86::CCRRegClass;
24396 // 'A' means EAX + EDX.
24397 if (Constraint == "A") {
24398 Res.first = X86::EAX;
24399 Res.second = &X86::GR32_ADRegClass;
24405 // Otherwise, check to see if this is a register class of the wrong value
24406 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24407 // turn into {ax},{dx}.
24408 if (Res.second->hasType(VT))
24409 return Res; // Correct type already, nothing to do.
24411 // All of the single-register GCC register classes map their values onto
24412 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24413 // really want an 8-bit or 32-bit register, map to the appropriate register
24414 // class and return the appropriate register.
24415 if (Res.second == &X86::GR16RegClass) {
24416 if (VT == MVT::i8 || VT == MVT::i1) {
24417 unsigned DestReg = 0;
24418 switch (Res.first) {
24420 case X86::AX: DestReg = X86::AL; break;
24421 case X86::DX: DestReg = X86::DL; break;
24422 case X86::CX: DestReg = X86::CL; break;
24423 case X86::BX: DestReg = X86::BL; break;
24426 Res.first = DestReg;
24427 Res.second = &X86::GR8RegClass;
24429 } else if (VT == MVT::i32 || VT == MVT::f32) {
24430 unsigned DestReg = 0;
24431 switch (Res.first) {
24433 case X86::AX: DestReg = X86::EAX; break;
24434 case X86::DX: DestReg = X86::EDX; break;
24435 case X86::CX: DestReg = X86::ECX; break;
24436 case X86::BX: DestReg = X86::EBX; break;
24437 case X86::SI: DestReg = X86::ESI; break;
24438 case X86::DI: DestReg = X86::EDI; break;
24439 case X86::BP: DestReg = X86::EBP; break;
24440 case X86::SP: DestReg = X86::ESP; break;
24443 Res.first = DestReg;
24444 Res.second = &X86::GR32RegClass;
24446 } else if (VT == MVT::i64 || VT == MVT::f64) {
24447 unsigned DestReg = 0;
24448 switch (Res.first) {
24450 case X86::AX: DestReg = X86::RAX; break;
24451 case X86::DX: DestReg = X86::RDX; break;
24452 case X86::CX: DestReg = X86::RCX; break;
24453 case X86::BX: DestReg = X86::RBX; break;
24454 case X86::SI: DestReg = X86::RSI; break;
24455 case X86::DI: DestReg = X86::RDI; break;
24456 case X86::BP: DestReg = X86::RBP; break;
24457 case X86::SP: DestReg = X86::RSP; break;
24460 Res.first = DestReg;
24461 Res.second = &X86::GR64RegClass;
24464 } else if (Res.second == &X86::FR32RegClass ||
24465 Res.second == &X86::FR64RegClass ||
24466 Res.second == &X86::VR128RegClass ||
24467 Res.second == &X86::VR256RegClass ||
24468 Res.second == &X86::FR32XRegClass ||
24469 Res.second == &X86::FR64XRegClass ||
24470 Res.second == &X86::VR128XRegClass ||
24471 Res.second == &X86::VR256XRegClass ||
24472 Res.second == &X86::VR512RegClass) {
24473 // Handle references to XMM physical registers that got mapped into the
24474 // wrong class. This can happen with constraints like {xmm0} where the
24475 // target independent register mapper will just pick the first match it can
24476 // find, ignoring the required type.
24478 if (VT == MVT::f32 || VT == MVT::i32)
24479 Res.second = &X86::FR32RegClass;
24480 else if (VT == MVT::f64 || VT == MVT::i64)
24481 Res.second = &X86::FR64RegClass;
24482 else if (X86::VR128RegClass.hasType(VT))
24483 Res.second = &X86::VR128RegClass;
24484 else if (X86::VR256RegClass.hasType(VT))
24485 Res.second = &X86::VR256RegClass;
24486 else if (X86::VR512RegClass.hasType(VT))
24487 Res.second = &X86::VR512RegClass;
24493 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24495 // Scaling factors are not free at all.
24496 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24497 // will take 2 allocations in the out of order engine instead of 1
24498 // for plain addressing mode, i.e. inst (reg1).
24500 // vaddps (%rsi,%drx), %ymm0, %ymm1
24501 // Requires two allocations (one for the load, one for the computation)
24503 // vaddps (%rsi), %ymm0, %ymm1
24504 // Requires just 1 allocation, i.e., freeing allocations for other operations
24505 // and having less micro operations to execute.
24507 // For some X86 architectures, this is even worse because for instance for
24508 // stores, the complex addressing mode forces the instruction to use the
24509 // "load" ports instead of the dedicated "store" port.
24510 // E.g., on Haswell:
24511 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24512 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24513 if (isLegalAddressingMode(AM, Ty))
24514 // Scale represents reg2 * scale, thus account for 1
24515 // as soon as we use a second register.
24516 return AM.Scale != 0;
24520 bool X86TargetLowering::isTargetFTOL() const {
24521 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();