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 "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62 "x86-experimental-vector-widening-legalization", cl::init(false),
63 cl::desc("Enable an experimental vector type legalization through widening "
64 "rather than promotion."),
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68 "x86-experimental-vector-shuffle-lowering", cl::init(false),
69 cl::desc("Enable an experimental vector shuffle lowering code path."),
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77 SelectionDAG &DAG, SDLoc dl,
78 unsigned vectorWidth) {
79 assert((vectorWidth == 128 || vectorWidth == 256) &&
80 "Unsupported vector width");
81 EVT VT = Vec.getValueType();
82 EVT ElVT = VT.getVectorElementType();
83 unsigned Factor = VT.getSizeInBits()/vectorWidth;
84 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85 VT.getVectorNumElements()/Factor);
87 // Extract from UNDEF is UNDEF.
88 if (Vec.getOpcode() == ISD::UNDEF)
89 return DAG.getUNDEF(ResultVT);
91 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
92 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94 // This is the index of the first element of the vectorWidth-bit chunk
96 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99 // If the input is a buildvector just emit a smaller one.
100 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
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 bounday. 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,
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 bounday. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163 unsigned IdxVal, SelectionDAG &DAG,
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170 unsigned IdxVal, SelectionDAG &DAG,
172 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181 unsigned NumElems, SelectionDAG &DAG,
183 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188 unsigned NumElems, SelectionDAG &DAG,
190 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195 if (TT.isOSBinFormatMachO()) {
196 if (TT.getArch() == Triple::x86_64)
197 return new X86_64MachoTargetObjectFile();
198 return new TargetLoweringObjectFileMachO();
202 return new X86LinuxTargetObjectFile();
203 if (TT.isOSBinFormatELF())
204 return new TargetLoweringObjectFileELF();
205 if (TT.isKnownWindowsMSVCEnvironment())
206 return new X86WindowsTargetObjectFile();
207 if (TT.isOSBinFormatCOFF())
208 return new TargetLoweringObjectFileCOFF();
209 llvm_unreachable("unknown subtarget type");
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216 Subtarget = &TM.getSubtarget<X86Subtarget>();
217 X86ScalarSSEf64 = Subtarget->hasSSE2();
218 X86ScalarSSEf32 = Subtarget->hasSSE1();
219 TD = getDataLayout();
221 resetOperationActions();
224 void X86TargetLowering::resetOperationActions() {
225 const TargetMachine &TM = getTargetMachine();
226 static bool FirstTimeThrough = true;
228 // If none of the target options have changed, then we don't need to reset the
229 // operation actions.
230 if (!FirstTimeThrough && TO == TM.Options) return;
232 if (!FirstTimeThrough) {
233 // Reinitialize the actions.
235 FirstTimeThrough = false;
240 // Set up the TargetLowering object.
241 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243 // X86 is weird, it always uses i8 for shift amounts and setcc results.
244 setBooleanContents(ZeroOrOneBooleanContent);
245 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 // For 64-bit since we have so many registers use the ILP scheduler, for
249 // 32-bit code use the register pressure specific scheduling.
250 // For Atom, always use ILP scheduling.
251 if (Subtarget->isAtom())
252 setSchedulingPreference(Sched::ILP);
253 else if (Subtarget->is64Bit())
254 setSchedulingPreference(Sched::ILP);
256 setSchedulingPreference(Sched::RegPressure);
257 const X86RegisterInfo *RegInfo =
258 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261 // Bypass expensive divides on Atom when compiling with O2
262 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263 addBypassSlowDiv(32, 8);
264 if (Subtarget->is64Bit())
265 addBypassSlowDiv(64, 16);
268 if (Subtarget->isTargetKnownWindowsMSVC()) {
269 // Setup Windows compiler runtime calls.
270 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272 setLibcallName(RTLIB::SREM_I64, "_allrem");
273 setLibcallName(RTLIB::UREM_I64, "_aullrem");
274 setLibcallName(RTLIB::MUL_I64, "_allmul");
275 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281 // The _ftol2 runtime function has an unusual calling conv, which
282 // is modeled by a special pseudo-instruction.
283 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289 if (Subtarget->isTargetDarwin()) {
290 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291 setUseUnderscoreSetJmp(false);
292 setUseUnderscoreLongJmp(false);
293 } else if (Subtarget->isTargetWindowsGNU()) {
294 // MS runtime is weird: it exports _setjmp, but longjmp!
295 setUseUnderscoreSetJmp(true);
296 setUseUnderscoreLongJmp(false);
298 setUseUnderscoreSetJmp(true);
299 setUseUnderscoreLongJmp(true);
302 // Set up the register classes.
303 addRegisterClass(MVT::i8, &X86::GR8RegClass);
304 addRegisterClass(MVT::i16, &X86::GR16RegClass);
305 addRegisterClass(MVT::i32, &X86::GR32RegClass);
306 if (Subtarget->is64Bit())
307 addRegisterClass(MVT::i64, &X86::GR64RegClass);
309 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311 // We don't accept any truncstore of integer registers.
312 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
319 // SETOEQ and SETUNE require checking two conditions.
320 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
330 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
336 } else if (!TM.Options.UseSoftFloat) {
337 // We have an algorithm for SSE2->double, and we turn this into a
338 // 64-bit FILD followed by conditional FADD for other targets.
339 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
340 // We have an algorithm for SSE2, and we turn this into a 64-bit
341 // FILD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
345 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
350 if (!TM.Options.UseSoftFloat) {
351 // SSE has no i16 to fp conversion, only i32
352 if (X86ScalarSSEf32) {
353 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
354 // f32 and f64 cases are Legal, f80 case is not
355 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
357 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
365 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
366 // are Legal, f80 is custom lowered.
367 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
368 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
370 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
375 if (X86ScalarSSEf32) {
376 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
377 // f32 and f64 cases are Legal, f80 case is not
378 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
380 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
384 // Handle FP_TO_UINT by promoting the destination to a larger signed
386 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
387 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
390 if (Subtarget->is64Bit()) {
391 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
393 } else if (!TM.Options.UseSoftFloat) {
394 // Since AVX is a superset of SSE3, only check for SSE here.
395 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396 // Expand FP_TO_UINT into a select.
397 // FIXME: We would like to use a Custom expander here eventually to do
398 // the optimal thing for SSE vs. the default expansion in the legalizer.
399 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
401 // With SSE3 we can use fisttpll to convert to a signed i64; without
402 // SSE, we're stuck with a fistpll.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
406 if (isTargetFTOL()) {
407 // Use the _ftol2 runtime function, which has a pseudo-instruction
408 // to handle its weird calling convention.
409 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
412 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413 if (!X86ScalarSSEf64) {
414 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
415 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
418 // Without SSE, i64->f64 goes through memory.
419 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
423 // Scalar integer divide and remainder are lowered to use operations that
424 // produce two results, to match the available instructions. This exposes
425 // the two-result form to trivial CSE, which is able to combine x/y and x%y
426 // into a single instruction.
428 // Scalar integer multiply-high is also lowered to use two-result
429 // operations, to match the available instructions. However, plain multiply
430 // (low) operations are left as Legal, as there are single-result
431 // instructions for this in x86. Using the two-result multiply instructions
432 // when both high and low results are needed must be arranged by dagcombine.
433 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435 setOperationAction(ISD::MULHS, VT, Expand);
436 setOperationAction(ISD::MULHU, VT, Expand);
437 setOperationAction(ISD::SDIV, VT, Expand);
438 setOperationAction(ISD::UDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UREM, VT, Expand);
442 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443 setOperationAction(ISD::ADDC, VT, Custom);
444 setOperationAction(ISD::ADDE, VT, Custom);
445 setOperationAction(ISD::SUBC, VT, Custom);
446 setOperationAction(ISD::SUBE, VT, Custom);
449 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
450 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
451 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
452 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
454 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
470 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
471 setOperationAction(ISD::FREM , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f64 , Expand);
473 setOperationAction(ISD::FREM , MVT::f80 , Expand);
474 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
476 // Promote the i8 variants and force them on up to i32 which has a shorter
478 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
482 if (Subtarget->hasBMI()) {
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
494 if (Subtarget->hasLZCNT()) {
495 // When promoting the i8 variants, force them to i32 for a shorter
497 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
498 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
500 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
507 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
512 if (Subtarget->is64Bit()) {
513 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518 // Special handling for half-precision floating point conversions.
519 // If we don't have F16C support, then lower half float conversions
520 // into library calls.
521 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
526 // There's never any support for operations beyond MVT::f32.
527 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537 if (Subtarget->hasPOPCNT()) {
538 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
540 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
541 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
542 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
543 if (Subtarget->is64Bit())
544 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
547 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
549 if (!Subtarget->hasMOVBE())
550 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
552 // These should be promoted to a larger select which is supported.
553 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
554 // X86 wants to expand cmov itself.
555 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
556 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
557 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
558 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
559 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
560 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
561 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
562 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
563 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
564 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
565 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
566 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
569 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
571 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
572 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574 // support continuation, user-level threading, and etc.. As a result, no
575 // other SjLj exception interfaces are implemented and please don't build
576 // your own exception handling based on them.
577 // LLVM/Clang supports zero-cost DWARF exception handling.
578 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
582 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
583 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
584 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
585 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
586 if (Subtarget->is64Bit())
587 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
589 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
590 if (Subtarget->is64Bit()) {
591 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
592 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
593 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
594 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
595 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
597 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
599 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
600 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
601 if (Subtarget->is64Bit()) {
602 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
603 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
604 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
607 if (Subtarget->hasSSE1())
608 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
610 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
612 // Expand certain atomics
613 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
620 if (Subtarget->hasCmpxchg16b()) {
621 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
624 // FIXME - use subtarget debug flags
625 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
630 if (Subtarget->is64Bit()) {
631 setExceptionPointerRegister(X86::RAX);
632 setExceptionSelectorRegister(X86::RDX);
634 setExceptionPointerRegister(X86::EAX);
635 setExceptionSelectorRegister(X86::EDX);
637 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643 setOperationAction(ISD::TRAP, MVT::Other, Legal);
644 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647 setOperationAction(ISD::VASTART , MVT::Other, Custom);
648 setOperationAction(ISD::VAEND , MVT::Other, Expand);
649 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650 // TargetInfo::X86_64ABIBuiltinVaList
651 setOperationAction(ISD::VAARG , MVT::Other, Custom);
652 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
654 // TargetInfo::CharPtrBuiltinVaList
655 setOperationAction(ISD::VAARG , MVT::Other, Expand);
656 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
659 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
660 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
662 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663 MVT::i64 : MVT::i32, Custom);
665 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666 // f32 and f64 use SSE.
667 // Set up the FP register classes.
668 addRegisterClass(MVT::f32, &X86::FR32RegClass);
669 addRegisterClass(MVT::f64, &X86::FR64RegClass);
671 // Use ANDPD to simulate FABS.
672 setOperationAction(ISD::FABS , MVT::f64, Custom);
673 setOperationAction(ISD::FABS , MVT::f32, Custom);
675 // Use XORP to simulate FNEG.
676 setOperationAction(ISD::FNEG , MVT::f64, Custom);
677 setOperationAction(ISD::FNEG , MVT::f32, Custom);
679 // Use ANDPD and ORPD to simulate FCOPYSIGN.
680 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
683 // Lower this to FGETSIGNx86 plus an AND.
684 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
687 // We don't support sin/cos/fmod
688 setOperationAction(ISD::FSIN , MVT::f64, Expand);
689 setOperationAction(ISD::FCOS , MVT::f64, Expand);
690 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691 setOperationAction(ISD::FSIN , MVT::f32, Expand);
692 setOperationAction(ISD::FCOS , MVT::f32, Expand);
693 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
695 // Expand FP immediates into loads from the stack, except for the special
697 addLegalFPImmediate(APFloat(+0.0)); // xorpd
698 addLegalFPImmediate(APFloat(+0.0f)); // xorps
699 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700 // Use SSE for f32, x87 for f64.
701 // Set up the FP register classes.
702 addRegisterClass(MVT::f32, &X86::FR32RegClass);
703 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
705 // Use ANDPS to simulate FABS.
706 setOperationAction(ISD::FABS , MVT::f32, Custom);
708 // Use XORP to simulate FNEG.
709 setOperationAction(ISD::FNEG , MVT::f32, Custom);
711 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
713 // Use ANDPS and ORPS to simulate FCOPYSIGN.
714 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
717 // We don't support sin/cos/fmod
718 setOperationAction(ISD::FSIN , MVT::f32, Expand);
719 setOperationAction(ISD::FCOS , MVT::f32, Expand);
720 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
722 // Special cases we handle for FP constants.
723 addLegalFPImmediate(APFloat(+0.0f)); // xorps
724 addLegalFPImmediate(APFloat(+0.0)); // FLD0
725 addLegalFPImmediate(APFloat(+1.0)); // FLD1
726 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 } else if (!TM.Options.UseSoftFloat) {
735 // f32 and f64 in x87.
736 // Set up the FP register classes.
737 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
740 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
741 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
742 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
745 if (!TM.Options.UnsafeFPMath) {
746 setOperationAction(ISD::FSIN , MVT::f64, Expand);
747 setOperationAction(ISD::FSIN , MVT::f32, Expand);
748 setOperationAction(ISD::FCOS , MVT::f64, Expand);
749 setOperationAction(ISD::FCOS , MVT::f32, Expand);
750 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
753 addLegalFPImmediate(APFloat(+0.0)); // FLD0
754 addLegalFPImmediate(APFloat(+1.0)); // FLD1
755 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
763 // We don't support FMA.
764 setOperationAction(ISD::FMA, MVT::f64, Expand);
765 setOperationAction(ISD::FMA, MVT::f32, Expand);
767 // Long double always uses X87.
768 if (!TM.Options.UseSoftFloat) {
769 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
771 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
773 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774 addLegalFPImmediate(TmpFlt); // FLD0
776 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
779 APFloat TmpFlt2(+1.0);
780 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
782 addLegalFPImmediate(TmpFlt2); // FLD1
783 TmpFlt2.changeSign();
784 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
787 if (!TM.Options.UnsafeFPMath) {
788 setOperationAction(ISD::FSIN , MVT::f80, Expand);
789 setOperationAction(ISD::FCOS , MVT::f80, Expand);
790 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
793 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
795 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796 setOperationAction(ISD::FRINT, MVT::f80, Expand);
797 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798 setOperationAction(ISD::FMA, MVT::f80, Expand);
801 // Always use a library call for pow.
802 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
803 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
804 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
806 setOperationAction(ISD::FLOG, MVT::f80, Expand);
807 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809 setOperationAction(ISD::FEXP, MVT::f80, Expand);
810 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
812 // First set operation action for all vector types to either promote
813 // (for widening) or expand (for scalarization). Then we will selectively
814 // turn on ones that can be effectively codegen'd.
815 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817 MVT VT = (MVT::SimpleValueType)i;
818 setOperationAction(ISD::ADD , VT, Expand);
819 setOperationAction(ISD::SUB , VT, Expand);
820 setOperationAction(ISD::FADD, VT, Expand);
821 setOperationAction(ISD::FNEG, VT, Expand);
822 setOperationAction(ISD::FSUB, VT, Expand);
823 setOperationAction(ISD::MUL , VT, Expand);
824 setOperationAction(ISD::FMUL, VT, Expand);
825 setOperationAction(ISD::SDIV, VT, Expand);
826 setOperationAction(ISD::UDIV, VT, Expand);
827 setOperationAction(ISD::FDIV, VT, Expand);
828 setOperationAction(ISD::SREM, VT, Expand);
829 setOperationAction(ISD::UREM, VT, Expand);
830 setOperationAction(ISD::LOAD, VT, Expand);
831 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836 setOperationAction(ISD::FABS, VT, Expand);
837 setOperationAction(ISD::FSIN, VT, Expand);
838 setOperationAction(ISD::FSINCOS, VT, Expand);
839 setOperationAction(ISD::FCOS, VT, Expand);
840 setOperationAction(ISD::FSINCOS, VT, Expand);
841 setOperationAction(ISD::FREM, VT, Expand);
842 setOperationAction(ISD::FMA, VT, Expand);
843 setOperationAction(ISD::FPOWI, VT, Expand);
844 setOperationAction(ISD::FSQRT, VT, Expand);
845 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846 setOperationAction(ISD::FFLOOR, VT, Expand);
847 setOperationAction(ISD::FCEIL, VT, Expand);
848 setOperationAction(ISD::FTRUNC, VT, Expand);
849 setOperationAction(ISD::FRINT, VT, Expand);
850 setOperationAction(ISD::FNEARBYINT, VT, Expand);
851 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852 setOperationAction(ISD::MULHS, VT, Expand);
853 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854 setOperationAction(ISD::MULHU, VT, Expand);
855 setOperationAction(ISD::SDIVREM, VT, Expand);
856 setOperationAction(ISD::UDIVREM, VT, Expand);
857 setOperationAction(ISD::FPOW, VT, Expand);
858 setOperationAction(ISD::CTPOP, VT, Expand);
859 setOperationAction(ISD::CTTZ, VT, Expand);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861 setOperationAction(ISD::CTLZ, VT, Expand);
862 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863 setOperationAction(ISD::SHL, VT, Expand);
864 setOperationAction(ISD::SRA, VT, Expand);
865 setOperationAction(ISD::SRL, VT, Expand);
866 setOperationAction(ISD::ROTL, VT, Expand);
867 setOperationAction(ISD::ROTR, VT, Expand);
868 setOperationAction(ISD::BSWAP, VT, Expand);
869 setOperationAction(ISD::SETCC, VT, Expand);
870 setOperationAction(ISD::FLOG, VT, Expand);
871 setOperationAction(ISD::FLOG2, VT, Expand);
872 setOperationAction(ISD::FLOG10, VT, Expand);
873 setOperationAction(ISD::FEXP, VT, Expand);
874 setOperationAction(ISD::FEXP2, VT, Expand);
875 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880 setOperationAction(ISD::TRUNCATE, VT, Expand);
881 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884 setOperationAction(ISD::VSELECT, VT, Expand);
885 setOperationAction(ISD::SELECT_CC, VT, Expand);
886 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888 setTruncStoreAction(VT,
889 (MVT::SimpleValueType)InnerVT, Expand);
890 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
893 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894 // we have to deal with them whether we ask for Expansion or not. Setting
895 // Expand causes its own optimisation problems though, so leave them legal.
896 if (VT.getVectorElementType() == MVT::i1)
897 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
900 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901 // with -msoft-float, disable use of MMX as well.
902 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904 // No operations on x86mmx supported, everything uses intrinsics.
907 // MMX-sized vectors (other than x86mmx) are expected to be expanded
908 // into smaller operations.
909 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
910 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
911 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
912 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
913 setOperationAction(ISD::AND, MVT::v8i8, Expand);
914 setOperationAction(ISD::AND, MVT::v4i16, Expand);
915 setOperationAction(ISD::AND, MVT::v2i32, Expand);
916 setOperationAction(ISD::AND, MVT::v1i64, Expand);
917 setOperationAction(ISD::OR, MVT::v8i8, Expand);
918 setOperationAction(ISD::OR, MVT::v4i16, Expand);
919 setOperationAction(ISD::OR, MVT::v2i32, Expand);
920 setOperationAction(ISD::OR, MVT::v1i64, Expand);
921 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
922 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
923 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
924 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
930 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
931 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
932 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
933 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
934 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
936 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
937 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
939 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
942 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
943 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
944 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
945 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
946 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
947 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
948 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
949 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
950 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
951 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
956 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
959 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960 // registers cannot be used even for integer operations.
961 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
966 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
967 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
968 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
969 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
970 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
971 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
972 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
973 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
974 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
975 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
976 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
977 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
978 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
979 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
980 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
981 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
982 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
983 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
984 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
985 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
986 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
987 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
990 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
991 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
992 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
995 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to custom lower non-power-of-2 vectors
1004 if (!isPowerOf2_32(VT.getVectorNumElements()))
1006 // Do not attempt to custom lower non-128-bit vectors
1007 if (!VT.is128BitVector())
1009 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1010 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1014 // We support custom legalizing of sext and anyext loads for specific
1015 // memory vector types which we can load as a scalar (or sequence of
1016 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017 // loads these must work with a single scalar load.
1018 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019 if (Subtarget->is64Bit()) {
1020 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1033 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1034 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1035 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1037 if (Subtarget->is64Bit()) {
1038 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1039 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1042 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044 MVT VT = (MVT::SimpleValueType)i;
1046 // Do not attempt to promote non-128-bit vectors
1047 if (!VT.is128BitVector())
1050 setOperationAction(ISD::AND, VT, Promote);
1051 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1052 setOperationAction(ISD::OR, VT, Promote);
1053 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1054 setOperationAction(ISD::XOR, VT, Promote);
1055 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1056 setOperationAction(ISD::LOAD, VT, Promote);
1057 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1058 setOperationAction(ISD::SELECT, VT, Promote);
1059 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1062 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1064 // Custom lower v2i64 and v2f64 selects.
1065 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1066 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1067 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1068 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1070 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1073 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1074 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1075 // As there is no 64-bit GPR available, we need build a special custom
1076 // sequence to convert from v2i32 to v2f32.
1077 if (!Subtarget->is64Bit())
1078 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1080 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1081 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1083 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1085 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1086 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1087 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1090 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1092 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1093 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1094 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1095 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1096 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1097 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1098 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1099 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1100 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1102 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1103 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1104 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1105 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1106 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1107 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1108 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1109 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1110 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1111 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1113 // FIXME: Do we need to handle scalar-to-vector here?
1114 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1116 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1117 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1118 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1119 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1120 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1121 // There is no BLENDI for byte vectors. We don't need to custom lower
1122 // some vselects for now.
1123 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1125 // SSE41 brings specific instructions for doing vector sign extend even in
1126 // cases where we don't have SRA.
1127 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1131 // i8 and i16 vectors are custom , because the source register and source
1132 // source memory operand types are not the same width. f32 vectors are
1133 // custom since the immediate controlling the insert encodes additional
1135 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1137 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1138 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1140 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1145 // FIXME: these should be Legal but thats only for the case where
1146 // the index is constant. For now custom expand to deal with that.
1147 if (Subtarget->is64Bit()) {
1148 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1149 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1153 if (Subtarget->hasSSE2()) {
1154 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1155 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1157 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1158 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1160 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1161 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1163 // In the customized shift lowering, the legal cases in AVX2 will be
1165 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1166 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1168 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1169 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1171 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1174 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1176 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1178 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1179 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1180 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1182 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1183 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1184 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1186 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1187 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1188 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1189 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1190 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1192 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1193 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1194 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1195 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1196 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1197 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1199 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1200 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1201 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1202 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1203 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1205 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1206 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1208 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1209 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1210 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1212 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213 // even though v8i16 is a legal type.
1214 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1215 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1216 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1218 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1219 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1220 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1222 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1223 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1225 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1227 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1228 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1231 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1233 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1234 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1237 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1238 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1239 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1241 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1242 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1243 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1245 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1246 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1247 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1248 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1250 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1251 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1252 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1253 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1254 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1255 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1256 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1257 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1258 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1259 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1260 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1261 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1263 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1265 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1266 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1267 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1268 setOperationAction(ISD::FMA, MVT::f32, Legal);
1269 setOperationAction(ISD::FMA, MVT::f64, Legal);
1272 if (Subtarget->hasInt256()) {
1273 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1274 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1275 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1276 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1278 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1279 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1280 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1281 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1283 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1284 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1285 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1286 // Don't lower v32i8 because there is no 128-bit byte mul
1288 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1289 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1290 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1291 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1293 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1294 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1296 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1297 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1298 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1299 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1301 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1302 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1303 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1304 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1306 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1307 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1308 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1309 // Don't lower v32i8 because there is no 128-bit byte mul
1312 // In the customized shift lowering, the legal cases in AVX2 will be
1314 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1315 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1317 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1318 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1320 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1322 // Custom lower several nodes for 256-bit types.
1323 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325 MVT VT = (MVT::SimpleValueType)i;
1327 // Extract subvector is special because the value type
1328 // (result) is 128-bit but the source is 256-bit wide.
1329 if (VT.is128BitVector())
1330 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1332 // Do not attempt to custom lower other non-256-bit vectors
1333 if (!VT.is256BitVector())
1336 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1337 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1338 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1341 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1342 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1345 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347 MVT VT = (MVT::SimpleValueType)i;
1349 // Do not attempt to promote non-256-bit vectors
1350 if (!VT.is256BitVector())
1353 setOperationAction(ISD::AND, VT, Promote);
1354 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1355 setOperationAction(ISD::OR, VT, Promote);
1356 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1357 setOperationAction(ISD::XOR, VT, Promote);
1358 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1359 setOperationAction(ISD::LOAD, VT, Promote);
1360 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1361 setOperationAction(ISD::SELECT, VT, Promote);
1362 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1366 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1370 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1372 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1373 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1374 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1376 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1377 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1378 setOperationAction(ISD::XOR, MVT::i1, Legal);
1379 setOperationAction(ISD::OR, MVT::i1, Legal);
1380 setOperationAction(ISD::AND, MVT::i1, Legal);
1381 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1382 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1383 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1384 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1385 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1386 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1388 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1390 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1391 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1392 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1393 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1395 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1396 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1397 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1398 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1399 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1400 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1401 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1402 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1404 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1405 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1406 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1407 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1408 if (Subtarget->is64Bit()) {
1409 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1410 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1411 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1412 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1414 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1416 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1417 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1418 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1419 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1421 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1422 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1423 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1425 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1426 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1427 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1428 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1429 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1430 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1431 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1432 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1434 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1437 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
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::v8i1, Custom);
1444 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1446 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1447 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1449 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1454 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1456 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1459 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1461 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1462 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1465 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1467 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1469 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1470 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1472 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1473 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1475 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1476 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1478 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1479 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1481 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1482 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1483 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1485 if (Subtarget->hasCDI()) {
1486 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1487 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1490 // Custom lower several nodes.
1491 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493 MVT VT = (MVT::SimpleValueType)i;
1495 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496 // Extract subvector is special because the value type
1497 // (result) is 256/128-bit but the source is 512-bit wide.
1498 if (VT.is128BitVector() || VT.is256BitVector())
1499 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1501 if (VT.getVectorElementType() == MVT::i1)
1502 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1504 // Do not attempt to custom lower other non-512-bit vectors
1505 if (!VT.is512BitVector())
1508 if ( EltSize >= 32) {
1509 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1510 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1511 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1512 setOperationAction(ISD::VSELECT, VT, Legal);
1513 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1514 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1515 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1518 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519 MVT VT = (MVT::SimpleValueType)i;
1521 // Do not attempt to promote non-256-bit vectors
1522 if (!VT.is512BitVector())
1525 setOperationAction(ISD::SELECT, VT, Promote);
1526 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1530 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1532 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536 // of this type with custom code.
1537 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1543 // We want to custom lower some of our intrinsics.
1544 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547 if (!Subtarget->is64Bit())
1548 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1550 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551 // handle type legalization for these operations here.
1553 // FIXME: We really should do custom legalization for addition and
1554 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1555 // than generic legalization for 64-bit multiplication-with-overflow, though.
1556 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557 // Add/Sub/Mul with overflow operations are custom lowered.
1559 setOperationAction(ISD::SADDO, VT, Custom);
1560 setOperationAction(ISD::UADDO, VT, Custom);
1561 setOperationAction(ISD::SSUBO, VT, Custom);
1562 setOperationAction(ISD::USUBO, VT, Custom);
1563 setOperationAction(ISD::SMULO, VT, Custom);
1564 setOperationAction(ISD::UMULO, VT, Custom);
1567 // There are no 8-bit 3-address imul/mul instructions
1568 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1571 if (!Subtarget->is64Bit()) {
1572 // These libcalls are not available in 32-bit.
1573 setLibcallName(RTLIB::SHL_I128, nullptr);
1574 setLibcallName(RTLIB::SRL_I128, nullptr);
1575 setLibcallName(RTLIB::SRA_I128, nullptr);
1578 // Combine sin / cos into one node or libcall if possible.
1579 if (Subtarget->hasSinCos()) {
1580 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582 if (Subtarget->isTargetDarwin()) {
1583 // For MacOSX, we don't want to the normal expansion of a libcall to
1584 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1586 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1591 if (Subtarget->isTargetWin64()) {
1592 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594 setOperationAction(ISD::SREM, MVT::i128, Custom);
1595 setOperationAction(ISD::UREM, MVT::i128, Custom);
1596 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1600 // We have target-specific dag combine patterns for the following nodes:
1601 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603 setTargetDAGCombine(ISD::VSELECT);
1604 setTargetDAGCombine(ISD::SELECT);
1605 setTargetDAGCombine(ISD::SHL);
1606 setTargetDAGCombine(ISD::SRA);
1607 setTargetDAGCombine(ISD::SRL);
1608 setTargetDAGCombine(ISD::OR);
1609 setTargetDAGCombine(ISD::AND);
1610 setTargetDAGCombine(ISD::ADD);
1611 setTargetDAGCombine(ISD::FADD);
1612 setTargetDAGCombine(ISD::FSUB);
1613 setTargetDAGCombine(ISD::FMA);
1614 setTargetDAGCombine(ISD::SUB);
1615 setTargetDAGCombine(ISD::LOAD);
1616 setTargetDAGCombine(ISD::STORE);
1617 setTargetDAGCombine(ISD::ZERO_EXTEND);
1618 setTargetDAGCombine(ISD::ANY_EXTEND);
1619 setTargetDAGCombine(ISD::SIGN_EXTEND);
1620 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621 setTargetDAGCombine(ISD::TRUNCATE);
1622 setTargetDAGCombine(ISD::SINT_TO_FP);
1623 setTargetDAGCombine(ISD::SETCC);
1624 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625 setTargetDAGCombine(ISD::BUILD_VECTOR);
1626 if (Subtarget->is64Bit())
1627 setTargetDAGCombine(ISD::MUL);
1628 setTargetDAGCombine(ISD::XOR);
1630 computeRegisterProperties();
1632 // On Darwin, -Os means optimize for size without hurting performance,
1633 // do not reduce the limit.
1634 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640 setPrefLoopAlignment(4); // 2^4 bytes.
1642 // Predictable cmov don't hurt on atom because it's in-order.
1643 PredictableSelectIsExpensive = !Subtarget->isAtom();
1645 setPrefFunctionAlignment(4); // 2^4 bytes.
1648 TargetLoweringBase::LegalizeTypeAction
1649 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1650 if (ExperimentalVectorWideningLegalization &&
1651 VT.getVectorNumElements() != 1 &&
1652 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1653 return TypeWidenVector;
1655 return TargetLoweringBase::getPreferredVectorAction(VT);
1658 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1660 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1662 if (Subtarget->hasAVX512())
1663 switch(VT.getVectorNumElements()) {
1664 case 8: return MVT::v8i1;
1665 case 16: return MVT::v16i1;
1668 return VT.changeVectorElementTypeToInteger();
1671 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1672 /// the desired ByVal argument alignment.
1673 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1676 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1677 if (VTy->getBitWidth() == 128)
1679 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1680 unsigned EltAlign = 0;
1681 getMaxByValAlign(ATy->getElementType(), EltAlign);
1682 if (EltAlign > MaxAlign)
1683 MaxAlign = EltAlign;
1684 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1685 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1686 unsigned EltAlign = 0;
1687 getMaxByValAlign(STy->getElementType(i), EltAlign);
1688 if (EltAlign > MaxAlign)
1689 MaxAlign = EltAlign;
1696 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1697 /// function arguments in the caller parameter area. For X86, aggregates
1698 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1699 /// are at 4-byte boundaries.
1700 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1701 if (Subtarget->is64Bit()) {
1702 // Max of 8 and alignment of type.
1703 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710 if (Subtarget->hasSSE1())
1711 getMaxByValAlign(Ty, Align);
1715 /// getOptimalMemOpType - Returns the target specific optimal type for load
1716 /// and store operations as a result of memset, memcpy, and memmove
1717 /// lowering. If DstAlign is zero that means it's safe to destination
1718 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1719 /// means there isn't a need to check it against alignment requirement,
1720 /// probably because the source does not need to be loaded. If 'IsMemset' is
1721 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1722 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1723 /// source is constant so it does not need to be loaded.
1724 /// It returns EVT::Other if the type should be determined using generic
1725 /// target-independent logic.
1727 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1728 unsigned DstAlign, unsigned SrcAlign,
1729 bool IsMemset, bool ZeroMemset,
1731 MachineFunction &MF) const {
1732 const Function *F = MF.getFunction();
1733 if ((!IsMemset || ZeroMemset) &&
1734 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1735 Attribute::NoImplicitFloat)) {
1737 (Subtarget->isUnalignedMemAccessFast() ||
1738 ((DstAlign == 0 || DstAlign >= 16) &&
1739 (SrcAlign == 0 || SrcAlign >= 16)))) {
1741 if (Subtarget->hasInt256())
1743 if (Subtarget->hasFp256())
1746 if (Subtarget->hasSSE2())
1748 if (Subtarget->hasSSE1())
1750 } else if (!MemcpyStrSrc && Size >= 8 &&
1751 !Subtarget->is64Bit() &&
1752 Subtarget->hasSSE2()) {
1753 // Do not use f64 to lower memcpy if source is string constant. It's
1754 // better to use i32 to avoid the loads.
1758 if (Subtarget->is64Bit() && Size >= 8)
1763 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1765 return X86ScalarSSEf32;
1766 else if (VT == MVT::f64)
1767 return X86ScalarSSEf64;
1772 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1776 *Fast = Subtarget->isUnalignedMemAccessFast();
1780 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1781 /// current function. The returned value is a member of the
1782 /// MachineJumpTableInfo::JTEntryKind enum.
1783 unsigned X86TargetLowering::getJumpTableEncoding() const {
1784 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1786 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1787 Subtarget->isPICStyleGOT())
1788 return MachineJumpTableInfo::EK_Custom32;
1790 // Otherwise, use the normal jump table encoding heuristics.
1791 return TargetLowering::getJumpTableEncoding();
1795 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1796 const MachineBasicBlock *MBB,
1797 unsigned uid,MCContext &Ctx) const{
1798 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1799 Subtarget->isPICStyleGOT());
1800 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1802 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1803 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1806 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1808 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1809 SelectionDAG &DAG) const {
1810 if (!Subtarget->is64Bit())
1811 // This doesn't have SDLoc associated with it, but is not really the
1812 // same as a Register.
1813 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1817 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1818 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1820 const MCExpr *X86TargetLowering::
1821 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1822 MCContext &Ctx) const {
1823 // X86-64 uses RIP relative addressing based on the jump table label.
1824 if (Subtarget->isPICStyleRIPRel())
1825 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1827 // Otherwise, the reference is relative to the PIC base.
1828 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1831 // FIXME: Why this routine is here? Move to RegInfo!
1832 std::pair<const TargetRegisterClass*, uint8_t>
1833 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1834 const TargetRegisterClass *RRC = nullptr;
1836 switch (VT.SimpleTy) {
1838 return TargetLowering::findRepresentativeClass(VT);
1839 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1840 RRC = Subtarget->is64Bit() ?
1841 (const TargetRegisterClass*)&X86::GR64RegClass :
1842 (const TargetRegisterClass*)&X86::GR32RegClass;
1845 RRC = &X86::VR64RegClass;
1847 case MVT::f32: case MVT::f64:
1848 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1849 case MVT::v4f32: case MVT::v2f64:
1850 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1852 RRC = &X86::VR128RegClass;
1855 return std::make_pair(RRC, Cost);
1858 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1859 unsigned &Offset) const {
1860 if (!Subtarget->isTargetLinux())
1863 if (Subtarget->is64Bit()) {
1864 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1866 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1878 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1879 unsigned DestAS) const {
1880 assert(SrcAS != DestAS && "Expected different address spaces!");
1882 return SrcAS < 256 && DestAS < 256;
1885 //===----------------------------------------------------------------------===//
1886 // Return Value Calling Convention Implementation
1887 //===----------------------------------------------------------------------===//
1889 #include "X86GenCallingConv.inc"
1892 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1893 MachineFunction &MF, bool isVarArg,
1894 const SmallVectorImpl<ISD::OutputArg> &Outs,
1895 LLVMContext &Context) const {
1896 SmallVector<CCValAssign, 16> RVLocs;
1897 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1899 return CCInfo.CheckReturn(Outs, RetCC_X86);
1902 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1903 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1908 X86TargetLowering::LowerReturn(SDValue Chain,
1909 CallingConv::ID CallConv, bool isVarArg,
1910 const SmallVectorImpl<ISD::OutputArg> &Outs,
1911 const SmallVectorImpl<SDValue> &OutVals,
1912 SDLoc dl, SelectionDAG &DAG) const {
1913 MachineFunction &MF = DAG.getMachineFunction();
1914 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1916 SmallVector<CCValAssign, 16> RVLocs;
1917 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1918 RVLocs, *DAG.getContext());
1919 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1922 SmallVector<SDValue, 6> RetOps;
1923 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1924 // Operand #1 = Bytes To Pop
1925 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1928 // Copy the result values into the output registers.
1929 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1930 CCValAssign &VA = RVLocs[i];
1931 assert(VA.isRegLoc() && "Can only return in registers!");
1932 SDValue ValToCopy = OutVals[i];
1933 EVT ValVT = ValToCopy.getValueType();
1935 // Promote values to the appropriate types
1936 if (VA.getLocInfo() == CCValAssign::SExt)
1937 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1938 else if (VA.getLocInfo() == CCValAssign::ZExt)
1939 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1940 else if (VA.getLocInfo() == CCValAssign::AExt)
1941 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942 else if (VA.getLocInfo() == CCValAssign::BCvt)
1943 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1945 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1946 "Unexpected FP-extend for return value.");
1948 // If this is x86-64, and we disabled SSE, we can't return FP values,
1949 // or SSE or MMX vectors.
1950 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1951 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1952 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1953 report_fatal_error("SSE register return with SSE disabled");
1955 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1956 // llvm-gcc has never done it right and no one has noticed, so this
1957 // should be OK for now.
1958 if (ValVT == MVT::f64 &&
1959 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1960 report_fatal_error("SSE2 register return with SSE2 disabled");
1962 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1963 // the RET instruction and handled by the FP Stackifier.
1964 if (VA.getLocReg() == X86::ST0 ||
1965 VA.getLocReg() == X86::ST1) {
1966 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1967 // change the value to the FP stack register class.
1968 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1969 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1970 RetOps.push_back(ValToCopy);
1971 // Don't emit a copytoreg.
1975 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1976 // which is returned in RAX / RDX.
1977 if (Subtarget->is64Bit()) {
1978 if (ValVT == MVT::x86mmx) {
1979 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1980 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1981 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1983 // If we don't have SSE2 available, convert to v4f32 so the generated
1984 // register is legal.
1985 if (!Subtarget->hasSSE2())
1986 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1991 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1992 Flag = Chain.getValue(1);
1993 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1996 // The x86-64 ABIs require that for returning structs by value we copy
1997 // the sret argument into %rax/%eax (depending on ABI) for the return.
1998 // Win32 requires us to put the sret argument to %eax as well.
1999 // We saved the argument into a virtual register in the entry block,
2000 // so now we copy the value out and into %rax/%eax.
2001 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2002 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2003 MachineFunction &MF = DAG.getMachineFunction();
2004 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2005 unsigned Reg = FuncInfo->getSRetReturnReg();
2007 "SRetReturnReg should have been set in LowerFormalArguments().");
2008 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2011 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2012 X86::RAX : X86::EAX;
2013 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2014 Flag = Chain.getValue(1);
2016 // RAX/EAX now acts like a return value.
2017 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2020 RetOps[0] = Chain; // Update chain.
2022 // Add the flag if we have it.
2024 RetOps.push_back(Flag);
2026 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2029 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2030 if (N->getNumValues() != 1)
2032 if (!N->hasNUsesOfValue(1, 0))
2035 SDValue TCChain = Chain;
2036 SDNode *Copy = *N->use_begin();
2037 if (Copy->getOpcode() == ISD::CopyToReg) {
2038 // If the copy has a glue operand, we conservatively assume it isn't safe to
2039 // perform a tail call.
2040 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2042 TCChain = Copy->getOperand(0);
2043 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2046 bool HasRet = false;
2047 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2049 if (UI->getOpcode() != X86ISD::RET_FLAG)
2062 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2063 ISD::NodeType ExtendKind) const {
2065 // TODO: Is this also valid on 32-bit?
2066 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2067 ReturnMVT = MVT::i8;
2069 ReturnMVT = MVT::i32;
2071 MVT MinVT = getRegisterType(ReturnMVT);
2072 return VT.bitsLT(MinVT) ? MinVT : VT;
2075 /// LowerCallResult - Lower the result values of a call into the
2076 /// appropriate copies out of appropriate physical registers.
2079 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2080 CallingConv::ID CallConv, bool isVarArg,
2081 const SmallVectorImpl<ISD::InputArg> &Ins,
2082 SDLoc dl, SelectionDAG &DAG,
2083 SmallVectorImpl<SDValue> &InVals) const {
2085 // Assign locations to each value returned by this call.
2086 SmallVector<CCValAssign, 16> RVLocs;
2087 bool Is64Bit = Subtarget->is64Bit();
2088 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2089 DAG.getTarget(), RVLocs, *DAG.getContext());
2090 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2092 // Copy all of the result registers out of their specified physreg.
2093 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2094 CCValAssign &VA = RVLocs[i];
2095 EVT CopyVT = VA.getValVT();
2097 // If this is x86-64, and we disabled SSE, we can't return FP values
2098 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2099 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2100 report_fatal_error("SSE register return with SSE disabled");
2105 // If this is a call to a function that returns an fp value on the floating
2106 // point stack, we must guarantee the value is popped from the stack, so
2107 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2108 // if the return value is not used. We use the FpPOP_RETVAL instruction
2110 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2111 // If we prefer to use the value in xmm registers, copy it out as f80 and
2112 // use a truncate to move it from fp stack reg to xmm reg.
2113 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2114 SDValue Ops[] = { Chain, InFlag };
2115 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2116 MVT::Other, MVT::Glue, Ops), 1);
2117 Val = Chain.getValue(0);
2119 // Round the f80 to the right size, which also moves it to the appropriate
2121 if (CopyVT != VA.getValVT())
2122 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2123 // This truncation won't change the value.
2124 DAG.getIntPtrConstant(1));
2126 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2127 CopyVT, InFlag).getValue(1);
2128 Val = Chain.getValue(0);
2130 InFlag = Chain.getValue(2);
2131 InVals.push_back(Val);
2137 //===----------------------------------------------------------------------===//
2138 // C & StdCall & Fast Calling Convention implementation
2139 //===----------------------------------------------------------------------===//
2140 // StdCall calling convention seems to be standard for many Windows' API
2141 // routines and around. It differs from C calling convention just a little:
2142 // callee should clean up the stack, not caller. Symbols should be also
2143 // decorated in some fancy way :) It doesn't support any vector arguments.
2144 // For info on fast calling convention see Fast Calling Convention (tail call)
2145 // implementation LowerX86_32FastCCCallTo.
2147 /// CallIsStructReturn - Determines whether a call uses struct return
2149 enum StructReturnType {
2154 static StructReturnType
2155 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2157 return NotStructReturn;
2159 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2160 if (!Flags.isSRet())
2161 return NotStructReturn;
2162 if (Flags.isInReg())
2163 return RegStructReturn;
2164 return StackStructReturn;
2167 /// ArgsAreStructReturn - Determines whether a function uses struct
2168 /// return semantics.
2169 static StructReturnType
2170 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2172 return NotStructReturn;
2174 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2175 if (!Flags.isSRet())
2176 return NotStructReturn;
2177 if (Flags.isInReg())
2178 return RegStructReturn;
2179 return StackStructReturn;
2182 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2183 /// by "Src" to address "Dst" with size and alignment information specified by
2184 /// the specific parameter attribute. The copy will be passed as a byval
2185 /// function parameter.
2187 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2188 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2190 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2192 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2193 /*isVolatile*/false, /*AlwaysInline=*/true,
2194 MachinePointerInfo(), MachinePointerInfo());
2197 /// IsTailCallConvention - Return true if the calling convention is one that
2198 /// supports tail call optimization.
2199 static bool IsTailCallConvention(CallingConv::ID CC) {
2200 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2201 CC == CallingConv::HiPE);
2204 /// \brief Return true if the calling convention is a C calling convention.
2205 static bool IsCCallConvention(CallingConv::ID CC) {
2206 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2207 CC == CallingConv::X86_64_SysV);
2210 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2211 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2215 CallingConv::ID CalleeCC = CS.getCallingConv();
2216 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2222 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2223 /// a tailcall target by changing its ABI.
2224 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2225 bool GuaranteedTailCallOpt) {
2226 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2230 X86TargetLowering::LowerMemArgument(SDValue Chain,
2231 CallingConv::ID CallConv,
2232 const SmallVectorImpl<ISD::InputArg> &Ins,
2233 SDLoc dl, SelectionDAG &DAG,
2234 const CCValAssign &VA,
2235 MachineFrameInfo *MFI,
2237 // Create the nodes corresponding to a load from this parameter slot.
2238 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2239 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2240 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2241 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2244 // If value is passed by pointer we have address passed instead of the value
2246 if (VA.getLocInfo() == CCValAssign::Indirect)
2247 ValVT = VA.getLocVT();
2249 ValVT = VA.getValVT();
2251 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2252 // changed with more analysis.
2253 // In case of tail call optimization mark all arguments mutable. Since they
2254 // could be overwritten by lowering of arguments in case of a tail call.
2255 if (Flags.isByVal()) {
2256 unsigned Bytes = Flags.getByValSize();
2257 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2258 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2259 return DAG.getFrameIndex(FI, getPointerTy());
2261 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2262 VA.getLocMemOffset(), isImmutable);
2263 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2264 return DAG.getLoad(ValVT, dl, Chain, FIN,
2265 MachinePointerInfo::getFixedStack(FI),
2266 false, false, false, 0);
2271 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2272 CallingConv::ID CallConv,
2274 const SmallVectorImpl<ISD::InputArg> &Ins,
2277 SmallVectorImpl<SDValue> &InVals)
2279 MachineFunction &MF = DAG.getMachineFunction();
2280 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2282 const Function* Fn = MF.getFunction();
2283 if (Fn->hasExternalLinkage() &&
2284 Subtarget->isTargetCygMing() &&
2285 Fn->getName() == "main")
2286 FuncInfo->setForceFramePointer(true);
2288 MachineFrameInfo *MFI = MF.getFrameInfo();
2289 bool Is64Bit = Subtarget->is64Bit();
2290 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2292 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2293 "Var args not supported with calling convention fastcc, ghc or hipe");
2295 // Assign locations to all of the incoming arguments.
2296 SmallVector<CCValAssign, 16> ArgLocs;
2297 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2298 ArgLocs, *DAG.getContext());
2300 // Allocate shadow area for Win64
2302 CCInfo.AllocateStack(32, 8);
2304 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2306 unsigned LastVal = ~0U;
2308 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2309 CCValAssign &VA = ArgLocs[i];
2310 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2312 assert(VA.getValNo() != LastVal &&
2313 "Don't support value assigned to multiple locs yet");
2315 LastVal = VA.getValNo();
2317 if (VA.isRegLoc()) {
2318 EVT RegVT = VA.getLocVT();
2319 const TargetRegisterClass *RC;
2320 if (RegVT == MVT::i32)
2321 RC = &X86::GR32RegClass;
2322 else if (Is64Bit && RegVT == MVT::i64)
2323 RC = &X86::GR64RegClass;
2324 else if (RegVT == MVT::f32)
2325 RC = &X86::FR32RegClass;
2326 else if (RegVT == MVT::f64)
2327 RC = &X86::FR64RegClass;
2328 else if (RegVT.is512BitVector())
2329 RC = &X86::VR512RegClass;
2330 else if (RegVT.is256BitVector())
2331 RC = &X86::VR256RegClass;
2332 else if (RegVT.is128BitVector())
2333 RC = &X86::VR128RegClass;
2334 else if (RegVT == MVT::x86mmx)
2335 RC = &X86::VR64RegClass;
2336 else if (RegVT == MVT::i1)
2337 RC = &X86::VK1RegClass;
2338 else if (RegVT == MVT::v8i1)
2339 RC = &X86::VK8RegClass;
2340 else if (RegVT == MVT::v16i1)
2341 RC = &X86::VK16RegClass;
2342 else if (RegVT == MVT::v32i1)
2343 RC = &X86::VK32RegClass;
2344 else if (RegVT == MVT::v64i1)
2345 RC = &X86::VK64RegClass;
2347 llvm_unreachable("Unknown argument type!");
2349 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2350 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2352 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2353 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2355 if (VA.getLocInfo() == CCValAssign::SExt)
2356 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2357 DAG.getValueType(VA.getValVT()));
2358 else if (VA.getLocInfo() == CCValAssign::ZExt)
2359 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2360 DAG.getValueType(VA.getValVT()));
2361 else if (VA.getLocInfo() == CCValAssign::BCvt)
2362 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2364 if (VA.isExtInLoc()) {
2365 // Handle MMX values passed in XMM regs.
2366 if (RegVT.isVector())
2367 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2369 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2372 assert(VA.isMemLoc());
2373 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2376 // If value is passed via pointer - do a load.
2377 if (VA.getLocInfo() == CCValAssign::Indirect)
2378 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2379 MachinePointerInfo(), false, false, false, 0);
2381 InVals.push_back(ArgValue);
2384 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2385 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2386 // The x86-64 ABIs require that for returning structs by value we copy
2387 // the sret argument into %rax/%eax (depending on ABI) for the return.
2388 // Win32 requires us to put the sret argument to %eax as well.
2389 // Save the argument into a virtual register so that we can access it
2390 // from the return points.
2391 if (Ins[i].Flags.isSRet()) {
2392 unsigned Reg = FuncInfo->getSRetReturnReg();
2394 MVT PtrTy = getPointerTy();
2395 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2396 FuncInfo->setSRetReturnReg(Reg);
2398 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2399 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2405 unsigned StackSize = CCInfo.getNextStackOffset();
2406 // Align stack specially for tail calls.
2407 if (FuncIsMadeTailCallSafe(CallConv,
2408 MF.getTarget().Options.GuaranteedTailCallOpt))
2409 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2411 // If the function takes variable number of arguments, make a frame index for
2412 // the start of the first vararg value... for expansion of llvm.va_start.
2414 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2415 CallConv != CallingConv::X86_ThisCall)) {
2416 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2419 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2421 // FIXME: We should really autogenerate these arrays
2422 static const MCPhysReg GPR64ArgRegsWin64[] = {
2423 X86::RCX, X86::RDX, X86::R8, X86::R9
2425 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2426 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2428 static const MCPhysReg XMMArgRegs64Bit[] = {
2429 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2430 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2432 const MCPhysReg *GPR64ArgRegs;
2433 unsigned NumXMMRegs = 0;
2436 // The XMM registers which might contain var arg parameters are shadowed
2437 // in their paired GPR. So we only need to save the GPR to their home
2439 TotalNumIntRegs = 4;
2440 GPR64ArgRegs = GPR64ArgRegsWin64;
2442 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2443 GPR64ArgRegs = GPR64ArgRegs64Bit;
2445 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2448 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2451 bool NoImplicitFloatOps = Fn->getAttributes().
2452 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2453 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2454 "SSE register cannot be used when SSE is disabled!");
2455 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2456 NoImplicitFloatOps) &&
2457 "SSE register cannot be used when SSE is disabled!");
2458 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2459 !Subtarget->hasSSE1())
2460 // Kernel mode asks for SSE to be disabled, so don't push them
2462 TotalNumXMMRegs = 0;
2465 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2466 // Get to the caller-allocated home save location. Add 8 to account
2467 // for the return address.
2468 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2469 FuncInfo->setRegSaveFrameIndex(
2470 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2471 // Fixup to set vararg frame on shadow area (4 x i64).
2473 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2475 // For X86-64, if there are vararg parameters that are passed via
2476 // registers, then we must store them to their spots on the stack so
2477 // they may be loaded by deferencing the result of va_next.
2478 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2479 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2480 FuncInfo->setRegSaveFrameIndex(
2481 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2485 // Store the integer parameter registers.
2486 SmallVector<SDValue, 8> MemOps;
2487 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2489 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2490 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2491 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2492 DAG.getIntPtrConstant(Offset));
2493 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2494 &X86::GR64RegClass);
2495 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2497 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2498 MachinePointerInfo::getFixedStack(
2499 FuncInfo->getRegSaveFrameIndex(), Offset),
2501 MemOps.push_back(Store);
2505 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2506 // Now store the XMM (fp + vector) parameter registers.
2507 SmallVector<SDValue, 11> SaveXMMOps;
2508 SaveXMMOps.push_back(Chain);
2510 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2511 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2512 SaveXMMOps.push_back(ALVal);
2514 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2515 FuncInfo->getRegSaveFrameIndex()));
2516 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2517 FuncInfo->getVarArgsFPOffset()));
2519 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2520 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2521 &X86::VR128RegClass);
2522 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2523 SaveXMMOps.push_back(Val);
2525 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2526 MVT::Other, SaveXMMOps));
2529 if (!MemOps.empty())
2530 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2534 // Some CCs need callee pop.
2535 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2536 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2537 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2539 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2540 // If this is an sret function, the return should pop the hidden pointer.
2541 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2542 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2543 argsAreStructReturn(Ins) == StackStructReturn)
2544 FuncInfo->setBytesToPopOnReturn(4);
2548 // RegSaveFrameIndex is X86-64 only.
2549 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2550 if (CallConv == CallingConv::X86_FastCall ||
2551 CallConv == CallingConv::X86_ThisCall)
2552 // fastcc functions can't have varargs.
2553 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2556 FuncInfo->setArgumentStackSize(StackSize);
2562 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2563 SDValue StackPtr, SDValue Arg,
2564 SDLoc dl, SelectionDAG &DAG,
2565 const CCValAssign &VA,
2566 ISD::ArgFlagsTy Flags) const {
2567 unsigned LocMemOffset = VA.getLocMemOffset();
2568 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2569 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2570 if (Flags.isByVal())
2571 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2573 return DAG.getStore(Chain, dl, Arg, PtrOff,
2574 MachinePointerInfo::getStack(LocMemOffset),
2578 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2579 /// optimization is performed and it is required.
2581 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2582 SDValue &OutRetAddr, SDValue Chain,
2583 bool IsTailCall, bool Is64Bit,
2584 int FPDiff, SDLoc dl) const {
2585 // Adjust the Return address stack slot.
2586 EVT VT = getPointerTy();
2587 OutRetAddr = getReturnAddressFrameIndex(DAG);
2589 // Load the "old" Return address.
2590 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2591 false, false, false, 0);
2592 return SDValue(OutRetAddr.getNode(), 1);
2595 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2596 /// optimization is performed and it is required (FPDiff!=0).
2597 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2598 SDValue Chain, SDValue RetAddrFrIdx,
2599 EVT PtrVT, unsigned SlotSize,
2600 int FPDiff, SDLoc dl) {
2601 // Store the return address to the appropriate stack slot.
2602 if (!FPDiff) return Chain;
2603 // Calculate the new stack slot for the return address.
2604 int NewReturnAddrFI =
2605 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2607 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2608 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2609 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2615 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2616 SmallVectorImpl<SDValue> &InVals) const {
2617 SelectionDAG &DAG = CLI.DAG;
2619 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2620 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2621 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2622 SDValue Chain = CLI.Chain;
2623 SDValue Callee = CLI.Callee;
2624 CallingConv::ID CallConv = CLI.CallConv;
2625 bool &isTailCall = CLI.IsTailCall;
2626 bool isVarArg = CLI.IsVarArg;
2628 MachineFunction &MF = DAG.getMachineFunction();
2629 bool Is64Bit = Subtarget->is64Bit();
2630 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2631 StructReturnType SR = callIsStructReturn(Outs);
2632 bool IsSibcall = false;
2634 if (MF.getTarget().Options.DisableTailCalls)
2637 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2639 // Force this to be a tail call. The verifier rules are enough to ensure
2640 // that we can lower this successfully without moving the return address
2643 } else if (isTailCall) {
2644 // Check if it's really possible to do a tail call.
2645 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2646 isVarArg, SR != NotStructReturn,
2647 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2648 Outs, OutVals, Ins, DAG);
2650 // Sibcalls are automatically detected tailcalls which do not require
2652 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2659 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2660 "Var args not supported with calling convention fastcc, ghc or hipe");
2662 // Analyze operands of the call, assigning locations to each operand.
2663 SmallVector<CCValAssign, 16> ArgLocs;
2664 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2665 ArgLocs, *DAG.getContext());
2667 // Allocate shadow area for Win64
2669 CCInfo.AllocateStack(32, 8);
2671 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2673 // Get a count of how many bytes are to be pushed on the stack.
2674 unsigned NumBytes = CCInfo.getNextStackOffset();
2676 // This is a sibcall. The memory operands are available in caller's
2677 // own caller's stack.
2679 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2680 IsTailCallConvention(CallConv))
2681 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2684 if (isTailCall && !IsSibcall && !IsMustTail) {
2685 // Lower arguments at fp - stackoffset + fpdiff.
2686 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2687 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2689 FPDiff = NumBytesCallerPushed - NumBytes;
2691 // Set the delta of movement of the returnaddr stackslot.
2692 // But only set if delta is greater than previous delta.
2693 if (FPDiff < X86Info->getTCReturnAddrDelta())
2694 X86Info->setTCReturnAddrDelta(FPDiff);
2697 unsigned NumBytesToPush = NumBytes;
2698 unsigned NumBytesToPop = NumBytes;
2700 // If we have an inalloca argument, all stack space has already been allocated
2701 // for us and be right at the top of the stack. We don't support multiple
2702 // arguments passed in memory when using inalloca.
2703 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2705 if (!ArgLocs.back().isMemLoc())
2706 report_fatal_error("cannot use inalloca attribute on a register "
2708 if (ArgLocs.back().getLocMemOffset() != 0)
2709 report_fatal_error("any parameter with the inalloca attribute must be "
2710 "the only memory argument");
2714 Chain = DAG.getCALLSEQ_START(
2715 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2717 SDValue RetAddrFrIdx;
2718 // Load return address for tail calls.
2719 if (isTailCall && FPDiff)
2720 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2721 Is64Bit, FPDiff, dl);
2723 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2724 SmallVector<SDValue, 8> MemOpChains;
2727 // Walk the register/memloc assignments, inserting copies/loads. In the case
2728 // of tail call optimization arguments are handle later.
2729 const X86RegisterInfo *RegInfo =
2730 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2731 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2732 // Skip inalloca arguments, they have already been written.
2733 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2734 if (Flags.isInAlloca())
2737 CCValAssign &VA = ArgLocs[i];
2738 EVT RegVT = VA.getLocVT();
2739 SDValue Arg = OutVals[i];
2740 bool isByVal = Flags.isByVal();
2742 // Promote the value if needed.
2743 switch (VA.getLocInfo()) {
2744 default: llvm_unreachable("Unknown loc info!");
2745 case CCValAssign::Full: break;
2746 case CCValAssign::SExt:
2747 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2749 case CCValAssign::ZExt:
2750 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2752 case CCValAssign::AExt:
2753 if (RegVT.is128BitVector()) {
2754 // Special case: passing MMX values in XMM registers.
2755 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2756 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2757 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2759 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2761 case CCValAssign::BCvt:
2762 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2764 case CCValAssign::Indirect: {
2765 // Store the argument.
2766 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2767 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2768 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2769 MachinePointerInfo::getFixedStack(FI),
2776 if (VA.isRegLoc()) {
2777 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2778 if (isVarArg && IsWin64) {
2779 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2780 // shadow reg if callee is a varargs function.
2781 unsigned ShadowReg = 0;
2782 switch (VA.getLocReg()) {
2783 case X86::XMM0: ShadowReg = X86::RCX; break;
2784 case X86::XMM1: ShadowReg = X86::RDX; break;
2785 case X86::XMM2: ShadowReg = X86::R8; break;
2786 case X86::XMM3: ShadowReg = X86::R9; break;
2789 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2791 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2792 assert(VA.isMemLoc());
2793 if (!StackPtr.getNode())
2794 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2796 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2797 dl, DAG, VA, Flags));
2801 if (!MemOpChains.empty())
2802 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2804 if (Subtarget->isPICStyleGOT()) {
2805 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2808 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2809 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2811 // If we are tail calling and generating PIC/GOT style code load the
2812 // address of the callee into ECX. The value in ecx is used as target of
2813 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2814 // for tail calls on PIC/GOT architectures. Normally we would just put the
2815 // address of GOT into ebx and then call target@PLT. But for tail calls
2816 // ebx would be restored (since ebx is callee saved) before jumping to the
2819 // Note: The actual moving to ECX is done further down.
2820 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2821 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2822 !G->getGlobal()->hasProtectedVisibility())
2823 Callee = LowerGlobalAddress(Callee, DAG);
2824 else if (isa<ExternalSymbolSDNode>(Callee))
2825 Callee = LowerExternalSymbol(Callee, DAG);
2829 if (Is64Bit && isVarArg && !IsWin64) {
2830 // From AMD64 ABI document:
2831 // For calls that may call functions that use varargs or stdargs
2832 // (prototype-less calls or calls to functions containing ellipsis (...) in
2833 // the declaration) %al is used as hidden argument to specify the number
2834 // of SSE registers used. The contents of %al do not need to match exactly
2835 // the number of registers, but must be an ubound on the number of SSE
2836 // registers used and is in the range 0 - 8 inclusive.
2838 // Count the number of XMM registers allocated.
2839 static const MCPhysReg XMMArgRegs[] = {
2840 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2841 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2843 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2844 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2845 && "SSE registers cannot be used when SSE is disabled");
2847 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2848 DAG.getConstant(NumXMMRegs, MVT::i8)));
2851 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2852 // don't need this because the eligibility check rejects calls that require
2853 // shuffling arguments passed in memory.
2854 if (!IsSibcall && isTailCall) {
2855 // Force all the incoming stack arguments to be loaded from the stack
2856 // before any new outgoing arguments are stored to the stack, because the
2857 // outgoing stack slots may alias the incoming argument stack slots, and
2858 // the alias isn't otherwise explicit. This is slightly more conservative
2859 // than necessary, because it means that each store effectively depends
2860 // on every argument instead of just those arguments it would clobber.
2861 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2863 SmallVector<SDValue, 8> MemOpChains2;
2866 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2867 CCValAssign &VA = ArgLocs[i];
2870 assert(VA.isMemLoc());
2871 SDValue Arg = OutVals[i];
2872 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2873 // Skip inalloca arguments. They don't require any work.
2874 if (Flags.isInAlloca())
2876 // Create frame index.
2877 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2878 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2879 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2880 FIN = DAG.getFrameIndex(FI, getPointerTy());
2882 if (Flags.isByVal()) {
2883 // Copy relative to framepointer.
2884 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2885 if (!StackPtr.getNode())
2886 StackPtr = DAG.getCopyFromReg(Chain, dl,
2887 RegInfo->getStackRegister(),
2889 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2891 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2895 // Store relative to framepointer.
2896 MemOpChains2.push_back(
2897 DAG.getStore(ArgChain, dl, Arg, FIN,
2898 MachinePointerInfo::getFixedStack(FI),
2903 if (!MemOpChains2.empty())
2904 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2906 // Store the return address to the appropriate stack slot.
2907 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2908 getPointerTy(), RegInfo->getSlotSize(),
2912 // Build a sequence of copy-to-reg nodes chained together with token chain
2913 // and flag operands which copy the outgoing args into registers.
2915 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2916 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2917 RegsToPass[i].second, InFlag);
2918 InFlag = Chain.getValue(1);
2921 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2922 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2923 // In the 64-bit large code model, we have to make all calls
2924 // through a register, since the call instruction's 32-bit
2925 // pc-relative offset may not be large enough to hold the whole
2927 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2928 // If the callee is a GlobalAddress node (quite common, every direct call
2929 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2932 // We should use extra load for direct calls to dllimported functions in
2934 const GlobalValue *GV = G->getGlobal();
2935 if (!GV->hasDLLImportStorageClass()) {
2936 unsigned char OpFlags = 0;
2937 bool ExtraLoad = false;
2938 unsigned WrapperKind = ISD::DELETED_NODE;
2940 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2941 // external symbols most go through the PLT in PIC mode. If the symbol
2942 // has hidden or protected visibility, or if it is static or local, then
2943 // we don't need to use the PLT - we can directly call it.
2944 if (Subtarget->isTargetELF() &&
2945 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2946 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2947 OpFlags = X86II::MO_PLT;
2948 } else if (Subtarget->isPICStyleStubAny() &&
2949 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2950 (!Subtarget->getTargetTriple().isMacOSX() ||
2951 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2952 // PC-relative references to external symbols should go through $stub,
2953 // unless we're building with the leopard linker or later, which
2954 // automatically synthesizes these stubs.
2955 OpFlags = X86II::MO_DARWIN_STUB;
2956 } else if (Subtarget->isPICStyleRIPRel() &&
2957 isa<Function>(GV) &&
2958 cast<Function>(GV)->getAttributes().
2959 hasAttribute(AttributeSet::FunctionIndex,
2960 Attribute::NonLazyBind)) {
2961 // If the function is marked as non-lazy, generate an indirect call
2962 // which loads from the GOT directly. This avoids runtime overhead
2963 // at the cost of eager binding (and one extra byte of encoding).
2964 OpFlags = X86II::MO_GOTPCREL;
2965 WrapperKind = X86ISD::WrapperRIP;
2969 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2970 G->getOffset(), OpFlags);
2972 // Add a wrapper if needed.
2973 if (WrapperKind != ISD::DELETED_NODE)
2974 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2975 // Add extra indirection if needed.
2977 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2978 MachinePointerInfo::getGOT(),
2979 false, false, false, 0);
2981 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2982 unsigned char OpFlags = 0;
2984 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2985 // external symbols should go through the PLT.
2986 if (Subtarget->isTargetELF() &&
2987 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2988 OpFlags = X86II::MO_PLT;
2989 } else if (Subtarget->isPICStyleStubAny() &&
2990 (!Subtarget->getTargetTriple().isMacOSX() ||
2991 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2992 // PC-relative references to external symbols should go through $stub,
2993 // unless we're building with the leopard linker or later, which
2994 // automatically synthesizes these stubs.
2995 OpFlags = X86II::MO_DARWIN_STUB;
2998 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3002 // Returns a chain & a flag for retval copy to use.
3003 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3004 SmallVector<SDValue, 8> Ops;
3006 if (!IsSibcall && isTailCall) {
3007 Chain = DAG.getCALLSEQ_END(Chain,
3008 DAG.getIntPtrConstant(NumBytesToPop, true),
3009 DAG.getIntPtrConstant(0, true), InFlag, dl);
3010 InFlag = Chain.getValue(1);
3013 Ops.push_back(Chain);
3014 Ops.push_back(Callee);
3017 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3019 // Add argument registers to the end of the list so that they are known live
3021 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3022 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3023 RegsToPass[i].second.getValueType()));
3025 // Add a register mask operand representing the call-preserved registers.
3026 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3027 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3028 assert(Mask && "Missing call preserved mask for calling convention");
3029 Ops.push_back(DAG.getRegisterMask(Mask));
3031 if (InFlag.getNode())
3032 Ops.push_back(InFlag);
3036 //// If this is the first return lowered for this function, add the regs
3037 //// to the liveout set for the function.
3038 // This isn't right, although it's probably harmless on x86; liveouts
3039 // should be computed from returns not tail calls. Consider a void
3040 // function making a tail call to a function returning int.
3041 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3044 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3045 InFlag = Chain.getValue(1);
3047 // Create the CALLSEQ_END node.
3048 unsigned NumBytesForCalleeToPop;
3049 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3050 DAG.getTarget().Options.GuaranteedTailCallOpt))
3051 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3052 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3053 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3054 SR == StackStructReturn)
3055 // If this is a call to a struct-return function, the callee
3056 // pops the hidden struct pointer, so we have to push it back.
3057 // This is common for Darwin/X86, Linux & Mingw32 targets.
3058 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3059 NumBytesForCalleeToPop = 4;
3061 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3063 // Returns a flag for retval copy to use.
3065 Chain = DAG.getCALLSEQ_END(Chain,
3066 DAG.getIntPtrConstant(NumBytesToPop, true),
3067 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3070 InFlag = Chain.getValue(1);
3073 // Handle result values, copying them out of physregs into vregs that we
3075 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3076 Ins, dl, DAG, InVals);
3079 //===----------------------------------------------------------------------===//
3080 // Fast Calling Convention (tail call) implementation
3081 //===----------------------------------------------------------------------===//
3083 // Like std call, callee cleans arguments, convention except that ECX is
3084 // reserved for storing the tail called function address. Only 2 registers are
3085 // free for argument passing (inreg). Tail call optimization is performed
3087 // * tailcallopt is enabled
3088 // * caller/callee are fastcc
3089 // On X86_64 architecture with GOT-style position independent code only local
3090 // (within module) calls are supported at the moment.
3091 // To keep the stack aligned according to platform abi the function
3092 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3093 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3094 // If a tail called function callee has more arguments than the caller the
3095 // caller needs to make sure that there is room to move the RETADDR to. This is
3096 // achieved by reserving an area the size of the argument delta right after the
3097 // original RETADDR, but before the saved framepointer or the spilled registers
3098 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3110 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3111 /// for a 16 byte align requirement.
3113 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3114 SelectionDAG& DAG) const {
3115 MachineFunction &MF = DAG.getMachineFunction();
3116 const TargetMachine &TM = MF.getTarget();
3117 const X86RegisterInfo *RegInfo =
3118 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3119 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3120 unsigned StackAlignment = TFI.getStackAlignment();
3121 uint64_t AlignMask = StackAlignment - 1;
3122 int64_t Offset = StackSize;
3123 unsigned SlotSize = RegInfo->getSlotSize();
3124 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3125 // Number smaller than 12 so just add the difference.
3126 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3128 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3129 Offset = ((~AlignMask) & Offset) + StackAlignment +
3130 (StackAlignment-SlotSize);
3135 /// MatchingStackOffset - Return true if the given stack call argument is
3136 /// already available in the same position (relatively) of the caller's
3137 /// incoming argument stack.
3139 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3140 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3141 const X86InstrInfo *TII) {
3142 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3144 if (Arg.getOpcode() == ISD::CopyFromReg) {
3145 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3146 if (!TargetRegisterInfo::isVirtualRegister(VR))
3148 MachineInstr *Def = MRI->getVRegDef(VR);
3151 if (!Flags.isByVal()) {
3152 if (!TII->isLoadFromStackSlot(Def, FI))
3155 unsigned Opcode = Def->getOpcode();
3156 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3157 Def->getOperand(1).isFI()) {
3158 FI = Def->getOperand(1).getIndex();
3159 Bytes = Flags.getByValSize();
3163 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3164 if (Flags.isByVal())
3165 // ByVal argument is passed in as a pointer but it's now being
3166 // dereferenced. e.g.
3167 // define @foo(%struct.X* %A) {
3168 // tail call @bar(%struct.X* byval %A)
3171 SDValue Ptr = Ld->getBasePtr();
3172 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3175 FI = FINode->getIndex();
3176 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3177 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3178 FI = FINode->getIndex();
3179 Bytes = Flags.getByValSize();
3183 assert(FI != INT_MAX);
3184 if (!MFI->isFixedObjectIndex(FI))
3186 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3189 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3190 /// for tail call optimization. Targets which want to do tail call
3191 /// optimization should implement this function.
3193 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3194 CallingConv::ID CalleeCC,
3196 bool isCalleeStructRet,
3197 bool isCallerStructRet,
3199 const SmallVectorImpl<ISD::OutputArg> &Outs,
3200 const SmallVectorImpl<SDValue> &OutVals,
3201 const SmallVectorImpl<ISD::InputArg> &Ins,
3202 SelectionDAG &DAG) const {
3203 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3206 // If -tailcallopt is specified, make fastcc functions tail-callable.
3207 const MachineFunction &MF = DAG.getMachineFunction();
3208 const Function *CallerF = MF.getFunction();
3210 // If the function return type is x86_fp80 and the callee return type is not,
3211 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3212 // perform a tailcall optimization here.
3213 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3216 CallingConv::ID CallerCC = CallerF->getCallingConv();
3217 bool CCMatch = CallerCC == CalleeCC;
3218 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3219 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3221 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3222 if (IsTailCallConvention(CalleeCC) && CCMatch)
3227 // Look for obvious safe cases to perform tail call optimization that do not
3228 // require ABI changes. This is what gcc calls sibcall.
3230 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3231 // emit a special epilogue.
3232 const X86RegisterInfo *RegInfo =
3233 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3234 if (RegInfo->needsStackRealignment(MF))
3237 // Also avoid sibcall optimization if either caller or callee uses struct
3238 // return semantics.
3239 if (isCalleeStructRet || isCallerStructRet)
3242 // An stdcall/thiscall caller is expected to clean up its arguments; the
3243 // callee isn't going to do that.
3244 // FIXME: this is more restrictive than needed. We could produce a tailcall
3245 // when the stack adjustment matches. For example, with a thiscall that takes
3246 // only one argument.
3247 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3248 CallerCC == CallingConv::X86_ThisCall))
3251 // Do not sibcall optimize vararg calls unless all arguments are passed via
3253 if (isVarArg && !Outs.empty()) {
3255 // Optimizing for varargs on Win64 is unlikely to be safe without
3256 // additional testing.
3257 if (IsCalleeWin64 || IsCallerWin64)
3260 SmallVector<CCValAssign, 16> ArgLocs;
3261 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3262 DAG.getTarget(), ArgLocs, *DAG.getContext());
3264 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3265 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3266 if (!ArgLocs[i].isRegLoc())
3270 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3271 // stack. Therefore, if it's not used by the call it is not safe to optimize
3272 // this into a sibcall.
3273 bool Unused = false;
3274 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3281 SmallVector<CCValAssign, 16> RVLocs;
3282 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3283 DAG.getTarget(), RVLocs, *DAG.getContext());
3284 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3285 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3286 CCValAssign &VA = RVLocs[i];
3287 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3292 // If the calling conventions do not match, then we'd better make sure the
3293 // results are returned in the same way as what the caller expects.
3295 SmallVector<CCValAssign, 16> RVLocs1;
3296 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3297 DAG.getTarget(), RVLocs1, *DAG.getContext());
3298 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3300 SmallVector<CCValAssign, 16> RVLocs2;
3301 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3302 DAG.getTarget(), RVLocs2, *DAG.getContext());
3303 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3305 if (RVLocs1.size() != RVLocs2.size())
3307 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3308 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3310 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3312 if (RVLocs1[i].isRegLoc()) {
3313 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3316 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3322 // If the callee takes no arguments then go on to check the results of the
3324 if (!Outs.empty()) {
3325 // Check if stack adjustment is needed. For now, do not do this if any
3326 // argument is passed on the stack.
3327 SmallVector<CCValAssign, 16> ArgLocs;
3328 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3329 DAG.getTarget(), ArgLocs, *DAG.getContext());
3331 // Allocate shadow area for Win64
3333 CCInfo.AllocateStack(32, 8);
3335 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3336 if (CCInfo.getNextStackOffset()) {
3337 MachineFunction &MF = DAG.getMachineFunction();
3338 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3341 // Check if the arguments are already laid out in the right way as
3342 // the caller's fixed stack objects.
3343 MachineFrameInfo *MFI = MF.getFrameInfo();
3344 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3345 const X86InstrInfo *TII =
3346 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3347 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3348 CCValAssign &VA = ArgLocs[i];
3349 SDValue Arg = OutVals[i];
3350 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3351 if (VA.getLocInfo() == CCValAssign::Indirect)
3353 if (!VA.isRegLoc()) {
3354 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3361 // If the tailcall address may be in a register, then make sure it's
3362 // possible to register allocate for it. In 32-bit, the call address can
3363 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3364 // callee-saved registers are restored. These happen to be the same
3365 // registers used to pass 'inreg' arguments so watch out for those.
3366 if (!Subtarget->is64Bit() &&
3367 ((!isa<GlobalAddressSDNode>(Callee) &&
3368 !isa<ExternalSymbolSDNode>(Callee)) ||
3369 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3370 unsigned NumInRegs = 0;
3371 // In PIC we need an extra register to formulate the address computation
3373 unsigned MaxInRegs =
3374 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3376 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3377 CCValAssign &VA = ArgLocs[i];
3380 unsigned Reg = VA.getLocReg();
3383 case X86::EAX: case X86::EDX: case X86::ECX:
3384 if (++NumInRegs == MaxInRegs)
3396 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3397 const TargetLibraryInfo *libInfo) const {
3398 return X86::createFastISel(funcInfo, libInfo);
3401 //===----------------------------------------------------------------------===//
3402 // Other Lowering Hooks
3403 //===----------------------------------------------------------------------===//
3405 static bool MayFoldLoad(SDValue Op) {
3406 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3409 static bool MayFoldIntoStore(SDValue Op) {
3410 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3413 static bool isTargetShuffle(unsigned Opcode) {
3415 default: return false;
3416 case X86ISD::PSHUFD:
3417 case X86ISD::PSHUFHW:
3418 case X86ISD::PSHUFLW:
3420 case X86ISD::PALIGNR:
3421 case X86ISD::MOVLHPS:
3422 case X86ISD::MOVLHPD:
3423 case X86ISD::MOVHLPS:
3424 case X86ISD::MOVLPS:
3425 case X86ISD::MOVLPD:
3426 case X86ISD::MOVSHDUP:
3427 case X86ISD::MOVSLDUP:
3428 case X86ISD::MOVDDUP:
3431 case X86ISD::UNPCKL:
3432 case X86ISD::UNPCKH:
3433 case X86ISD::VPERMILP:
3434 case X86ISD::VPERM2X128:
3435 case X86ISD::VPERMI:
3440 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3441 SDValue V1, SelectionDAG &DAG) {
3443 default: llvm_unreachable("Unknown x86 shuffle node");
3444 case X86ISD::MOVSHDUP:
3445 case X86ISD::MOVSLDUP:
3446 case X86ISD::MOVDDUP:
3447 return DAG.getNode(Opc, dl, VT, V1);
3451 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3452 SDValue V1, unsigned TargetMask,
3453 SelectionDAG &DAG) {
3455 default: llvm_unreachable("Unknown x86 shuffle node");
3456 case X86ISD::PSHUFD:
3457 case X86ISD::PSHUFHW:
3458 case X86ISD::PSHUFLW:
3459 case X86ISD::VPERMILP:
3460 case X86ISD::VPERMI:
3461 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3465 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3466 SDValue V1, SDValue V2, unsigned TargetMask,
3467 SelectionDAG &DAG) {
3469 default: llvm_unreachable("Unknown x86 shuffle node");
3470 case X86ISD::PALIGNR:
3472 case X86ISD::VPERM2X128:
3473 return DAG.getNode(Opc, dl, VT, V1, V2,
3474 DAG.getConstant(TargetMask, MVT::i8));
3478 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3479 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3481 default: llvm_unreachable("Unknown x86 shuffle node");
3482 case X86ISD::MOVLHPS:
3483 case X86ISD::MOVLHPD:
3484 case X86ISD::MOVHLPS:
3485 case X86ISD::MOVLPS:
3486 case X86ISD::MOVLPD:
3489 case X86ISD::UNPCKL:
3490 case X86ISD::UNPCKH:
3491 return DAG.getNode(Opc, dl, VT, V1, V2);
3495 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3496 MachineFunction &MF = DAG.getMachineFunction();
3497 const X86RegisterInfo *RegInfo =
3498 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3499 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3500 int ReturnAddrIndex = FuncInfo->getRAIndex();
3502 if (ReturnAddrIndex == 0) {
3503 // Set up a frame object for the return address.
3504 unsigned SlotSize = RegInfo->getSlotSize();
3505 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3508 FuncInfo->setRAIndex(ReturnAddrIndex);
3511 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3514 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3515 bool hasSymbolicDisplacement) {
3516 // Offset should fit into 32 bit immediate field.
3517 if (!isInt<32>(Offset))
3520 // If we don't have a symbolic displacement - we don't have any extra
3522 if (!hasSymbolicDisplacement)
3525 // FIXME: Some tweaks might be needed for medium code model.
3526 if (M != CodeModel::Small && M != CodeModel::Kernel)
3529 // For small code model we assume that latest object is 16MB before end of 31
3530 // bits boundary. We may also accept pretty large negative constants knowing
3531 // that all objects are in the positive half of address space.
3532 if (M == CodeModel::Small && Offset < 16*1024*1024)
3535 // For kernel code model we know that all object resist in the negative half
3536 // of 32bits address space. We may not accept negative offsets, since they may
3537 // be just off and we may accept pretty large positive ones.
3538 if (M == CodeModel::Kernel && Offset > 0)
3544 /// isCalleePop - Determines whether the callee is required to pop its
3545 /// own arguments. Callee pop is necessary to support tail calls.
3546 bool X86::isCalleePop(CallingConv::ID CallingConv,
3547 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3551 switch (CallingConv) {
3554 case CallingConv::X86_StdCall:
3556 case CallingConv::X86_FastCall:
3558 case CallingConv::X86_ThisCall:
3560 case CallingConv::Fast:
3562 case CallingConv::GHC:
3564 case CallingConv::HiPE:
3569 /// \brief Return true if the condition is an unsigned comparison operation.
3570 static bool isX86CCUnsigned(unsigned X86CC) {
3572 default: llvm_unreachable("Invalid integer condition!");
3573 case X86::COND_E: return true;
3574 case X86::COND_G: return false;
3575 case X86::COND_GE: return false;
3576 case X86::COND_L: return false;
3577 case X86::COND_LE: return false;
3578 case X86::COND_NE: return true;
3579 case X86::COND_B: return true;
3580 case X86::COND_A: return true;
3581 case X86::COND_BE: return true;
3582 case X86::COND_AE: return true;
3584 llvm_unreachable("covered switch fell through?!");
3587 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3588 /// specific condition code, returning the condition code and the LHS/RHS of the
3589 /// comparison to make.
3590 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3591 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3593 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3594 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3595 // X > -1 -> X == 0, jump !sign.
3596 RHS = DAG.getConstant(0, RHS.getValueType());
3597 return X86::COND_NS;
3599 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3600 // X < 0 -> X == 0, jump on sign.
3603 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3605 RHS = DAG.getConstant(0, RHS.getValueType());
3606 return X86::COND_LE;
3610 switch (SetCCOpcode) {
3611 default: llvm_unreachable("Invalid integer condition!");
3612 case ISD::SETEQ: return X86::COND_E;
3613 case ISD::SETGT: return X86::COND_G;
3614 case ISD::SETGE: return X86::COND_GE;
3615 case ISD::SETLT: return X86::COND_L;
3616 case ISD::SETLE: return X86::COND_LE;
3617 case ISD::SETNE: return X86::COND_NE;
3618 case ISD::SETULT: return X86::COND_B;
3619 case ISD::SETUGT: return X86::COND_A;
3620 case ISD::SETULE: return X86::COND_BE;
3621 case ISD::SETUGE: return X86::COND_AE;
3625 // First determine if it is required or is profitable to flip the operands.
3627 // If LHS is a foldable load, but RHS is not, flip the condition.
3628 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3629 !ISD::isNON_EXTLoad(RHS.getNode())) {
3630 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3631 std::swap(LHS, RHS);
3634 switch (SetCCOpcode) {
3640 std::swap(LHS, RHS);
3644 // On a floating point condition, the flags are set as follows:
3646 // 0 | 0 | 0 | X > Y
3647 // 0 | 0 | 1 | X < Y
3648 // 1 | 0 | 0 | X == Y
3649 // 1 | 1 | 1 | unordered
3650 switch (SetCCOpcode) {
3651 default: llvm_unreachable("Condcode should be pre-legalized away");
3653 case ISD::SETEQ: return X86::COND_E;
3654 case ISD::SETOLT: // flipped
3656 case ISD::SETGT: return X86::COND_A;
3657 case ISD::SETOLE: // flipped
3659 case ISD::SETGE: return X86::COND_AE;
3660 case ISD::SETUGT: // flipped
3662 case ISD::SETLT: return X86::COND_B;
3663 case ISD::SETUGE: // flipped
3665 case ISD::SETLE: return X86::COND_BE;
3667 case ISD::SETNE: return X86::COND_NE;
3668 case ISD::SETUO: return X86::COND_P;
3669 case ISD::SETO: return X86::COND_NP;
3671 case ISD::SETUNE: return X86::COND_INVALID;
3675 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3676 /// code. Current x86 isa includes the following FP cmov instructions:
3677 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3678 static bool hasFPCMov(unsigned X86CC) {
3694 /// isFPImmLegal - Returns true if the target can instruction select the
3695 /// specified FP immediate natively. If false, the legalizer will
3696 /// materialize the FP immediate as a load from a constant pool.
3697 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3698 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3699 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3705 /// \brief Returns true if it is beneficial to convert a load of a constant
3706 /// to just the constant itself.
3707 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3709 assert(Ty->isIntegerTy());
3711 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3712 if (BitSize == 0 || BitSize > 64)
3717 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3718 /// the specified range (L, H].
3719 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3720 return (Val < 0) || (Val >= Low && Val < Hi);
3723 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3724 /// specified value.
3725 static bool isUndefOrEqual(int Val, int CmpVal) {
3726 return (Val < 0 || Val == CmpVal);
3729 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3730 /// from position Pos and ending in Pos+Size, falls within the specified
3731 /// sequential range (L, L+Pos]. or is undef.
3732 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3733 unsigned Pos, unsigned Size, int Low) {
3734 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3735 if (!isUndefOrEqual(Mask[i], Low))
3740 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3741 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3742 /// the second operand.
3743 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3744 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3745 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3746 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3747 return (Mask[0] < 2 && Mask[1] < 2);
3751 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3752 /// is suitable for input to PSHUFHW.
3753 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3754 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3757 // Lower quadword copied in order or undef.
3758 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3761 // Upper quadword shuffled.
3762 for (unsigned i = 4; i != 8; ++i)
3763 if (!isUndefOrInRange(Mask[i], 4, 8))
3766 if (VT == MVT::v16i16) {
3767 // Lower quadword copied in order or undef.
3768 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3771 // Upper quadword shuffled.
3772 for (unsigned i = 12; i != 16; ++i)
3773 if (!isUndefOrInRange(Mask[i], 12, 16))
3780 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3781 /// is suitable for input to PSHUFLW.
3782 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3783 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3786 // Upper quadword copied in order.
3787 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3790 // Lower quadword shuffled.
3791 for (unsigned i = 0; i != 4; ++i)
3792 if (!isUndefOrInRange(Mask[i], 0, 4))
3795 if (VT == MVT::v16i16) {
3796 // Upper quadword copied in order.
3797 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3800 // Lower quadword shuffled.
3801 for (unsigned i = 8; i != 12; ++i)
3802 if (!isUndefOrInRange(Mask[i], 8, 12))
3809 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3810 /// is suitable for input to PALIGNR.
3811 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3812 const X86Subtarget *Subtarget) {
3813 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3814 (VT.is256BitVector() && !Subtarget->hasInt256()))
3817 unsigned NumElts = VT.getVectorNumElements();
3818 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3819 unsigned NumLaneElts = NumElts/NumLanes;
3821 // Do not handle 64-bit element shuffles with palignr.
3822 if (NumLaneElts == 2)
3825 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3827 for (i = 0; i != NumLaneElts; ++i) {
3832 // Lane is all undef, go to next lane
3833 if (i == NumLaneElts)
3836 int Start = Mask[i+l];
3838 // Make sure its in this lane in one of the sources
3839 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3840 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3843 // If not lane 0, then we must match lane 0
3844 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3847 // Correct second source to be contiguous with first source
3848 if (Start >= (int)NumElts)
3849 Start -= NumElts - NumLaneElts;
3851 // Make sure we're shifting in the right direction.
3852 if (Start <= (int)(i+l))
3857 // Check the rest of the elements to see if they are consecutive.
3858 for (++i; i != NumLaneElts; ++i) {
3859 int Idx = Mask[i+l];
3861 // Make sure its in this lane
3862 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3863 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3866 // If not lane 0, then we must match lane 0
3867 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3870 if (Idx >= (int)NumElts)
3871 Idx -= NumElts - NumLaneElts;
3873 if (!isUndefOrEqual(Idx, Start+i))
3882 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3883 /// the two vector operands have swapped position.
3884 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3885 unsigned NumElems) {
3886 for (unsigned i = 0; i != NumElems; ++i) {
3890 else if (idx < (int)NumElems)
3891 Mask[i] = idx + NumElems;
3893 Mask[i] = idx - NumElems;
3897 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3898 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3899 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3900 /// reverse of what x86 shuffles want.
3901 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3903 unsigned NumElems = VT.getVectorNumElements();
3904 unsigned NumLanes = VT.getSizeInBits()/128;
3905 unsigned NumLaneElems = NumElems/NumLanes;
3907 if (NumLaneElems != 2 && NumLaneElems != 4)
3910 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3911 bool symetricMaskRequired =
3912 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3914 // VSHUFPSY divides the resulting vector into 4 chunks.
3915 // The sources are also splitted into 4 chunks, and each destination
3916 // chunk must come from a different source chunk.
3918 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3919 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3921 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3922 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3924 // VSHUFPDY divides the resulting vector into 4 chunks.
3925 // The sources are also splitted into 4 chunks, and each destination
3926 // chunk must come from a different source chunk.
3928 // SRC1 => X3 X2 X1 X0
3929 // SRC2 => Y3 Y2 Y1 Y0
3931 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3933 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3934 unsigned HalfLaneElems = NumLaneElems/2;
3935 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3936 for (unsigned i = 0; i != NumLaneElems; ++i) {
3937 int Idx = Mask[i+l];
3938 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3939 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3941 // For VSHUFPSY, the mask of the second half must be the same as the
3942 // first but with the appropriate offsets. This works in the same way as
3943 // VPERMILPS works with masks.
3944 if (!symetricMaskRequired || Idx < 0)
3946 if (MaskVal[i] < 0) {
3947 MaskVal[i] = Idx - l;
3950 if ((signed)(Idx - l) != MaskVal[i])
3958 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3959 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3960 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3961 if (!VT.is128BitVector())
3964 unsigned NumElems = VT.getVectorNumElements();
3969 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3970 return isUndefOrEqual(Mask[0], 6) &&
3971 isUndefOrEqual(Mask[1], 7) &&
3972 isUndefOrEqual(Mask[2], 2) &&
3973 isUndefOrEqual(Mask[3], 3);
3976 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3977 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3979 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3980 if (!VT.is128BitVector())
3983 unsigned NumElems = VT.getVectorNumElements();
3988 return isUndefOrEqual(Mask[0], 2) &&
3989 isUndefOrEqual(Mask[1], 3) &&
3990 isUndefOrEqual(Mask[2], 2) &&
3991 isUndefOrEqual(Mask[3], 3);
3994 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3995 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3996 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3997 if (!VT.is128BitVector())
4000 unsigned NumElems = VT.getVectorNumElements();
4002 if (NumElems != 2 && NumElems != 4)
4005 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4006 if (!isUndefOrEqual(Mask[i], i + NumElems))
4009 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4010 if (!isUndefOrEqual(Mask[i], i))
4016 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4017 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4018 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4019 if (!VT.is128BitVector())
4022 unsigned NumElems = VT.getVectorNumElements();
4024 if (NumElems != 2 && NumElems != 4)
4027 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4028 if (!isUndefOrEqual(Mask[i], i))
4031 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4032 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4038 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4039 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4040 /// i. e: If all but one element come from the same vector.
4041 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4042 // TODO: Deal with AVX's VINSERTPS
4043 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4046 unsigned CorrectPosV1 = 0;
4047 unsigned CorrectPosV2 = 0;
4048 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4049 if (Mask[i] == -1) {
4057 else if (Mask[i] == i + 4)
4061 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4062 // We have 3 elements (undefs count as elements from any vector) from one
4063 // vector, and one from another.
4070 // Some special combinations that can be optimized.
4073 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4074 SelectionDAG &DAG) {
4075 MVT VT = SVOp->getSimpleValueType(0);
4078 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4081 ArrayRef<int> Mask = SVOp->getMask();
4083 // These are the special masks that may be optimized.
4084 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4085 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4086 bool MatchEvenMask = true;
4087 bool MatchOddMask = true;
4088 for (int i=0; i<8; ++i) {
4089 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4090 MatchEvenMask = false;
4091 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4092 MatchOddMask = false;
4095 if (!MatchEvenMask && !MatchOddMask)
4098 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4100 SDValue Op0 = SVOp->getOperand(0);
4101 SDValue Op1 = SVOp->getOperand(1);
4103 if (MatchEvenMask) {
4104 // Shift the second operand right to 32 bits.
4105 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4106 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4108 // Shift the first operand left to 32 bits.
4109 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4110 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4112 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4113 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4116 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4117 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4118 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4119 bool HasInt256, bool V2IsSplat = false) {
4121 assert(VT.getSizeInBits() >= 128 &&
4122 "Unsupported vector type for unpckl");
4124 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4126 unsigned NumOf256BitLanes;
4127 unsigned NumElts = VT.getVectorNumElements();
4128 if (VT.is256BitVector()) {
4129 if (NumElts != 4 && NumElts != 8 &&
4130 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4133 NumOf256BitLanes = 1;
4134 } else if (VT.is512BitVector()) {
4135 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4136 "Unsupported vector type for unpckh");
4138 NumOf256BitLanes = 2;
4141 NumOf256BitLanes = 1;
4144 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4145 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4147 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4148 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4149 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4150 int BitI = Mask[l256*NumEltsInStride+l+i];
4151 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4152 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4154 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4156 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4164 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4165 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4166 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4167 bool HasInt256, bool V2IsSplat = false) {
4168 assert(VT.getSizeInBits() >= 128 &&
4169 "Unsupported vector type for unpckh");
4171 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4173 unsigned NumOf256BitLanes;
4174 unsigned NumElts = VT.getVectorNumElements();
4175 if (VT.is256BitVector()) {
4176 if (NumElts != 4 && NumElts != 8 &&
4177 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4180 NumOf256BitLanes = 1;
4181 } else if (VT.is512BitVector()) {
4182 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4183 "Unsupported vector type for unpckh");
4185 NumOf256BitLanes = 2;
4188 NumOf256BitLanes = 1;
4191 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4192 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4194 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4195 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4196 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4197 int BitI = Mask[l256*NumEltsInStride+l+i];
4198 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4199 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4201 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4203 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4211 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4212 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4214 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4215 unsigned NumElts = VT.getVectorNumElements();
4216 bool Is256BitVec = VT.is256BitVector();
4218 if (VT.is512BitVector())
4220 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4221 "Unsupported vector type for unpckh");
4223 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4224 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4227 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4228 // FIXME: Need a better way to get rid of this, there's no latency difference
4229 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4230 // the former later. We should also remove the "_undef" special mask.
4231 if (NumElts == 4 && Is256BitVec)
4234 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4235 // independently on 128-bit lanes.
4236 unsigned NumLanes = VT.getSizeInBits()/128;
4237 unsigned NumLaneElts = NumElts/NumLanes;
4239 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4240 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4241 int BitI = Mask[l+i];
4242 int BitI1 = Mask[l+i+1];
4244 if (!isUndefOrEqual(BitI, j))
4246 if (!isUndefOrEqual(BitI1, j))
4254 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4255 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4257 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4258 unsigned NumElts = VT.getVectorNumElements();
4260 if (VT.is512BitVector())
4263 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4264 "Unsupported vector type for unpckh");
4266 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4267 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4270 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4271 // independently on 128-bit lanes.
4272 unsigned NumLanes = VT.getSizeInBits()/128;
4273 unsigned NumLaneElts = NumElts/NumLanes;
4275 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4276 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4277 int BitI = Mask[l+i];
4278 int BitI1 = Mask[l+i+1];
4279 if (!isUndefOrEqual(BitI, j))
4281 if (!isUndefOrEqual(BitI1, j))
4288 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4289 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4290 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4291 if (!VT.is512BitVector())
4294 unsigned NumElts = VT.getVectorNumElements();
4295 unsigned HalfSize = NumElts/2;
4296 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4297 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4302 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4303 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4311 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4312 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4313 /// MOVSD, and MOVD, i.e. setting the lowest element.
4314 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4315 if (VT.getVectorElementType().getSizeInBits() < 32)
4317 if (!VT.is128BitVector())
4320 unsigned NumElts = VT.getVectorNumElements();
4322 if (!isUndefOrEqual(Mask[0], NumElts))
4325 for (unsigned i = 1; i != NumElts; ++i)
4326 if (!isUndefOrEqual(Mask[i], i))
4332 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4333 /// as permutations between 128-bit chunks or halves. As an example: this
4335 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4336 /// The first half comes from the second half of V1 and the second half from the
4337 /// the second half of V2.
4338 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4339 if (!HasFp256 || !VT.is256BitVector())
4342 // The shuffle result is divided into half A and half B. In total the two
4343 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4344 // B must come from C, D, E or F.
4345 unsigned HalfSize = VT.getVectorNumElements()/2;
4346 bool MatchA = false, MatchB = false;
4348 // Check if A comes from one of C, D, E, F.
4349 for (unsigned Half = 0; Half != 4; ++Half) {
4350 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4356 // Check if B comes from one of C, D, E, F.
4357 for (unsigned Half = 0; Half != 4; ++Half) {
4358 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4364 return MatchA && MatchB;
4367 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4368 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4369 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4370 MVT VT = SVOp->getSimpleValueType(0);
4372 unsigned HalfSize = VT.getVectorNumElements()/2;
4374 unsigned FstHalf = 0, SndHalf = 0;
4375 for (unsigned i = 0; i < HalfSize; ++i) {
4376 if (SVOp->getMaskElt(i) > 0) {
4377 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4381 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4382 if (SVOp->getMaskElt(i) > 0) {
4383 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4388 return (FstHalf | (SndHalf << 4));
4391 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4392 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4393 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4397 unsigned NumElts = VT.getVectorNumElements();
4399 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4400 for (unsigned i = 0; i != NumElts; ++i) {
4403 Imm8 |= Mask[i] << (i*2);
4408 unsigned LaneSize = 4;
4409 SmallVector<int, 4> MaskVal(LaneSize, -1);
4411 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4412 for (unsigned i = 0; i != LaneSize; ++i) {
4413 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4417 if (MaskVal[i] < 0) {
4418 MaskVal[i] = Mask[i+l] - l;
4419 Imm8 |= MaskVal[i] << (i*2);
4422 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4429 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4430 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4431 /// Note that VPERMIL mask matching is different depending whether theunderlying
4432 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4433 /// to the same elements of the low, but to the higher half of the source.
4434 /// In VPERMILPD the two lanes could be shuffled independently of each other
4435 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4436 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4437 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4438 if (VT.getSizeInBits() < 256 || EltSize < 32)
4440 bool symetricMaskRequired = (EltSize == 32);
4441 unsigned NumElts = VT.getVectorNumElements();
4443 unsigned NumLanes = VT.getSizeInBits()/128;
4444 unsigned LaneSize = NumElts/NumLanes;
4445 // 2 or 4 elements in one lane
4447 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4448 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4449 for (unsigned i = 0; i != LaneSize; ++i) {
4450 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4452 if (symetricMaskRequired) {
4453 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4454 ExpectedMaskVal[i] = Mask[i+l] - l;
4457 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4465 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4466 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4467 /// element of vector 2 and the other elements to come from vector 1 in order.
4468 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4469 bool V2IsSplat = false, bool V2IsUndef = false) {
4470 if (!VT.is128BitVector())
4473 unsigned NumOps = VT.getVectorNumElements();
4474 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4477 if (!isUndefOrEqual(Mask[0], 0))
4480 for (unsigned i = 1; i != NumOps; ++i)
4481 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4482 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4483 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4489 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4490 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4491 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4492 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4493 const X86Subtarget *Subtarget) {
4494 if (!Subtarget->hasSSE3())
4497 unsigned NumElems = VT.getVectorNumElements();
4499 if ((VT.is128BitVector() && NumElems != 4) ||
4500 (VT.is256BitVector() && NumElems != 8) ||
4501 (VT.is512BitVector() && NumElems != 16))
4504 // "i+1" is the value the indexed mask element must have
4505 for (unsigned i = 0; i != NumElems; i += 2)
4506 if (!isUndefOrEqual(Mask[i], i+1) ||
4507 !isUndefOrEqual(Mask[i+1], i+1))
4513 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4514 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4515 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4516 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4517 const X86Subtarget *Subtarget) {
4518 if (!Subtarget->hasSSE3())
4521 unsigned NumElems = VT.getVectorNumElements();
4523 if ((VT.is128BitVector() && NumElems != 4) ||
4524 (VT.is256BitVector() && NumElems != 8) ||
4525 (VT.is512BitVector() && NumElems != 16))
4528 // "i" is the value the indexed mask element must have
4529 for (unsigned i = 0; i != NumElems; i += 2)
4530 if (!isUndefOrEqual(Mask[i], i) ||
4531 !isUndefOrEqual(Mask[i+1], i))
4537 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4538 /// specifies a shuffle of elements that is suitable for input to 256-bit
4539 /// version of MOVDDUP.
4540 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4541 if (!HasFp256 || !VT.is256BitVector())
4544 unsigned NumElts = VT.getVectorNumElements();
4548 for (unsigned i = 0; i != NumElts/2; ++i)
4549 if (!isUndefOrEqual(Mask[i], 0))
4551 for (unsigned i = NumElts/2; i != NumElts; ++i)
4552 if (!isUndefOrEqual(Mask[i], NumElts/2))
4557 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4558 /// specifies a shuffle of elements that is suitable for input to 128-bit
4559 /// version of MOVDDUP.
4560 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4561 if (!VT.is128BitVector())
4564 unsigned e = VT.getVectorNumElements() / 2;
4565 for (unsigned i = 0; i != e; ++i)
4566 if (!isUndefOrEqual(Mask[i], i))
4568 for (unsigned i = 0; i != e; ++i)
4569 if (!isUndefOrEqual(Mask[e+i], i))
4574 /// isVEXTRACTIndex - Return true if the specified
4575 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4576 /// suitable for instruction that extract 128 or 256 bit vectors
4577 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4578 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4579 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4582 // The index should be aligned on a vecWidth-bit boundary.
4584 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4586 MVT VT = N->getSimpleValueType(0);
4587 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4588 bool Result = (Index * ElSize) % vecWidth == 0;
4593 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4594 /// operand specifies a subvector insert that is suitable for input to
4595 /// insertion of 128 or 256-bit subvectors
4596 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4597 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4598 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4600 // The index should be aligned on a vecWidth-bit boundary.
4602 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4604 MVT VT = N->getSimpleValueType(0);
4605 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4606 bool Result = (Index * ElSize) % vecWidth == 0;
4611 bool X86::isVINSERT128Index(SDNode *N) {
4612 return isVINSERTIndex(N, 128);
4615 bool X86::isVINSERT256Index(SDNode *N) {
4616 return isVINSERTIndex(N, 256);
4619 bool X86::isVEXTRACT128Index(SDNode *N) {
4620 return isVEXTRACTIndex(N, 128);
4623 bool X86::isVEXTRACT256Index(SDNode *N) {
4624 return isVEXTRACTIndex(N, 256);
4627 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4628 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4629 /// Handles 128-bit and 256-bit.
4630 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4631 MVT VT = N->getSimpleValueType(0);
4633 assert((VT.getSizeInBits() >= 128) &&
4634 "Unsupported vector type for PSHUF/SHUFP");
4636 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4637 // independently on 128-bit lanes.
4638 unsigned NumElts = VT.getVectorNumElements();
4639 unsigned NumLanes = VT.getSizeInBits()/128;
4640 unsigned NumLaneElts = NumElts/NumLanes;
4642 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4643 "Only supports 2, 4 or 8 elements per lane");
4645 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4647 for (unsigned i = 0; i != NumElts; ++i) {
4648 int Elt = N->getMaskElt(i);
4649 if (Elt < 0) continue;
4650 Elt &= NumLaneElts - 1;
4651 unsigned ShAmt = (i << Shift) % 8;
4652 Mask |= Elt << ShAmt;
4658 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4659 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4660 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4661 MVT VT = N->getSimpleValueType(0);
4663 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4664 "Unsupported vector type for PSHUFHW");
4666 unsigned NumElts = VT.getVectorNumElements();
4669 for (unsigned l = 0; l != NumElts; l += 8) {
4670 // 8 nodes per lane, but we only care about the last 4.
4671 for (unsigned i = 0; i < 4; ++i) {
4672 int Elt = N->getMaskElt(l+i+4);
4673 if (Elt < 0) continue;
4674 Elt &= 0x3; // only 2-bits.
4675 Mask |= Elt << (i * 2);
4682 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4683 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4684 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4685 MVT VT = N->getSimpleValueType(0);
4687 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4688 "Unsupported vector type for PSHUFHW");
4690 unsigned NumElts = VT.getVectorNumElements();
4693 for (unsigned l = 0; l != NumElts; l += 8) {
4694 // 8 nodes per lane, but we only care about the first 4.
4695 for (unsigned i = 0; i < 4; ++i) {
4696 int Elt = N->getMaskElt(l+i);
4697 if (Elt < 0) continue;
4698 Elt &= 0x3; // only 2-bits
4699 Mask |= Elt << (i * 2);
4706 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4707 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4708 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4709 MVT VT = SVOp->getSimpleValueType(0);
4710 unsigned EltSize = VT.is512BitVector() ? 1 :
4711 VT.getVectorElementType().getSizeInBits() >> 3;
4713 unsigned NumElts = VT.getVectorNumElements();
4714 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4715 unsigned NumLaneElts = NumElts/NumLanes;
4719 for (i = 0; i != NumElts; ++i) {
4720 Val = SVOp->getMaskElt(i);
4724 if (Val >= (int)NumElts)
4725 Val -= NumElts - NumLaneElts;
4727 assert(Val - i > 0 && "PALIGNR imm should be positive");
4728 return (Val - i) * EltSize;
4731 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4732 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4733 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4734 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4737 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4739 MVT VecVT = N->getOperand(0).getSimpleValueType();
4740 MVT ElVT = VecVT.getVectorElementType();
4742 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4743 return Index / NumElemsPerChunk;
4746 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4747 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4748 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4749 llvm_unreachable("Illegal insert subvector for VINSERT");
4752 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4754 MVT VecVT = N->getSimpleValueType(0);
4755 MVT ElVT = VecVT.getVectorElementType();
4757 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4758 return Index / NumElemsPerChunk;
4761 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4762 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4763 /// and VINSERTI128 instructions.
4764 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4765 return getExtractVEXTRACTImmediate(N, 128);
4768 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4769 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4770 /// and VINSERTI64x4 instructions.
4771 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4772 return getExtractVEXTRACTImmediate(N, 256);
4775 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4776 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4777 /// and VINSERTI128 instructions.
4778 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4779 return getInsertVINSERTImmediate(N, 128);
4782 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4783 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4784 /// and VINSERTI64x4 instructions.
4785 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4786 return getInsertVINSERTImmediate(N, 256);
4789 /// isZero - Returns true if Elt is a constant integer zero
4790 static bool isZero(SDValue V) {
4791 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4792 return C && C->isNullValue();
4795 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4797 bool X86::isZeroNode(SDValue Elt) {
4800 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4801 return CFP->getValueAPF().isPosZero();
4805 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4806 /// match movhlps. The lower half elements should come from upper half of
4807 /// V1 (and in order), and the upper half elements should come from the upper
4808 /// half of V2 (and in order).
4809 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4810 if (!VT.is128BitVector())
4812 if (VT.getVectorNumElements() != 4)
4814 for (unsigned i = 0, e = 2; i != e; ++i)
4815 if (!isUndefOrEqual(Mask[i], i+2))
4817 for (unsigned i = 2; i != 4; ++i)
4818 if (!isUndefOrEqual(Mask[i], i+4))
4823 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4824 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4826 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4827 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4829 N = N->getOperand(0).getNode();
4830 if (!ISD::isNON_EXTLoad(N))
4833 *LD = cast<LoadSDNode>(N);
4837 // Test whether the given value is a vector value which will be legalized
4839 static bool WillBeConstantPoolLoad(SDNode *N) {
4840 if (N->getOpcode() != ISD::BUILD_VECTOR)
4843 // Check for any non-constant elements.
4844 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4845 switch (N->getOperand(i).getNode()->getOpcode()) {
4847 case ISD::ConstantFP:
4854 // Vectors of all-zeros and all-ones are materialized with special
4855 // instructions rather than being loaded.
4856 return !ISD::isBuildVectorAllZeros(N) &&
4857 !ISD::isBuildVectorAllOnes(N);
4860 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4861 /// match movlp{s|d}. The lower half elements should come from lower half of
4862 /// V1 (and in order), and the upper half elements should come from the upper
4863 /// half of V2 (and in order). And since V1 will become the source of the
4864 /// MOVLP, it must be either a vector load or a scalar load to vector.
4865 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4866 ArrayRef<int> Mask, MVT VT) {
4867 if (!VT.is128BitVector())
4870 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4872 // Is V2 is a vector load, don't do this transformation. We will try to use
4873 // load folding shufps op.
4874 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4877 unsigned NumElems = VT.getVectorNumElements();
4879 if (NumElems != 2 && NumElems != 4)
4881 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4882 if (!isUndefOrEqual(Mask[i], i))
4884 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4885 if (!isUndefOrEqual(Mask[i], i+NumElems))
4890 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4891 /// to an zero vector.
4892 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4893 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4894 SDValue V1 = N->getOperand(0);
4895 SDValue V2 = N->getOperand(1);
4896 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4897 for (unsigned i = 0; i != NumElems; ++i) {
4898 int Idx = N->getMaskElt(i);
4899 if (Idx >= (int)NumElems) {
4900 unsigned Opc = V2.getOpcode();
4901 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4903 if (Opc != ISD::BUILD_VECTOR ||
4904 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4906 } else if (Idx >= 0) {
4907 unsigned Opc = V1.getOpcode();
4908 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4910 if (Opc != ISD::BUILD_VECTOR ||
4911 !X86::isZeroNode(V1.getOperand(Idx)))
4918 /// getZeroVector - Returns a vector of specified type with all zero elements.
4920 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4921 SelectionDAG &DAG, SDLoc dl) {
4922 assert(VT.isVector() && "Expected a vector type");
4924 // Always build SSE zero vectors as <4 x i32> bitcasted
4925 // to their dest type. This ensures they get CSE'd.
4927 if (VT.is128BitVector()) { // SSE
4928 if (Subtarget->hasSSE2()) { // SSE2
4929 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4930 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4932 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4933 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4935 } else if (VT.is256BitVector()) { // AVX
4936 if (Subtarget->hasInt256()) { // AVX2
4937 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4938 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4939 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4941 // 256-bit logic and arithmetic instructions in AVX are all
4942 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4943 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4944 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4945 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4947 } else if (VT.is512BitVector()) { // AVX-512
4948 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4949 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4950 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4951 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4952 } else if (VT.getScalarType() == MVT::i1) {
4953 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4954 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4955 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4956 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4958 llvm_unreachable("Unexpected vector type");
4960 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4963 /// getOnesVector - Returns a vector of specified type with all bits set.
4964 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4965 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4966 /// Then bitcast to their original type, ensuring they get CSE'd.
4967 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4969 assert(VT.isVector() && "Expected a vector type");
4971 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4973 if (VT.is256BitVector()) {
4974 if (HasInt256) { // AVX2
4975 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4976 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4978 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4979 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4981 } else if (VT.is128BitVector()) {
4982 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4984 llvm_unreachable("Unexpected vector type");
4986 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4989 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4990 /// that point to V2 points to its first element.
4991 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4992 for (unsigned i = 0; i != NumElems; ++i) {
4993 if (Mask[i] > (int)NumElems) {
4999 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5000 /// operation of specified width.
5001 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5003 unsigned NumElems = VT.getVectorNumElements();
5004 SmallVector<int, 8> Mask;
5005 Mask.push_back(NumElems);
5006 for (unsigned i = 1; i != NumElems; ++i)
5008 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5011 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5012 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5014 unsigned NumElems = VT.getVectorNumElements();
5015 SmallVector<int, 8> Mask;
5016 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5018 Mask.push_back(i + NumElems);
5020 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5023 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5024 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5026 unsigned NumElems = VT.getVectorNumElements();
5027 SmallVector<int, 8> Mask;
5028 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5029 Mask.push_back(i + Half);
5030 Mask.push_back(i + NumElems + Half);
5032 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5035 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5036 // a generic shuffle instruction because the target has no such instructions.
5037 // Generate shuffles which repeat i16 and i8 several times until they can be
5038 // represented by v4f32 and then be manipulated by target suported shuffles.
5039 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5040 MVT VT = V.getSimpleValueType();
5041 int NumElems = VT.getVectorNumElements();
5044 while (NumElems > 4) {
5045 if (EltNo < NumElems/2) {
5046 V = getUnpackl(DAG, dl, VT, V, V);
5048 V = getUnpackh(DAG, dl, VT, V, V);
5049 EltNo -= NumElems/2;
5056 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5057 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5058 MVT VT = V.getSimpleValueType();
5061 if (VT.is128BitVector()) {
5062 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5063 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5064 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5066 } else if (VT.is256BitVector()) {
5067 // To use VPERMILPS to splat scalars, the second half of indicies must
5068 // refer to the higher part, which is a duplication of the lower one,
5069 // because VPERMILPS can only handle in-lane permutations.
5070 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5071 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5073 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5074 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5077 llvm_unreachable("Vector size not supported");
5079 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5082 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5083 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5084 MVT SrcVT = SV->getSimpleValueType(0);
5085 SDValue V1 = SV->getOperand(0);
5088 int EltNo = SV->getSplatIndex();
5089 int NumElems = SrcVT.getVectorNumElements();
5090 bool Is256BitVec = SrcVT.is256BitVector();
5092 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5093 "Unknown how to promote splat for type");
5095 // Extract the 128-bit part containing the splat element and update
5096 // the splat element index when it refers to the higher register.
5098 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5099 if (EltNo >= NumElems/2)
5100 EltNo -= NumElems/2;
5103 // All i16 and i8 vector types can't be used directly by a generic shuffle
5104 // instruction because the target has no such instruction. Generate shuffles
5105 // which repeat i16 and i8 several times until they fit in i32, and then can
5106 // be manipulated by target suported shuffles.
5107 MVT EltVT = SrcVT.getVectorElementType();
5108 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5109 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5111 // Recreate the 256-bit vector and place the same 128-bit vector
5112 // into the low and high part. This is necessary because we want
5113 // to use VPERM* to shuffle the vectors
5115 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5118 return getLegalSplat(DAG, V1, EltNo);
5121 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5122 /// vector of zero or undef vector. This produces a shuffle where the low
5123 /// element of V2 is swizzled into the zero/undef vector, landing at element
5124 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5125 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5127 const X86Subtarget *Subtarget,
5128 SelectionDAG &DAG) {
5129 MVT VT = V2.getSimpleValueType();
5131 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5132 unsigned NumElems = VT.getVectorNumElements();
5133 SmallVector<int, 16> MaskVec;
5134 for (unsigned i = 0; i != NumElems; ++i)
5135 // If this is the insertion idx, put the low elt of V2 here.
5136 MaskVec.push_back(i == Idx ? NumElems : i);
5137 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5140 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5141 /// target specific opcode. Returns true if the Mask could be calculated.
5142 /// Sets IsUnary to true if only uses one source.
5143 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5144 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5145 unsigned NumElems = VT.getVectorNumElements();
5149 switch(N->getOpcode()) {
5151 ImmN = N->getOperand(N->getNumOperands()-1);
5152 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154 case X86ISD::UNPCKH:
5155 DecodeUNPCKHMask(VT, Mask);
5157 case X86ISD::UNPCKL:
5158 DecodeUNPCKLMask(VT, Mask);
5160 case X86ISD::MOVHLPS:
5161 DecodeMOVHLPSMask(NumElems, Mask);
5163 case X86ISD::MOVLHPS:
5164 DecodeMOVLHPSMask(NumElems, Mask);
5166 case X86ISD::PALIGNR:
5167 ImmN = N->getOperand(N->getNumOperands()-1);
5168 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5170 case X86ISD::PSHUFD:
5171 case X86ISD::VPERMILP:
5172 ImmN = N->getOperand(N->getNumOperands()-1);
5173 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5176 case X86ISD::PSHUFHW:
5177 ImmN = N->getOperand(N->getNumOperands()-1);
5178 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5181 case X86ISD::PSHUFLW:
5182 ImmN = N->getOperand(N->getNumOperands()-1);
5183 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5186 case X86ISD::VPERMI:
5187 ImmN = N->getOperand(N->getNumOperands()-1);
5188 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5192 case X86ISD::MOVSD: {
5193 // The index 0 always comes from the first element of the second source,
5194 // this is why MOVSS and MOVSD are used in the first place. The other
5195 // elements come from the other positions of the first source vector
5196 Mask.push_back(NumElems);
5197 for (unsigned i = 1; i != NumElems; ++i) {
5202 case X86ISD::VPERM2X128:
5203 ImmN = N->getOperand(N->getNumOperands()-1);
5204 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5205 if (Mask.empty()) return false;
5207 case X86ISD::MOVDDUP:
5208 case X86ISD::MOVLHPD:
5209 case X86ISD::MOVLPD:
5210 case X86ISD::MOVLPS:
5211 case X86ISD::MOVSHDUP:
5212 case X86ISD::MOVSLDUP:
5213 // Not yet implemented
5215 default: llvm_unreachable("unknown target shuffle node");
5221 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5222 /// element of the result of the vector shuffle.
5223 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5226 return SDValue(); // Limit search depth.
5228 SDValue V = SDValue(N, 0);
5229 EVT VT = V.getValueType();
5230 unsigned Opcode = V.getOpcode();
5232 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5233 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5234 int Elt = SV->getMaskElt(Index);
5237 return DAG.getUNDEF(VT.getVectorElementType());
5239 unsigned NumElems = VT.getVectorNumElements();
5240 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5241 : SV->getOperand(1);
5242 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5245 // Recurse into target specific vector shuffles to find scalars.
5246 if (isTargetShuffle(Opcode)) {
5247 MVT ShufVT = V.getSimpleValueType();
5248 unsigned NumElems = ShufVT.getVectorNumElements();
5249 SmallVector<int, 16> ShuffleMask;
5252 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5255 int Elt = ShuffleMask[Index];
5257 return DAG.getUNDEF(ShufVT.getVectorElementType());
5259 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5261 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5265 // Actual nodes that may contain scalar elements
5266 if (Opcode == ISD::BITCAST) {
5267 V = V.getOperand(0);
5268 EVT SrcVT = V.getValueType();
5269 unsigned NumElems = VT.getVectorNumElements();
5271 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5275 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5276 return (Index == 0) ? V.getOperand(0)
5277 : DAG.getUNDEF(VT.getVectorElementType());
5279 if (V.getOpcode() == ISD::BUILD_VECTOR)
5280 return V.getOperand(Index);
5285 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5286 /// shuffle operation which come from a consecutively from a zero. The
5287 /// search can start in two different directions, from left or right.
5288 /// We count undefs as zeros until PreferredNum is reached.
5289 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5290 unsigned NumElems, bool ZerosFromLeft,
5292 unsigned PreferredNum = -1U) {
5293 unsigned NumZeros = 0;
5294 for (unsigned i = 0; i != NumElems; ++i) {
5295 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5296 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5300 if (X86::isZeroNode(Elt))
5302 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5303 NumZeros = std::min(NumZeros + 1, PreferredNum);
5311 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5312 /// correspond consecutively to elements from one of the vector operands,
5313 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5315 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5316 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5317 unsigned NumElems, unsigned &OpNum) {
5318 bool SeenV1 = false;
5319 bool SeenV2 = false;
5321 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5322 int Idx = SVOp->getMaskElt(i);
5323 // Ignore undef indicies
5327 if (Idx < (int)NumElems)
5332 // Only accept consecutive elements from the same vector
5333 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5337 OpNum = SeenV1 ? 0 : 1;
5341 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5342 /// logical left shift of a vector.
5343 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5344 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5346 SVOp->getSimpleValueType(0).getVectorNumElements();
5347 unsigned NumZeros = getNumOfConsecutiveZeros(
5348 SVOp, NumElems, false /* check zeros from right */, DAG,
5349 SVOp->getMaskElt(0));
5355 // Considering the elements in the mask that are not consecutive zeros,
5356 // check if they consecutively come from only one of the source vectors.
5358 // V1 = {X, A, B, C} 0
5360 // vector_shuffle V1, V2 <1, 2, 3, X>
5362 if (!isShuffleMaskConsecutive(SVOp,
5363 0, // Mask Start Index
5364 NumElems-NumZeros, // Mask End Index(exclusive)
5365 NumZeros, // Where to start looking in the src vector
5366 NumElems, // Number of elements in vector
5367 OpSrc)) // Which source operand ?
5372 ShVal = SVOp->getOperand(OpSrc);
5376 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5377 /// logical left shift of a vector.
5378 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5379 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5381 SVOp->getSimpleValueType(0).getVectorNumElements();
5382 unsigned NumZeros = getNumOfConsecutiveZeros(
5383 SVOp, NumElems, true /* check zeros from left */, DAG,
5384 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5390 // Considering the elements in the mask that are not consecutive zeros,
5391 // check if they consecutively come from only one of the source vectors.
5393 // 0 { A, B, X, X } = V2
5395 // vector_shuffle V1, V2 <X, X, 4, 5>
5397 if (!isShuffleMaskConsecutive(SVOp,
5398 NumZeros, // Mask Start Index
5399 NumElems, // Mask End Index(exclusive)
5400 0, // Where to start looking in the src vector
5401 NumElems, // Number of elements in vector
5402 OpSrc)) // Which source operand ?
5407 ShVal = SVOp->getOperand(OpSrc);
5411 /// isVectorShift - Returns true if the shuffle can be implemented as a
5412 /// logical left or right shift of a vector.
5413 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5414 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5415 // Although the logic below support any bitwidth size, there are no
5416 // shift instructions which handle more than 128-bit vectors.
5417 if (!SVOp->getSimpleValueType(0).is128BitVector())
5420 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5421 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5427 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5429 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5430 unsigned NumNonZero, unsigned NumZero,
5432 const X86Subtarget* Subtarget,
5433 const TargetLowering &TLI) {
5440 for (unsigned i = 0; i < 16; ++i) {
5441 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5442 if (ThisIsNonZero && First) {
5444 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5446 V = DAG.getUNDEF(MVT::v8i16);
5451 SDValue ThisElt, LastElt;
5452 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5453 if (LastIsNonZero) {
5454 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5455 MVT::i16, Op.getOperand(i-1));
5457 if (ThisIsNonZero) {
5458 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5459 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5460 ThisElt, DAG.getConstant(8, MVT::i8));
5462 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5466 if (ThisElt.getNode())
5467 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5468 DAG.getIntPtrConstant(i/2));
5472 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5475 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5477 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5478 unsigned NumNonZero, unsigned NumZero,
5480 const X86Subtarget* Subtarget,
5481 const TargetLowering &TLI) {
5488 for (unsigned i = 0; i < 8; ++i) {
5489 bool isNonZero = (NonZeros & (1 << i)) != 0;
5493 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5495 V = DAG.getUNDEF(MVT::v8i16);
5498 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5499 MVT::v8i16, V, Op.getOperand(i),
5500 DAG.getIntPtrConstant(i));
5507 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5508 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5509 unsigned NonZeros, unsigned NumNonZero,
5510 unsigned NumZero, SelectionDAG &DAG,
5511 const X86Subtarget *Subtarget,
5512 const TargetLowering &TLI) {
5513 // We know there's at least one non-zero element
5514 unsigned FirstNonZeroIdx = 0;
5515 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5516 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5517 X86::isZeroNode(FirstNonZero)) {
5519 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5522 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5523 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5526 SDValue V = FirstNonZero.getOperand(0);
5527 MVT VVT = V.getSimpleValueType();
5528 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5531 unsigned FirstNonZeroDst =
5532 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5533 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5534 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5535 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5537 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5538 SDValue Elem = Op.getOperand(Idx);
5539 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5542 // TODO: What else can be here? Deal with it.
5543 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5546 // TODO: Some optimizations are still possible here
5547 // ex: Getting one element from a vector, and the rest from another.
5548 if (Elem.getOperand(0) != V)
5551 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5554 else if (IncorrectIdx == -1U) {
5558 // There was already one element with an incorrect index.
5559 // We can't optimize this case to an insertps.
5563 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5565 EVT VT = Op.getSimpleValueType();
5566 unsigned ElementMoveMask = 0;
5567 if (IncorrectIdx == -1U)
5568 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5570 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5572 SDValue InsertpsMask =
5573 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5574 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5580 /// getVShift - Return a vector logical shift node.
5582 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5583 unsigned NumBits, SelectionDAG &DAG,
5584 const TargetLowering &TLI, SDLoc dl) {
5585 assert(VT.is128BitVector() && "Unknown type for VShift");
5586 EVT ShVT = MVT::v2i64;
5587 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5588 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5589 return DAG.getNode(ISD::BITCAST, dl, VT,
5590 DAG.getNode(Opc, dl, ShVT, SrcOp,
5591 DAG.getConstant(NumBits,
5592 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5596 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5598 // Check if the scalar load can be widened into a vector load. And if
5599 // the address is "base + cst" see if the cst can be "absorbed" into
5600 // the shuffle mask.
5601 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5602 SDValue Ptr = LD->getBasePtr();
5603 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5605 EVT PVT = LD->getValueType(0);
5606 if (PVT != MVT::i32 && PVT != MVT::f32)
5611 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5612 FI = FINode->getIndex();
5614 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5615 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5616 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5617 Offset = Ptr.getConstantOperandVal(1);
5618 Ptr = Ptr.getOperand(0);
5623 // FIXME: 256-bit vector instructions don't require a strict alignment,
5624 // improve this code to support it better.
5625 unsigned RequiredAlign = VT.getSizeInBits()/8;
5626 SDValue Chain = LD->getChain();
5627 // Make sure the stack object alignment is at least 16 or 32.
5628 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5629 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5630 if (MFI->isFixedObjectIndex(FI)) {
5631 // Can't change the alignment. FIXME: It's possible to compute
5632 // the exact stack offset and reference FI + adjust offset instead.
5633 // If someone *really* cares about this. That's the way to implement it.
5636 MFI->setObjectAlignment(FI, RequiredAlign);
5640 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5641 // Ptr + (Offset & ~15).
5644 if ((Offset % RequiredAlign) & 3)
5646 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5648 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5649 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5651 int EltNo = (Offset - StartOffset) >> 2;
5652 unsigned NumElems = VT.getVectorNumElements();
5654 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5655 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5656 LD->getPointerInfo().getWithOffset(StartOffset),
5657 false, false, false, 0);
5659 SmallVector<int, 8> Mask;
5660 for (unsigned i = 0; i != NumElems; ++i)
5661 Mask.push_back(EltNo);
5663 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5669 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5670 /// vector of type 'VT', see if the elements can be replaced by a single large
5671 /// load which has the same value as a build_vector whose operands are 'elts'.
5673 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5675 /// FIXME: we'd also like to handle the case where the last elements are zero
5676 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5677 /// There's even a handy isZeroNode for that purpose.
5678 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5679 SDLoc &DL, SelectionDAG &DAG,
5680 bool isAfterLegalize) {
5681 EVT EltVT = VT.getVectorElementType();
5682 unsigned NumElems = Elts.size();
5684 LoadSDNode *LDBase = nullptr;
5685 unsigned LastLoadedElt = -1U;
5687 // For each element in the initializer, see if we've found a load or an undef.
5688 // If we don't find an initial load element, or later load elements are
5689 // non-consecutive, bail out.
5690 for (unsigned i = 0; i < NumElems; ++i) {
5691 SDValue Elt = Elts[i];
5693 if (!Elt.getNode() ||
5694 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5697 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5699 LDBase = cast<LoadSDNode>(Elt.getNode());
5703 if (Elt.getOpcode() == ISD::UNDEF)
5706 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5707 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5712 // If we have found an entire vector of loads and undefs, then return a large
5713 // load of the entire vector width starting at the base pointer. If we found
5714 // consecutive loads for the low half, generate a vzext_load node.
5715 if (LastLoadedElt == NumElems - 1) {
5717 if (isAfterLegalize &&
5718 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5721 SDValue NewLd = SDValue();
5723 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5724 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5725 LDBase->getPointerInfo(),
5726 LDBase->isVolatile(), LDBase->isNonTemporal(),
5727 LDBase->isInvariant(), 0);
5728 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5729 LDBase->getPointerInfo(),
5730 LDBase->isVolatile(), LDBase->isNonTemporal(),
5731 LDBase->isInvariant(), LDBase->getAlignment());
5733 if (LDBase->hasAnyUseOfValue(1)) {
5734 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5736 SDValue(NewLd.getNode(), 1));
5737 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5738 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5739 SDValue(NewLd.getNode(), 1));
5744 if (NumElems == 4 && LastLoadedElt == 1 &&
5745 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5746 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5747 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5749 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5750 LDBase->getPointerInfo(),
5751 LDBase->getAlignment(),
5752 false/*isVolatile*/, true/*ReadMem*/,
5755 // Make sure the newly-created LOAD is in the same position as LDBase in
5756 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5757 // update uses of LDBase's output chain to use the TokenFactor.
5758 if (LDBase->hasAnyUseOfValue(1)) {
5759 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5760 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5761 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5762 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5763 SDValue(ResNode.getNode(), 1));
5766 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5771 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5772 /// to generate a splat value for the following cases:
5773 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5774 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5775 /// a scalar load, or a constant.
5776 /// The VBROADCAST node is returned when a pattern is found,
5777 /// or SDValue() otherwise.
5778 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5779 SelectionDAG &DAG) {
5780 if (!Subtarget->hasFp256())
5783 MVT VT = Op.getSimpleValueType();
5786 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5787 "Unsupported vector type for broadcast.");
5792 switch (Op.getOpcode()) {
5794 // Unknown pattern found.
5797 case ISD::BUILD_VECTOR: {
5798 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5799 BitVector UndefElements;
5800 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5802 // We need a splat of a single value to use broadcast, and it doesn't
5803 // make any sense if the value is only in one element of the vector.
5804 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5808 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5809 Ld.getOpcode() == ISD::ConstantFP);
5811 // Make sure that all of the users of a non-constant load are from the
5812 // BUILD_VECTOR node.
5813 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5818 case ISD::VECTOR_SHUFFLE: {
5819 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5821 // Shuffles must have a splat mask where the first element is
5823 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5826 SDValue Sc = Op.getOperand(0);
5827 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5828 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5830 if (!Subtarget->hasInt256())
5833 // Use the register form of the broadcast instruction available on AVX2.
5834 if (VT.getSizeInBits() >= 256)
5835 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5836 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5839 Ld = Sc.getOperand(0);
5840 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5841 Ld.getOpcode() == ISD::ConstantFP);
5843 // The scalar_to_vector node and the suspected
5844 // load node must have exactly one user.
5845 // Constants may have multiple users.
5847 // AVX-512 has register version of the broadcast
5848 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5849 Ld.getValueType().getSizeInBits() >= 32;
5850 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5857 bool IsGE256 = (VT.getSizeInBits() >= 256);
5859 // Handle the broadcasting a single constant scalar from the constant pool
5860 // into a vector. On Sandybridge it is still better to load a constant vector
5861 // from the constant pool and not to broadcast it from a scalar.
5862 if (ConstSplatVal && Subtarget->hasInt256()) {
5863 EVT CVT = Ld.getValueType();
5864 assert(!CVT.isVector() && "Must not broadcast a vector type");
5865 unsigned ScalarSize = CVT.getSizeInBits();
5867 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5868 const Constant *C = nullptr;
5869 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5870 C = CI->getConstantIntValue();
5871 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5872 C = CF->getConstantFPValue();
5874 assert(C && "Invalid constant type");
5876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5877 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5878 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5879 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5880 MachinePointerInfo::getConstantPool(),
5881 false, false, false, Alignment);
5883 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5887 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5888 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5890 // Handle AVX2 in-register broadcasts.
5891 if (!IsLoad && Subtarget->hasInt256() &&
5892 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5893 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5895 // The scalar source must be a normal load.
5899 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5900 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5902 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5903 // double since there is no vbroadcastsd xmm
5904 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5905 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5906 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5909 // Unsupported broadcast.
5913 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5914 /// underlying vector and index.
5916 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5918 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5920 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5921 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5924 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5926 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5928 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5929 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5932 // In this case the vector is the extract_subvector expression and the index
5933 // is 2, as specified by the shuffle.
5934 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5935 SDValue ShuffleVec = SVOp->getOperand(0);
5936 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5937 assert(ShuffleVecVT.getVectorElementType() ==
5938 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5940 int ShuffleIdx = SVOp->getMaskElt(Idx);
5941 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5942 ExtractedFromVec = ShuffleVec;
5948 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5949 MVT VT = Op.getSimpleValueType();
5951 // Skip if insert_vec_elt is not supported.
5952 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5953 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5957 unsigned NumElems = Op.getNumOperands();
5961 SmallVector<unsigned, 4> InsertIndices;
5962 SmallVector<int, 8> Mask(NumElems, -1);
5964 for (unsigned i = 0; i != NumElems; ++i) {
5965 unsigned Opc = Op.getOperand(i).getOpcode();
5967 if (Opc == ISD::UNDEF)
5970 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5971 // Quit if more than 1 elements need inserting.
5972 if (InsertIndices.size() > 1)
5975 InsertIndices.push_back(i);
5979 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5980 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5981 // Quit if non-constant index.
5982 if (!isa<ConstantSDNode>(ExtIdx))
5984 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5986 // Quit if extracted from vector of different type.
5987 if (ExtractedFromVec.getValueType() != VT)
5990 if (!VecIn1.getNode())
5991 VecIn1 = ExtractedFromVec;
5992 else if (VecIn1 != ExtractedFromVec) {
5993 if (!VecIn2.getNode())
5994 VecIn2 = ExtractedFromVec;
5995 else if (VecIn2 != ExtractedFromVec)
5996 // Quit if more than 2 vectors to shuffle
6000 if (ExtractedFromVec == VecIn1)
6002 else if (ExtractedFromVec == VecIn2)
6003 Mask[i] = Idx + NumElems;
6006 if (!VecIn1.getNode())
6009 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6010 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6011 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6012 unsigned Idx = InsertIndices[i];
6013 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6014 DAG.getIntPtrConstant(Idx));
6020 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6022 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6024 MVT VT = Op.getSimpleValueType();
6025 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6026 "Unexpected type in LowerBUILD_VECTORvXi1!");
6029 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6030 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6031 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6032 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6035 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6036 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6037 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6038 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6041 bool AllContants = true;
6042 uint64_t Immediate = 0;
6043 int NonConstIdx = -1;
6044 bool IsSplat = true;
6045 unsigned NumNonConsts = 0;
6046 unsigned NumConsts = 0;
6047 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6048 SDValue In = Op.getOperand(idx);
6049 if (In.getOpcode() == ISD::UNDEF)
6051 if (!isa<ConstantSDNode>(In)) {
6052 AllContants = false;
6058 if (cast<ConstantSDNode>(In)->getZExtValue())
6059 Immediate |= (1ULL << idx);
6061 if (In != Op.getOperand(0))
6066 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6067 DAG.getConstant(Immediate, MVT::i16));
6068 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6069 DAG.getIntPtrConstant(0));
6072 if (NumNonConsts == 1 && NonConstIdx != 0) {
6075 SDValue VecAsImm = DAG.getConstant(Immediate,
6076 MVT::getIntegerVT(VT.getSizeInBits()));
6077 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6080 DstVec = DAG.getUNDEF(VT);
6081 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6082 Op.getOperand(NonConstIdx),
6083 DAG.getIntPtrConstant(NonConstIdx));
6085 if (!IsSplat && (NonConstIdx != 0))
6086 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6087 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6090 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6091 DAG.getConstant(-1, SelectVT),
6092 DAG.getConstant(0, SelectVT));
6094 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6095 DAG.getConstant((Immediate | 1), SelectVT),
6096 DAG.getConstant(Immediate, SelectVT));
6097 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6100 /// \brief Return true if \p N implements a horizontal binop and return the
6101 /// operands for the horizontal binop into V0 and V1.
6103 /// This is a helper function of PerformBUILD_VECTORCombine.
6104 /// This function checks that the build_vector \p N in input implements a
6105 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6106 /// operation to match.
6107 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6108 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6109 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6112 /// This function only analyzes elements of \p N whose indices are
6113 /// in range [BaseIdx, LastIdx).
6114 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6116 unsigned BaseIdx, unsigned LastIdx,
6117 SDValue &V0, SDValue &V1) {
6118 EVT VT = N->getValueType(0);
6120 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6121 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6122 "Invalid Vector in input!");
6124 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6125 bool CanFold = true;
6126 unsigned ExpectedVExtractIdx = BaseIdx;
6127 unsigned NumElts = LastIdx - BaseIdx;
6128 V0 = DAG.getUNDEF(VT);
6129 V1 = DAG.getUNDEF(VT);
6131 // Check if N implements a horizontal binop.
6132 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6133 SDValue Op = N->getOperand(i + BaseIdx);
6136 if (Op->getOpcode() == ISD::UNDEF) {
6137 // Update the expected vector extract index.
6138 if (i * 2 == NumElts)
6139 ExpectedVExtractIdx = BaseIdx;
6140 ExpectedVExtractIdx += 2;
6144 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6149 SDValue Op0 = Op.getOperand(0);
6150 SDValue Op1 = Op.getOperand(1);
6152 // Try to match the following pattern:
6153 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6154 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6155 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6156 Op0.getOperand(0) == Op1.getOperand(0) &&
6157 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6158 isa<ConstantSDNode>(Op1.getOperand(1)));
6162 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6163 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6165 if (i * 2 < NumElts) {
6166 if (V0.getOpcode() == ISD::UNDEF)
6167 V0 = Op0.getOperand(0);
6169 if (V1.getOpcode() == ISD::UNDEF)
6170 V1 = Op0.getOperand(0);
6171 if (i * 2 == NumElts)
6172 ExpectedVExtractIdx = BaseIdx;
6175 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6176 if (I0 == ExpectedVExtractIdx)
6177 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6178 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6179 // Try to match the following dag sequence:
6180 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6181 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6185 ExpectedVExtractIdx += 2;
6191 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6192 /// a concat_vector.
6194 /// This is a helper function of PerformBUILD_VECTORCombine.
6195 /// This function expects two 256-bit vectors called V0 and V1.
6196 /// At first, each vector is split into two separate 128-bit vectors.
6197 /// Then, the resulting 128-bit vectors are used to implement two
6198 /// horizontal binary operations.
6200 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6202 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6203 /// the two new horizontal binop.
6204 /// When Mode is set, the first horizontal binop dag node would take as input
6205 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6206 /// horizontal binop dag node would take as input the lower 128-bit of V1
6207 /// and the upper 128-bit of V1.
6209 /// HADD V0_LO, V0_HI
6210 /// HADD V1_LO, V1_HI
6212 /// Otherwise, the first horizontal binop dag node takes as input the lower
6213 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6214 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6216 /// HADD V0_LO, V1_LO
6217 /// HADD V0_HI, V1_HI
6219 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6220 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6221 /// the upper 128-bits of the result.
6222 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6223 SDLoc DL, SelectionDAG &DAG,
6224 unsigned X86Opcode, bool Mode,
6225 bool isUndefLO, bool isUndefHI) {
6226 EVT VT = V0.getValueType();
6227 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6228 "Invalid nodes in input!");
6230 unsigned NumElts = VT.getVectorNumElements();
6231 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6232 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6233 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6234 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6235 EVT NewVT = V0_LO.getValueType();
6237 SDValue LO = DAG.getUNDEF(NewVT);
6238 SDValue HI = DAG.getUNDEF(NewVT);
6241 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6242 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6243 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6244 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6245 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6247 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6248 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6249 V1_LO->getOpcode() != ISD::UNDEF))
6250 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6252 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6253 V1_HI->getOpcode() != ISD::UNDEF))
6254 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6257 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6260 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6261 /// sequence of 'vadd + vsub + blendi'.
6262 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6263 const X86Subtarget *Subtarget) {
6265 EVT VT = BV->getValueType(0);
6266 unsigned NumElts = VT.getVectorNumElements();
6267 SDValue InVec0 = DAG.getUNDEF(VT);
6268 SDValue InVec1 = DAG.getUNDEF(VT);
6270 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6271 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6273 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6275 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6278 // Odd-numbered elements in the input build vector are obtained from
6279 // adding two integer/float elements.
6280 // Even-numbered elements in the input build vector are obtained from
6281 // subtracting two integer/float elements.
6282 unsigned ExpectedOpcode = ISD::FSUB;
6283 unsigned NextExpectedOpcode = ISD::FADD;
6284 bool AddFound = false;
6285 bool SubFound = false;
6287 for (unsigned i = 0, e = NumElts; i != e; i++) {
6288 SDValue Op = BV->getOperand(i);
6290 // Skip 'undef' values.
6291 unsigned Opcode = Op.getOpcode();
6292 if (Opcode == ISD::UNDEF) {
6293 std::swap(ExpectedOpcode, NextExpectedOpcode);
6297 // Early exit if we found an unexpected opcode.
6298 if (Opcode != ExpectedOpcode)
6301 SDValue Op0 = Op.getOperand(0);
6302 SDValue Op1 = Op.getOperand(1);
6304 // Try to match the following pattern:
6305 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6306 // Early exit if we cannot match that sequence.
6307 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6308 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6309 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6310 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6311 Op0.getOperand(1) != Op1.getOperand(1))
6314 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6318 // We found a valid add/sub node. Update the information accordingly.
6324 // Update InVec0 and InVec1.
6325 if (InVec0.getOpcode() == ISD::UNDEF)
6326 InVec0 = Op0.getOperand(0);
6327 if (InVec1.getOpcode() == ISD::UNDEF)
6328 InVec1 = Op1.getOperand(0);
6330 // Make sure that operands in input to each add/sub node always
6331 // come from a same pair of vectors.
6332 if (InVec0 != Op0.getOperand(0)) {
6333 if (ExpectedOpcode == ISD::FSUB)
6336 // FADD is commutable. Try to commute the operands
6337 // and then test again.
6338 std::swap(Op0, Op1);
6339 if (InVec0 != Op0.getOperand(0))
6343 if (InVec1 != Op1.getOperand(0))
6346 // Update the pair of expected opcodes.
6347 std::swap(ExpectedOpcode, NextExpectedOpcode);
6350 // Don't try to fold this build_vector into a VSELECT if it has
6351 // too many UNDEF operands.
6352 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6353 InVec1.getOpcode() != ISD::UNDEF) {
6354 // Emit a sequence of vector add and sub followed by a VSELECT.
6355 // The new VSELECT will be lowered into a BLENDI.
6356 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6357 // and emit a single ADDSUB instruction.
6358 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6359 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6361 // Construct the VSELECT mask.
6362 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6363 EVT SVT = MaskVT.getVectorElementType();
6364 unsigned SVTBits = SVT.getSizeInBits();
6365 SmallVector<SDValue, 8> Ops;
6367 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6368 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6369 APInt::getAllOnesValue(SVTBits);
6370 SDValue Constant = DAG.getConstant(Value, SVT);
6371 Ops.push_back(Constant);
6374 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6375 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6381 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6382 const X86Subtarget *Subtarget) {
6384 EVT VT = N->getValueType(0);
6385 unsigned NumElts = VT.getVectorNumElements();
6386 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6387 SDValue InVec0, InVec1;
6389 // Try to match an ADDSUB.
6390 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6391 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6392 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6393 if (Value.getNode())
6397 // Try to match horizontal ADD/SUB.
6398 unsigned NumUndefsLO = 0;
6399 unsigned NumUndefsHI = 0;
6400 unsigned Half = NumElts/2;
6402 // Count the number of UNDEF operands in the build_vector in input.
6403 for (unsigned i = 0, e = Half; i != e; ++i)
6404 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6407 for (unsigned i = Half, e = NumElts; i != e; ++i)
6408 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6411 // Early exit if this is either a build_vector of all UNDEFs or all the
6412 // operands but one are UNDEF.
6413 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6416 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6417 // Try to match an SSE3 float HADD/HSUB.
6418 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6419 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6421 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6422 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6423 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6424 // Try to match an SSSE3 integer HADD/HSUB.
6425 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6426 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6428 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6429 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6432 if (!Subtarget->hasAVX())
6435 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6436 // Try to match an AVX horizontal add/sub of packed single/double
6437 // precision floating point values from 256-bit vectors.
6438 SDValue InVec2, InVec3;
6439 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6440 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6441 ((InVec0.getOpcode() == ISD::UNDEF ||
6442 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6443 ((InVec1.getOpcode() == ISD::UNDEF ||
6444 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6445 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6447 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6448 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6449 ((InVec0.getOpcode() == ISD::UNDEF ||
6450 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6451 ((InVec1.getOpcode() == ISD::UNDEF ||
6452 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6453 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6454 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6455 // Try to match an AVX2 horizontal add/sub of signed integers.
6456 SDValue InVec2, InVec3;
6458 bool CanFold = true;
6460 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6461 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6462 ((InVec0.getOpcode() == ISD::UNDEF ||
6463 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6464 ((InVec1.getOpcode() == ISD::UNDEF ||
6465 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6466 X86Opcode = X86ISD::HADD;
6467 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6468 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6469 ((InVec0.getOpcode() == ISD::UNDEF ||
6470 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6471 ((InVec1.getOpcode() == ISD::UNDEF ||
6472 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6473 X86Opcode = X86ISD::HSUB;
6478 // Fold this build_vector into a single horizontal add/sub.
6479 // Do this only if the target has AVX2.
6480 if (Subtarget->hasAVX2())
6481 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6483 // Do not try to expand this build_vector into a pair of horizontal
6484 // add/sub if we can emit a pair of scalar add/sub.
6485 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6488 // Convert this build_vector into a pair of horizontal binop followed by
6490 bool isUndefLO = NumUndefsLO == Half;
6491 bool isUndefHI = NumUndefsHI == Half;
6492 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6493 isUndefLO, isUndefHI);
6497 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6498 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6500 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6501 X86Opcode = X86ISD::HADD;
6502 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6503 X86Opcode = X86ISD::HSUB;
6504 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6505 X86Opcode = X86ISD::FHADD;
6506 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6507 X86Opcode = X86ISD::FHSUB;
6511 // Don't try to expand this build_vector into a pair of horizontal add/sub
6512 // if we can simply emit a pair of scalar add/sub.
6513 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6516 // Convert this build_vector into two horizontal add/sub followed by
6518 bool isUndefLO = NumUndefsLO == Half;
6519 bool isUndefHI = NumUndefsHI == Half;
6520 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6521 isUndefLO, isUndefHI);
6528 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6531 MVT VT = Op.getSimpleValueType();
6532 MVT ExtVT = VT.getVectorElementType();
6533 unsigned NumElems = Op.getNumOperands();
6535 // Generate vectors for predicate vectors.
6536 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6537 return LowerBUILD_VECTORvXi1(Op, DAG);
6539 // Vectors containing all zeros can be matched by pxor and xorps later
6540 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6541 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6542 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6543 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6546 return getZeroVector(VT, Subtarget, DAG, dl);
6549 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6550 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6551 // vpcmpeqd on 256-bit vectors.
6552 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6553 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6556 if (!VT.is512BitVector())
6557 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6560 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6561 if (Broadcast.getNode())
6564 unsigned EVTBits = ExtVT.getSizeInBits();
6566 unsigned NumZero = 0;
6567 unsigned NumNonZero = 0;
6568 unsigned NonZeros = 0;
6569 bool IsAllConstants = true;
6570 SmallSet<SDValue, 8> Values;
6571 for (unsigned i = 0; i < NumElems; ++i) {
6572 SDValue Elt = Op.getOperand(i);
6573 if (Elt.getOpcode() == ISD::UNDEF)
6576 if (Elt.getOpcode() != ISD::Constant &&
6577 Elt.getOpcode() != ISD::ConstantFP)
6578 IsAllConstants = false;
6579 if (X86::isZeroNode(Elt))
6582 NonZeros |= (1 << i);
6587 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6588 if (NumNonZero == 0)
6589 return DAG.getUNDEF(VT);
6591 // Special case for single non-zero, non-undef, element.
6592 if (NumNonZero == 1) {
6593 unsigned Idx = countTrailingZeros(NonZeros);
6594 SDValue Item = Op.getOperand(Idx);
6596 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6597 // the value are obviously zero, truncate the value to i32 and do the
6598 // insertion that way. Only do this if the value is non-constant or if the
6599 // value is a constant being inserted into element 0. It is cheaper to do
6600 // a constant pool load than it is to do a movd + shuffle.
6601 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6602 (!IsAllConstants || Idx == 0)) {
6603 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6605 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6606 EVT VecVT = MVT::v4i32;
6607 unsigned VecElts = 4;
6609 // Truncate the value (which may itself be a constant) to i32, and
6610 // convert it to a vector with movd (S2V+shuffle to zero extend).
6611 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6612 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6613 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6615 // Now we have our 32-bit value zero extended in the low element of
6616 // a vector. If Idx != 0, swizzle it into place.
6618 SmallVector<int, 4> Mask;
6619 Mask.push_back(Idx);
6620 for (unsigned i = 1; i != VecElts; ++i)
6622 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6625 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6629 // If we have a constant or non-constant insertion into the low element of
6630 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6631 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6632 // depending on what the source datatype is.
6635 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6637 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6638 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6639 if (VT.is256BitVector() || VT.is512BitVector()) {
6640 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6641 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6642 Item, DAG.getIntPtrConstant(0));
6644 assert(VT.is128BitVector() && "Expected an SSE value type!");
6645 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6646 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6647 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6650 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6651 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6652 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6653 if (VT.is256BitVector()) {
6654 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6655 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6657 assert(VT.is128BitVector() && "Expected an SSE value type!");
6658 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6660 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6664 // Is it a vector logical left shift?
6665 if (NumElems == 2 && Idx == 1 &&
6666 X86::isZeroNode(Op.getOperand(0)) &&
6667 !X86::isZeroNode(Op.getOperand(1))) {
6668 unsigned NumBits = VT.getSizeInBits();
6669 return getVShift(true, VT,
6670 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6671 VT, Op.getOperand(1)),
6672 NumBits/2, DAG, *this, dl);
6675 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6678 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6679 // is a non-constant being inserted into an element other than the low one,
6680 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6681 // movd/movss) to move this into the low element, then shuffle it into
6683 if (EVTBits == 32) {
6684 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6686 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6687 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6688 SmallVector<int, 8> MaskVec;
6689 for (unsigned i = 0; i != NumElems; ++i)
6690 MaskVec.push_back(i == Idx ? 0 : 1);
6691 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6695 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6696 if (Values.size() == 1) {
6697 if (EVTBits == 32) {
6698 // Instead of a shuffle like this:
6699 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6700 // Check if it's possible to issue this instead.
6701 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6702 unsigned Idx = countTrailingZeros(NonZeros);
6703 SDValue Item = Op.getOperand(Idx);
6704 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6705 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6710 // A vector full of immediates; various special cases are already
6711 // handled, so this is best done with a single constant-pool load.
6715 // For AVX-length vectors, build the individual 128-bit pieces and use
6716 // shuffles to put them in place.
6717 if (VT.is256BitVector() || VT.is512BitVector()) {
6718 SmallVector<SDValue, 64> V;
6719 for (unsigned i = 0; i != NumElems; ++i)
6720 V.push_back(Op.getOperand(i));
6722 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6724 // Build both the lower and upper subvector.
6725 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6726 makeArrayRef(&V[0], NumElems/2));
6727 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6728 makeArrayRef(&V[NumElems / 2], NumElems/2));
6730 // Recreate the wider vector with the lower and upper part.
6731 if (VT.is256BitVector())
6732 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6733 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6736 // Let legalizer expand 2-wide build_vectors.
6737 if (EVTBits == 64) {
6738 if (NumNonZero == 1) {
6739 // One half is zero or undef.
6740 unsigned Idx = countTrailingZeros(NonZeros);
6741 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6742 Op.getOperand(Idx));
6743 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6748 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6749 if (EVTBits == 8 && NumElems == 16) {
6750 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6752 if (V.getNode()) return V;
6755 if (EVTBits == 16 && NumElems == 8) {
6756 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6758 if (V.getNode()) return V;
6761 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6762 if (EVTBits == 32 && NumElems == 4) {
6763 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6764 NumZero, DAG, Subtarget, *this);
6769 // If element VT is == 32 bits, turn it into a number of shuffles.
6770 SmallVector<SDValue, 8> V(NumElems);
6771 if (NumElems == 4 && NumZero > 0) {
6772 for (unsigned i = 0; i < 4; ++i) {
6773 bool isZero = !(NonZeros & (1 << i));
6775 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6777 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6780 for (unsigned i = 0; i < 2; ++i) {
6781 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6784 V[i] = V[i*2]; // Must be a zero vector.
6787 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6790 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6793 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6798 bool Reverse1 = (NonZeros & 0x3) == 2;
6799 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6803 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6804 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6806 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6809 if (Values.size() > 1 && VT.is128BitVector()) {
6810 // Check for a build vector of consecutive loads.
6811 for (unsigned i = 0; i < NumElems; ++i)
6812 V[i] = Op.getOperand(i);
6814 // Check for elements which are consecutive loads.
6815 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6819 // Check for a build vector from mostly shuffle plus few inserting.
6820 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6824 // For SSE 4.1, use insertps to put the high elements into the low element.
6825 if (getSubtarget()->hasSSE41()) {
6827 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6828 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6830 Result = DAG.getUNDEF(VT);
6832 for (unsigned i = 1; i < NumElems; ++i) {
6833 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6834 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6835 Op.getOperand(i), DAG.getIntPtrConstant(i));
6840 // Otherwise, expand into a number of unpckl*, start by extending each of
6841 // our (non-undef) elements to the full vector width with the element in the
6842 // bottom slot of the vector (which generates no code for SSE).
6843 for (unsigned i = 0; i < NumElems; ++i) {
6844 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6845 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6847 V[i] = DAG.getUNDEF(VT);
6850 // Next, we iteratively mix elements, e.g. for v4f32:
6851 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6852 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6853 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6854 unsigned EltStride = NumElems >> 1;
6855 while (EltStride != 0) {
6856 for (unsigned i = 0; i < EltStride; ++i) {
6857 // If V[i+EltStride] is undef and this is the first round of mixing,
6858 // then it is safe to just drop this shuffle: V[i] is already in the
6859 // right place, the one element (since it's the first round) being
6860 // inserted as undef can be dropped. This isn't safe for successive
6861 // rounds because they will permute elements within both vectors.
6862 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6863 EltStride == NumElems/2)
6866 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6875 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6876 // to create 256-bit vectors from two other 128-bit ones.
6877 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6879 MVT ResVT = Op.getSimpleValueType();
6881 assert((ResVT.is256BitVector() ||
6882 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6884 SDValue V1 = Op.getOperand(0);
6885 SDValue V2 = Op.getOperand(1);
6886 unsigned NumElems = ResVT.getVectorNumElements();
6887 if(ResVT.is256BitVector())
6888 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6890 if (Op.getNumOperands() == 4) {
6891 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6892 ResVT.getVectorNumElements()/2);
6893 SDValue V3 = Op.getOperand(2);
6894 SDValue V4 = Op.getOperand(3);
6895 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6896 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6898 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6901 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6902 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6903 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6904 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6905 Op.getNumOperands() == 4)));
6907 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6908 // from two other 128-bit ones.
6910 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6911 return LowerAVXCONCAT_VECTORS(Op, DAG);
6915 //===----------------------------------------------------------------------===//
6916 // Vector shuffle lowering
6918 // This is an experimental code path for lowering vector shuffles on x86. It is
6919 // designed to handle arbitrary vector shuffles and blends, gracefully
6920 // degrading performance as necessary. It works hard to recognize idiomatic
6921 // shuffles and lower them to optimal instruction patterns without leaving
6922 // a framework that allows reasonably efficient handling of all vector shuffle
6924 //===----------------------------------------------------------------------===//
6926 /// \brief Tiny helper function to identify a no-op mask.
6928 /// This is a somewhat boring predicate function. It checks whether the mask
6929 /// array input, which is assumed to be a single-input shuffle mask of the kind
6930 /// used by the X86 shuffle instructions (not a fully general
6931 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6932 /// in-place shuffle are 'no-op's.
6933 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6934 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6935 if (Mask[i] != -1 && Mask[i] != i)
6940 /// \brief Helper function to classify a mask as a single-input mask.
6942 /// This isn't a generic single-input test because in the vector shuffle
6943 /// lowering we canonicalize single inputs to be the first input operand. This
6944 /// means we can more quickly test for a single input by only checking whether
6945 /// an input from the second operand exists. We also assume that the size of
6946 /// mask corresponds to the size of the input vectors which isn't true in the
6947 /// fully general case.
6948 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6950 if (M >= (int)Mask.size())
6955 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6957 /// This helper function produces an 8-bit shuffle immediate corresponding to
6958 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6959 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6962 /// NB: We rely heavily on "undef" masks preserving the input lane.
6963 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6964 SelectionDAG &DAG) {
6965 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6966 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6967 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6968 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6969 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6972 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6973 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6974 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6975 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6976 return DAG.getConstant(Imm, MVT::i8);
6979 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6981 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6982 /// support for floating point shuffles but not integer shuffles. These
6983 /// instructions will incur a domain crossing penalty on some chips though so
6984 /// it is better to avoid lowering through this for integer vectors where
6986 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6987 const X86Subtarget *Subtarget,
6988 SelectionDAG &DAG) {
6990 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6991 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6992 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6993 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6994 ArrayRef<int> Mask = SVOp->getMask();
6995 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6997 if (isSingleInputShuffleMask(Mask)) {
6998 // Straight shuffle of a single input vector. Simulate this by using the
6999 // single input as both of the "inputs" to this instruction..
7000 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7001 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7002 DAG.getConstant(SHUFPDMask, MVT::i8));
7004 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7005 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7007 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7008 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7009 DAG.getConstant(SHUFPDMask, MVT::i8));
7012 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7014 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7015 /// the integer unit to minimize domain crossing penalties. However, for blends
7016 /// it falls back to the floating point shuffle operation with appropriate bit
7018 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7019 const X86Subtarget *Subtarget,
7020 SelectionDAG &DAG) {
7022 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7023 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7024 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7025 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7026 ArrayRef<int> Mask = SVOp->getMask();
7027 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7029 if (isSingleInputShuffleMask(Mask)) {
7030 // Straight shuffle of a single input vector. For everything from SSE2
7031 // onward this has a single fast instruction with no scary immediates.
7032 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7033 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7034 int WidenedMask[4] = {
7035 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7036 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7038 ISD::BITCAST, DL, MVT::v2i64,
7039 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7040 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7043 // We implement this with SHUFPD which is pretty lame because it will likely
7044 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7045 // However, all the alternatives are still more cycles and newer chips don't
7046 // have this problem. It would be really nice if x86 had better shuffles here.
7047 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7048 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7049 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7050 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7053 /// \brief Lower 4-lane 32-bit floating point shuffles.
7055 /// Uses instructions exclusively from the floating point unit to minimize
7056 /// domain crossing penalties, as these are sufficient to implement all v4f32
7058 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7059 const X86Subtarget *Subtarget,
7060 SelectionDAG &DAG) {
7062 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7063 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7064 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7066 ArrayRef<int> Mask = SVOp->getMask();
7067 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7069 SDValue LowV = V1, HighV = V2;
7070 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7073 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7075 if (NumV2Elements == 0)
7076 // Straight shuffle of a single input vector. We pass the input vector to
7077 // both operands to simulate this with a SHUFPS.
7078 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7079 getV4X86ShuffleImm8ForMask(Mask, DAG));
7081 if (NumV2Elements == 1) {
7083 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7085 // Compute the index adjacent to V2Index and in the same half by toggling
7087 int V2AdjIndex = V2Index ^ 1;
7089 if (Mask[V2AdjIndex] == -1) {
7090 // Handles all the cases where we have a single V2 element and an undef.
7091 // This will only ever happen in the high lanes because we commute the
7092 // vector otherwise.
7094 std::swap(LowV, HighV);
7095 NewMask[V2Index] -= 4;
7097 // Handle the case where the V2 element ends up adjacent to a V1 element.
7098 // To make this work, blend them together as the first step.
7099 int V1Index = V2AdjIndex;
7100 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7101 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7102 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7104 // Now proceed to reconstruct the final blend as we have the necessary
7105 // high or low half formed.
7112 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7113 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7115 } else if (NumV2Elements == 2) {
7116 if (Mask[0] < 4 && Mask[1] < 4) {
7117 // Handle the easy case where we have V1 in the low lanes and V2 in the
7118 // high lanes. We never see this reversed because we sort the shuffle.
7122 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7123 // trying to place elements directly, just blend them and set up the final
7124 // shuffle to place them.
7126 // The first two blend mask elements are for V1, the second two are for
7128 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7129 Mask[2] < 4 ? Mask[2] : Mask[3],
7130 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7131 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7132 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7133 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7135 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7138 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7139 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7140 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7141 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7144 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7145 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7148 /// \brief Lower 4-lane i32 vector shuffles.
7150 /// We try to handle these with integer-domain shuffles where we can, but for
7151 /// blends we use the floating point domain blend instructions.
7152 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7153 const X86Subtarget *Subtarget,
7154 SelectionDAG &DAG) {
7156 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7157 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7158 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7159 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7160 ArrayRef<int> Mask = SVOp->getMask();
7161 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7163 if (isSingleInputShuffleMask(Mask))
7164 // Straight shuffle of a single input vector. For everything from SSE2
7165 // onward this has a single fast instruction with no scary immediates.
7166 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7167 getV4X86ShuffleImm8ForMask(Mask, DAG));
7169 // We implement this with SHUFPS because it can blend from two vectors.
7170 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7171 // up the inputs, bypassing domain shift penalties that we would encur if we
7172 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7174 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7175 DAG.getVectorShuffle(
7177 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7178 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7181 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7182 /// shuffle lowering, and the most complex part.
7184 /// The lowering strategy is to try to form pairs of input lanes which are
7185 /// targeted at the same half of the final vector, and then use a dword shuffle
7186 /// to place them onto the right half, and finally unpack the paired lanes into
7187 /// their final position.
7189 /// The exact breakdown of how to form these dword pairs and align them on the
7190 /// correct sides is really tricky. See the comments within the function for
7191 /// more of the details.
7192 static SDValue lowerV8I16SingleInputVectorShuffle(
7193 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7194 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7195 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7196 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7197 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7199 SmallVector<int, 4> LoInputs;
7200 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7201 [](int M) { return M >= 0; });
7202 std::sort(LoInputs.begin(), LoInputs.end());
7203 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7204 SmallVector<int, 4> HiInputs;
7205 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7206 [](int M) { return M >= 0; });
7207 std::sort(HiInputs.begin(), HiInputs.end());
7208 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7210 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7211 int NumHToL = LoInputs.size() - NumLToL;
7213 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7214 int NumHToH = HiInputs.size() - NumLToH;
7215 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7216 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7217 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7218 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7220 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7221 // such inputs we can swap two of the dwords across the half mark and end up
7222 // with <=2 inputs to each half in each half. Once there, we can fall through
7223 // to the generic code below. For example:
7225 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7226 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7228 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7230 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7231 int ThreeInputHalfSum, int OneInputHalfOffset) {
7232 // Compute the index of dword with only one word among the three inputs in
7233 // a half by taking the sum of the half with three inputs and subtracting
7234 // the sum of the actual three inputs. The difference is the remaining
7236 int DWordA = (ThreeInputHalfSum -
7237 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7239 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7241 int PSHUFDMask[] = {0, 1, 2, 3};
7242 PSHUFDMask[DWordA] = DWordB;
7243 PSHUFDMask[DWordB] = DWordA;
7244 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7245 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7246 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7247 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7249 // Adjust the mask to match the new locations of A and B.
7251 if (M != -1 && M/2 == DWordA)
7252 M = 2 * DWordB + M % 2;
7253 else if (M != -1 && M/2 == DWordB)
7254 M = 2 * DWordA + M % 2;
7256 // Recurse back into this routine to re-compute state now that this isn't
7257 // a 3 and 1 problem.
7258 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7261 if (NumLToL == 3 && NumHToL == 1)
7262 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7263 else if (NumLToL == 1 && NumHToL == 3)
7264 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7265 else if (NumLToH == 1 && NumHToH == 3)
7266 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7267 else if (NumLToH == 3 && NumHToH == 1)
7268 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7270 // At this point there are at most two inputs to the low and high halves from
7271 // each half. That means the inputs can always be grouped into dwords and
7272 // those dwords can then be moved to the correct half with a dword shuffle.
7273 // We use at most one low and one high word shuffle to collect these paired
7274 // inputs into dwords, and finally a dword shuffle to place them.
7275 int PSHUFLMask[4] = {-1, -1, -1, -1};
7276 int PSHUFHMask[4] = {-1, -1, -1, -1};
7277 int PSHUFDMask[4] = {-1, -1, -1, -1};
7279 // First fix the masks for all the inputs that are staying in their
7280 // original halves. This will then dictate the targets of the cross-half
7282 auto fixInPlaceInputs = [&PSHUFDMask](
7283 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7284 MutableArrayRef<int> HalfMask, int HalfOffset) {
7285 if (InPlaceInputs.empty())
7287 if (InPlaceInputs.size() == 1) {
7288 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7289 InPlaceInputs[0] - HalfOffset;
7290 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7294 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7295 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7296 InPlaceInputs[0] - HalfOffset;
7297 // Put the second input next to the first so that they are packed into
7298 // a dword. We find the adjacent index by toggling the low bit.
7299 int AdjIndex = InPlaceInputs[0] ^ 1;
7300 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7301 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7302 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7304 if (!HToLInputs.empty())
7305 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7306 if (!LToHInputs.empty())
7307 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7309 // Now gather the cross-half inputs and place them into a free dword of
7310 // their target half.
7311 // FIXME: This operation could almost certainly be simplified dramatically to
7312 // look more like the 3-1 fixing operation.
7313 auto moveInputsToRightHalf = [&PSHUFDMask](
7314 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7315 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7316 int SourceOffset, int DestOffset) {
7317 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7318 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7320 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7322 int LowWord = Word & ~1;
7323 int HighWord = Word | 1;
7324 return isWordClobbered(SourceHalfMask, LowWord) ||
7325 isWordClobbered(SourceHalfMask, HighWord);
7328 if (IncomingInputs.empty())
7331 if (ExistingInputs.empty()) {
7332 // Map any dwords with inputs from them into the right half.
7333 for (int Input : IncomingInputs) {
7334 // If the source half mask maps over the inputs, turn those into
7335 // swaps and use the swapped lane.
7336 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7337 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7338 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7339 Input - SourceOffset;
7340 // We have to swap the uses in our half mask in one sweep.
7341 for (int &M : HalfMask)
7342 if (M == SourceHalfMask[Input - SourceOffset])
7344 else if (M == Input)
7345 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7347 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7348 Input - SourceOffset &&
7349 "Previous placement doesn't match!");
7351 // Note that this correctly re-maps both when we do a swap and when
7352 // we observe the other side of the swap above. We rely on that to
7353 // avoid swapping the members of the input list directly.
7354 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7357 // Map the input's dword into the correct half.
7358 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7359 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7361 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7363 "Previous placement doesn't match!");
7366 // And just directly shift any other-half mask elements to be same-half
7367 // as we will have mirrored the dword containing the element into the
7368 // same position within that half.
7369 for (int &M : HalfMask)
7370 if (M >= SourceOffset && M < SourceOffset + 4) {
7371 M = M - SourceOffset + DestOffset;
7372 assert(M >= 0 && "This should never wrap below zero!");
7377 // Ensure we have the input in a viable dword of its current half. This
7378 // is particularly tricky because the original position may be clobbered
7379 // by inputs being moved and *staying* in that half.
7380 if (IncomingInputs.size() == 1) {
7381 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7382 int InputFixed = std::find(std::begin(SourceHalfMask),
7383 std::end(SourceHalfMask), -1) -
7384 std::begin(SourceHalfMask) + SourceOffset;
7385 SourceHalfMask[InputFixed - SourceOffset] =
7386 IncomingInputs[0] - SourceOffset;
7387 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7389 IncomingInputs[0] = InputFixed;
7391 } else if (IncomingInputs.size() == 2) {
7392 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7393 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7394 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7395 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7396 "Not all dwords can be clobbered!");
7397 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7398 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7399 for (int &M : HalfMask)
7400 if (M == IncomingInputs[0])
7401 M = SourceDWordBase + SourceOffset;
7402 else if (M == IncomingInputs[1])
7403 M = SourceDWordBase + 1 + SourceOffset;
7404 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7405 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7408 llvm_unreachable("Unhandled input size!");
7411 // Now hoist the DWord down to the right half.
7412 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7413 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7414 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7415 for (int Input : IncomingInputs)
7416 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7417 FreeDWord * 2 + Input % 2);
7419 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7420 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7421 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7422 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7424 // Now enact all the shuffles we've computed to move the inputs into their
7426 if (!isNoopShuffleMask(PSHUFLMask))
7427 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7428 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7429 if (!isNoopShuffleMask(PSHUFHMask))
7430 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7431 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7432 if (!isNoopShuffleMask(PSHUFDMask))
7433 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7434 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7435 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7436 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7438 // At this point, each half should contain all its inputs, and we can then
7439 // just shuffle them into their final position.
7440 assert(std::count_if(LoMask.begin(), LoMask.end(),
7441 [](int M) { return M >= 4; }) == 0 &&
7442 "Failed to lift all the high half inputs to the low mask!");
7443 assert(std::count_if(HiMask.begin(), HiMask.end(),
7444 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7445 "Failed to lift all the low half inputs to the high mask!");
7447 // Do a half shuffle for the low mask.
7448 if (!isNoopShuffleMask(LoMask))
7449 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7450 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7452 // Do a half shuffle with the high mask after shifting its values down.
7453 for (int &M : HiMask)
7456 if (!isNoopShuffleMask(HiMask))
7457 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7458 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7463 /// \brief Detect whether the mask pattern should be lowered through
7466 /// This essentially tests whether viewing the mask as an interleaving of two
7467 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7468 /// lowering it through interleaving is a significantly better strategy.
7469 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7470 int NumEvenInputs[2] = {0, 0};
7471 int NumOddInputs[2] = {0, 0};
7472 int NumLoInputs[2] = {0, 0};
7473 int NumHiInputs[2] = {0, 0};
7474 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7478 int InputIdx = Mask[i] >= Size;
7481 ++NumLoInputs[InputIdx];
7483 ++NumHiInputs[InputIdx];
7486 ++NumEvenInputs[InputIdx];
7488 ++NumOddInputs[InputIdx];
7491 // The minimum number of cross-input results for both the interleaved and
7492 // split cases. If interleaving results in fewer cross-input results, return
7494 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7495 NumEvenInputs[0] + NumOddInputs[1]);
7496 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7497 NumLoInputs[0] + NumHiInputs[1]);
7498 return InterleavedCrosses < SplitCrosses;
7501 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7503 /// This strategy only works when the inputs from each vector fit into a single
7504 /// half of that vector, and generally there are not so many inputs as to leave
7505 /// the in-place shuffles required highly constrained (and thus expensive). It
7506 /// shifts all the inputs into a single side of both input vectors and then
7507 /// uses an unpack to interleave these inputs in a single vector. At that
7508 /// point, we will fall back on the generic single input shuffle lowering.
7509 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7511 MutableArrayRef<int> Mask,
7512 const X86Subtarget *Subtarget,
7513 SelectionDAG &DAG) {
7514 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7515 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7516 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7517 for (int i = 0; i < 8; ++i)
7518 if (Mask[i] >= 0 && Mask[i] < 4)
7519 LoV1Inputs.push_back(i);
7520 else if (Mask[i] >= 4 && Mask[i] < 8)
7521 HiV1Inputs.push_back(i);
7522 else if (Mask[i] >= 8 && Mask[i] < 12)
7523 LoV2Inputs.push_back(i);
7524 else if (Mask[i] >= 12)
7525 HiV2Inputs.push_back(i);
7527 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7528 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7531 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7532 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7533 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7535 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7536 HiV1Inputs.size() + HiV2Inputs.size();
7538 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7539 ArrayRef<int> HiInputs, bool MoveToLo,
7541 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7542 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7543 if (BadInputs.empty())
7546 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7547 int MoveOffset = MoveToLo ? 0 : 4;
7549 if (GoodInputs.empty()) {
7550 for (int BadInput : BadInputs) {
7551 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7552 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7555 if (GoodInputs.size() == 2) {
7556 // If the low inputs are spread across two dwords, pack them into
7558 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7559 Mask[GoodInputs[0]] - MaskOffset;
7560 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7561 Mask[GoodInputs[1]] - MaskOffset;
7562 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7563 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7565 // Otherwise pin the low inputs.
7566 for (int GoodInput : GoodInputs)
7567 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7571 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7572 std::begin(MoveMask);
7573 assert(MoveMaskIdx >= MoveOffset && "Established above");
7575 if (BadInputs.size() == 2) {
7576 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7577 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7578 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7579 Mask[BadInputs[0]] - MaskOffset;
7580 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7581 Mask[BadInputs[1]] - MaskOffset;
7582 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7583 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7585 assert(BadInputs.size() == 1 && "All sizes handled");
7586 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7587 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7591 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7594 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7596 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7599 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7600 // cross-half traffic in the final shuffle.
7602 // Munge the mask to be a single-input mask after the unpack merges the
7606 M = 2 * (M % 4) + (M / 8);
7608 return DAG.getVectorShuffle(
7609 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7610 DL, MVT::v8i16, V1, V2),
7611 DAG.getUNDEF(MVT::v8i16), Mask);
7614 /// \brief Generic lowering of 8-lane i16 shuffles.
7616 /// This handles both single-input shuffles and combined shuffle/blends with
7617 /// two inputs. The single input shuffles are immediately delegated to
7618 /// a dedicated lowering routine.
7620 /// The blends are lowered in one of three fundamental ways. If there are few
7621 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7622 /// of the input is significantly cheaper when lowered as an interleaving of
7623 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7624 /// halves of the inputs separately (making them have relatively few inputs)
7625 /// and then concatenate them.
7626 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7627 const X86Subtarget *Subtarget,
7628 SelectionDAG &DAG) {
7630 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7631 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7632 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7633 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7634 ArrayRef<int> OrigMask = SVOp->getMask();
7635 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7636 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7637 MutableArrayRef<int> Mask(MaskStorage);
7639 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7641 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7642 auto isV2 = [](int M) { return M >= 8; };
7644 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7645 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7647 if (NumV2Inputs == 0)
7648 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7650 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7651 "to be V1-input shuffles.");
7653 if (NumV1Inputs + NumV2Inputs <= 4)
7654 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7656 // Check whether an interleaving lowering is likely to be more efficient.
7657 // This isn't perfect but it is a strong heuristic that tends to work well on
7658 // the kinds of shuffles that show up in practice.
7660 // FIXME: Handle 1x, 2x, and 4x interleaving.
7661 if (shouldLowerAsInterleaving(Mask)) {
7662 // FIXME: Figure out whether we should pack these into the low or high
7665 int EMask[8], OMask[8];
7666 for (int i = 0; i < 4; ++i) {
7667 EMask[i] = Mask[2*i];
7668 OMask[i] = Mask[2*i + 1];
7673 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7674 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7676 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7679 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7680 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7682 for (int i = 0; i < 4; ++i) {
7683 LoBlendMask[i] = Mask[i];
7684 HiBlendMask[i] = Mask[i + 4];
7687 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7688 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7689 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7690 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7692 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7693 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7696 /// \brief Generic lowering of v16i8 shuffles.
7698 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7699 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7700 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7701 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7703 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7704 const X86Subtarget *Subtarget,
7705 SelectionDAG &DAG) {
7707 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7708 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7709 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7710 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7711 ArrayRef<int> OrigMask = SVOp->getMask();
7712 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7713 int MaskStorage[16] = {
7714 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7715 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7716 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7717 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7718 MutableArrayRef<int> Mask(MaskStorage);
7719 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7720 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7722 // For single-input shuffles, there are some nicer lowering tricks we can use.
7723 if (isSingleInputShuffleMask(Mask)) {
7724 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7725 // Notably, this handles splat and partial-splat shuffles more efficiently.
7726 // However, it only makes sense if the pre-duplication shuffle simplifies
7727 // things significantly. Currently, this means we need to be able to
7728 // express the pre-duplication shuffle as an i16 shuffle.
7730 // FIXME: We should check for other patterns which can be widened into an
7731 // i16 shuffle as well.
7732 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7733 for (int i = 0; i < 16; i += 2) {
7734 if (Mask[i] != Mask[i + 1])
7739 auto tryToWidenViaDuplication = [&]() -> SDValue {
7740 if (!canWidenViaDuplication(Mask))
7742 SmallVector<int, 4> LoInputs;
7743 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7744 [](int M) { return M >= 0 && M < 8; });
7745 std::sort(LoInputs.begin(), LoInputs.end());
7746 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7748 SmallVector<int, 4> HiInputs;
7749 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7750 [](int M) { return M >= 8; });
7751 std::sort(HiInputs.begin(), HiInputs.end());
7752 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7755 bool TargetLo = LoInputs.size() >= HiInputs.size();
7756 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7757 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7759 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7760 SmallDenseMap<int, int, 8> LaneMap;
7761 for (int I : InPlaceInputs) {
7762 PreDupI16Shuffle[I/2] = I/2;
7765 int j = TargetLo ? 0 : 4, je = j + 4;
7766 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7767 // Check if j is already a shuffle of this input. This happens when
7768 // there are two adjacent bytes after we move the low one.
7769 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7770 // If we haven't yet mapped the input, search for a slot into which
7772 while (j < je && PreDupI16Shuffle[j] != -1)
7776 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7779 // Map this input with the i16 shuffle.
7780 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7783 // Update the lane map based on the mapping we ended up with.
7784 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7787 ISD::BITCAST, DL, MVT::v16i8,
7788 DAG.getVectorShuffle(MVT::v8i16, DL,
7789 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7790 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7792 // Unpack the bytes to form the i16s that will be shuffled into place.
7793 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7794 MVT::v16i8, V1, V1);
7796 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7797 for (int i = 0; i < 16; i += 2) {
7799 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7800 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7803 ISD::BITCAST, DL, MVT::v16i8,
7804 DAG.getVectorShuffle(MVT::v8i16, DL,
7805 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7806 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7808 if (SDValue V = tryToWidenViaDuplication())
7812 // Check whether an interleaving lowering is likely to be more efficient.
7813 // This isn't perfect but it is a strong heuristic that tends to work well on
7814 // the kinds of shuffles that show up in practice.
7816 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7817 if (shouldLowerAsInterleaving(Mask)) {
7818 // FIXME: Figure out whether we should pack these into the low or high
7821 int EMask[16], OMask[16];
7822 for (int i = 0; i < 8; ++i) {
7823 EMask[i] = Mask[2*i];
7824 OMask[i] = Mask[2*i + 1];
7829 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7830 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7832 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7835 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7836 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7837 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7838 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7840 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7841 MutableArrayRef<int> V1HalfBlendMask,
7842 MutableArrayRef<int> V2HalfBlendMask) {
7843 for (int i = 0; i < 8; ++i)
7844 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7845 V1HalfBlendMask[i] = HalfMask[i];
7847 } else if (HalfMask[i] >= 16) {
7848 V2HalfBlendMask[i] = HalfMask[i] - 16;
7849 HalfMask[i] = i + 8;
7852 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7853 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7855 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7857 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7858 MutableArrayRef<int> HiBlendMask) {
7860 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7861 // them out and avoid using UNPCK{L,H} to extract the elements of V as
7863 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7864 [](int M) { return M >= 0 && M % 2 == 1; }) &&
7865 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7866 [](int M) { return M >= 0 && M % 2 == 1; })) {
7867 // Use a mask to drop the high bytes.
7868 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7869 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7870 DAG.getConstant(0x00FF, MVT::v8i16));
7872 // This will be a single vector shuffle instead of a blend so nuke V2.
7873 V2 = DAG.getUNDEF(MVT::v8i16);
7875 // Squash the masks to point directly into V1.
7876 for (int &M : LoBlendMask)
7879 for (int &M : HiBlendMask)
7883 // Otherwise just unpack the low half of V into V1 and the high half into
7884 // V2 so that we can blend them as i16s.
7885 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7886 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7887 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7888 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7891 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7892 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7893 return std::make_pair(BlendedLo, BlendedHi);
7895 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7896 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7897 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7899 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7900 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7902 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7905 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7907 /// This routine breaks down the specific type of 128-bit shuffle and
7908 /// dispatches to the lowering routines accordingly.
7909 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7910 MVT VT, const X86Subtarget *Subtarget,
7911 SelectionDAG &DAG) {
7912 switch (VT.SimpleTy) {
7914 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7916 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7918 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7920 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7922 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7924 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7927 llvm_unreachable("Unimplemented!");
7931 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7932 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7933 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7934 if (Mask[i] + 1 != Mask[i+1])
7940 /// \brief Top-level lowering for x86 vector shuffles.
7942 /// This handles decomposition, canonicalization, and lowering of all x86
7943 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7944 /// above in helper routines. The canonicalization attempts to widen shuffles
7945 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7946 /// s.t. only one of the two inputs needs to be tested, etc.
7947 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7948 SelectionDAG &DAG) {
7949 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7950 ArrayRef<int> Mask = SVOp->getMask();
7951 SDValue V1 = Op.getOperand(0);
7952 SDValue V2 = Op.getOperand(1);
7953 MVT VT = Op.getSimpleValueType();
7954 int NumElements = VT.getVectorNumElements();
7957 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7959 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7960 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7961 if (V1IsUndef && V2IsUndef)
7962 return DAG.getUNDEF(VT);
7964 // When we create a shuffle node we put the UNDEF node to second operand,
7965 // but in some cases the first operand may be transformed to UNDEF.
7966 // In this case we should just commute the node.
7968 return DAG.getCommutedVectorShuffle(*SVOp);
7970 // Check for non-undef masks pointing at an undef vector and make the masks
7971 // undef as well. This makes it easier to match the shuffle based solely on
7975 if (M >= NumElements) {
7976 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7977 for (int &M : NewMask)
7978 if (M >= NumElements)
7980 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7983 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7984 // lanes but wider integers. We cap this to not form integers larger than i64
7985 // but it might be interesting to form i128 integers to handle flipping the
7986 // low and high halves of AVX 256-bit vectors.
7987 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7988 areAdjacentMasksSequential(Mask)) {
7989 SmallVector<int, 8> NewMask;
7990 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7991 NewMask.push_back(Mask[i] / 2);
7993 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7994 VT.getVectorNumElements() / 2);
7995 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7996 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7997 return DAG.getNode(ISD::BITCAST, dl, VT,
7998 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8001 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8002 for (int M : SVOp->getMask())
8005 else if (M < NumElements)
8010 // Commute the shuffle as needed such that more elements come from V1 than
8011 // V2. This allows us to match the shuffle pattern strictly on how many
8012 // elements come from V1 without handling the symmetric cases.
8013 if (NumV2Elements > NumV1Elements)
8014 return DAG.getCommutedVectorShuffle(*SVOp);
8016 // When the number of V1 and V2 elements are the same, try to minimize the
8017 // number of uses of V2 in the low half of the vector.
8018 if (NumV1Elements == NumV2Elements) {
8019 int LowV1Elements = 0, LowV2Elements = 0;
8020 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8021 if (M >= NumElements)
8025 if (LowV2Elements > LowV1Elements)
8026 return DAG.getCommutedVectorShuffle(*SVOp);
8029 // For each vector width, delegate to a specialized lowering routine.
8030 if (VT.getSizeInBits() == 128)
8031 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8033 llvm_unreachable("Unimplemented!");
8037 //===----------------------------------------------------------------------===//
8038 // Legacy vector shuffle lowering
8040 // This code is the legacy code handling vector shuffles until the above
8041 // replaces its functionality and performance.
8042 //===----------------------------------------------------------------------===//
8044 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8045 bool hasInt256, unsigned *MaskOut = nullptr) {
8046 MVT EltVT = VT.getVectorElementType();
8048 // There is no blend with immediate in AVX-512.
8049 if (VT.is512BitVector())
8052 if (!hasSSE41 || EltVT == MVT::i8)
8054 if (!hasInt256 && VT == MVT::v16i16)
8057 unsigned MaskValue = 0;
8058 unsigned NumElems = VT.getVectorNumElements();
8059 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8060 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8061 unsigned NumElemsInLane = NumElems / NumLanes;
8063 // Blend for v16i16 should be symetric for the both lanes.
8064 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8066 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8067 int EltIdx = MaskVals[i];
8069 if ((EltIdx < 0 || EltIdx == (int)i) &&
8070 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8073 if (((unsigned)EltIdx == (i + NumElems)) &&
8074 (SndLaneEltIdx < 0 ||
8075 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8076 MaskValue |= (1 << i);
8082 *MaskOut = MaskValue;
8086 // Try to lower a shuffle node into a simple blend instruction.
8087 // This function assumes isBlendMask returns true for this
8088 // SuffleVectorSDNode
8089 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8091 const X86Subtarget *Subtarget,
8092 SelectionDAG &DAG) {
8093 MVT VT = SVOp->getSimpleValueType(0);
8094 MVT EltVT = VT.getVectorElementType();
8095 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8096 Subtarget->hasInt256() && "Trying to lower a "
8097 "VECTOR_SHUFFLE to a Blend but "
8098 "with the wrong mask"));
8099 SDValue V1 = SVOp->getOperand(0);
8100 SDValue V2 = SVOp->getOperand(1);
8102 unsigned NumElems = VT.getVectorNumElements();
8104 // Convert i32 vectors to floating point if it is not AVX2.
8105 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8107 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8108 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8110 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8111 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8114 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8115 DAG.getConstant(MaskValue, MVT::i32));
8116 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8119 /// In vector type \p VT, return true if the element at index \p InputIdx
8120 /// falls on a different 128-bit lane than \p OutputIdx.
8121 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8122 unsigned OutputIdx) {
8123 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8124 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8127 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8128 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8129 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8130 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8132 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8133 SelectionDAG &DAG) {
8134 MVT VT = V1.getSimpleValueType();
8135 assert(VT.is128BitVector() || VT.is256BitVector());
8137 MVT EltVT = VT.getVectorElementType();
8138 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8139 unsigned NumElts = VT.getVectorNumElements();
8141 SmallVector<SDValue, 32> PshufbMask;
8142 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8143 int InputIdx = MaskVals[OutputIdx];
8144 unsigned InputByteIdx;
8146 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8147 InputByteIdx = 0x80;
8149 // Cross lane is not allowed.
8150 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8152 InputByteIdx = InputIdx * EltSizeInBytes;
8153 // Index is an byte offset within the 128-bit lane.
8154 InputByteIdx &= 0xf;
8157 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8158 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8159 if (InputByteIdx != 0x80)
8164 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8166 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8167 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8168 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8171 // v8i16 shuffles - Prefer shuffles in the following order:
8172 // 1. [all] pshuflw, pshufhw, optional move
8173 // 2. [ssse3] 1 x pshufb
8174 // 3. [ssse3] 2 x pshufb + 1 x por
8175 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8177 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8178 SelectionDAG &DAG) {
8179 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8180 SDValue V1 = SVOp->getOperand(0);
8181 SDValue V2 = SVOp->getOperand(1);
8183 SmallVector<int, 8> MaskVals;
8185 // Determine if more than 1 of the words in each of the low and high quadwords
8186 // of the result come from the same quadword of one of the two inputs. Undef
8187 // mask values count as coming from any quadword, for better codegen.
8189 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8190 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8191 unsigned LoQuad[] = { 0, 0, 0, 0 };
8192 unsigned HiQuad[] = { 0, 0, 0, 0 };
8193 // Indices of quads used.
8194 std::bitset<4> InputQuads;
8195 for (unsigned i = 0; i < 8; ++i) {
8196 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8197 int EltIdx = SVOp->getMaskElt(i);
8198 MaskVals.push_back(EltIdx);
8207 InputQuads.set(EltIdx / 4);
8210 int BestLoQuad = -1;
8211 unsigned MaxQuad = 1;
8212 for (unsigned i = 0; i < 4; ++i) {
8213 if (LoQuad[i] > MaxQuad) {
8215 MaxQuad = LoQuad[i];
8219 int BestHiQuad = -1;
8221 for (unsigned i = 0; i < 4; ++i) {
8222 if (HiQuad[i] > MaxQuad) {
8224 MaxQuad = HiQuad[i];
8228 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8229 // of the two input vectors, shuffle them into one input vector so only a
8230 // single pshufb instruction is necessary. If there are more than 2 input
8231 // quads, disable the next transformation since it does not help SSSE3.
8232 bool V1Used = InputQuads[0] || InputQuads[1];
8233 bool V2Used = InputQuads[2] || InputQuads[3];
8234 if (Subtarget->hasSSSE3()) {
8235 if (InputQuads.count() == 2 && V1Used && V2Used) {
8236 BestLoQuad = InputQuads[0] ? 0 : 1;
8237 BestHiQuad = InputQuads[2] ? 2 : 3;
8239 if (InputQuads.count() > 2) {
8245 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8246 // the shuffle mask. If a quad is scored as -1, that means that it contains
8247 // words from all 4 input quadwords.
8249 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8251 BestLoQuad < 0 ? 0 : BestLoQuad,
8252 BestHiQuad < 0 ? 1 : BestHiQuad
8254 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8255 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8256 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8257 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8259 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8260 // source words for the shuffle, to aid later transformations.
8261 bool AllWordsInNewV = true;
8262 bool InOrder[2] = { true, true };
8263 for (unsigned i = 0; i != 8; ++i) {
8264 int idx = MaskVals[i];
8266 InOrder[i/4] = false;
8267 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8269 AllWordsInNewV = false;
8273 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8274 if (AllWordsInNewV) {
8275 for (int i = 0; i != 8; ++i) {
8276 int idx = MaskVals[i];
8279 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8280 if ((idx != i) && idx < 4)
8282 if ((idx != i) && idx > 3)
8291 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8292 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8293 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8294 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8295 unsigned TargetMask = 0;
8296 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8297 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8298 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8299 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8300 getShufflePSHUFLWImmediate(SVOp);
8301 V1 = NewV.getOperand(0);
8302 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8306 // Promote splats to a larger type which usually leads to more efficient code.
8307 // FIXME: Is this true if pshufb is available?
8308 if (SVOp->isSplat())
8309 return PromoteSplat(SVOp, DAG);
8311 // If we have SSSE3, and all words of the result are from 1 input vector,
8312 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8313 // is present, fall back to case 4.
8314 if (Subtarget->hasSSSE3()) {
8315 SmallVector<SDValue,16> pshufbMask;
8317 // If we have elements from both input vectors, set the high bit of the
8318 // shuffle mask element to zero out elements that come from V2 in the V1
8319 // mask, and elements that come from V1 in the V2 mask, so that the two
8320 // results can be OR'd together.
8321 bool TwoInputs = V1Used && V2Used;
8322 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8324 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8326 // Calculate the shuffle mask for the second input, shuffle it, and
8327 // OR it with the first shuffled input.
8328 CommuteVectorShuffleMask(MaskVals, 8);
8329 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8330 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8331 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8334 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8335 // and update MaskVals with new element order.
8336 std::bitset<8> InOrder;
8337 if (BestLoQuad >= 0) {
8338 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8339 for (int i = 0; i != 4; ++i) {
8340 int idx = MaskVals[i];
8343 } else if ((idx / 4) == BestLoQuad) {
8348 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8351 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8352 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8353 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8355 getShufflePSHUFLWImmediate(SVOp), DAG);
8359 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8360 // and update MaskVals with the new element order.
8361 if (BestHiQuad >= 0) {
8362 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8363 for (unsigned i = 4; i != 8; ++i) {
8364 int idx = MaskVals[i];
8367 } else if ((idx / 4) == BestHiQuad) {
8368 MaskV[i] = (idx & 3) + 4;
8372 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8375 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8376 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8377 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8379 getShufflePSHUFHWImmediate(SVOp), DAG);
8383 // In case BestHi & BestLo were both -1, which means each quadword has a word
8384 // from each of the four input quadwords, calculate the InOrder bitvector now
8385 // before falling through to the insert/extract cleanup.
8386 if (BestLoQuad == -1 && BestHiQuad == -1) {
8388 for (int i = 0; i != 8; ++i)
8389 if (MaskVals[i] < 0 || MaskVals[i] == i)
8393 // The other elements are put in the right place using pextrw and pinsrw.
8394 for (unsigned i = 0; i != 8; ++i) {
8397 int EltIdx = MaskVals[i];
8400 SDValue ExtOp = (EltIdx < 8) ?
8401 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8402 DAG.getIntPtrConstant(EltIdx)) :
8403 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8404 DAG.getIntPtrConstant(EltIdx - 8));
8405 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8406 DAG.getIntPtrConstant(i));
8411 /// \brief v16i16 shuffles
8413 /// FIXME: We only support generation of a single pshufb currently. We can
8414 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8415 /// well (e.g 2 x pshufb + 1 x por).
8417 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8418 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8419 SDValue V1 = SVOp->getOperand(0);
8420 SDValue V2 = SVOp->getOperand(1);
8423 if (V2.getOpcode() != ISD::UNDEF)
8426 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8427 return getPSHUFB(MaskVals, V1, dl, DAG);
8430 // v16i8 shuffles - Prefer shuffles in the following order:
8431 // 1. [ssse3] 1 x pshufb
8432 // 2. [ssse3] 2 x pshufb + 1 x por
8433 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8434 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8435 const X86Subtarget* Subtarget,
8436 SelectionDAG &DAG) {
8437 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8438 SDValue V1 = SVOp->getOperand(0);
8439 SDValue V2 = SVOp->getOperand(1);
8441 ArrayRef<int> MaskVals = SVOp->getMask();
8443 // Promote splats to a larger type which usually leads to more efficient code.
8444 // FIXME: Is this true if pshufb is available?
8445 if (SVOp->isSplat())
8446 return PromoteSplat(SVOp, DAG);
8448 // If we have SSSE3, case 1 is generated when all result bytes come from
8449 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8450 // present, fall back to case 3.
8452 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8453 if (Subtarget->hasSSSE3()) {
8454 SmallVector<SDValue,16> pshufbMask;
8456 // If all result elements are from one input vector, then only translate
8457 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8459 // Otherwise, we have elements from both input vectors, and must zero out
8460 // elements that come from V2 in the first mask, and V1 in the second mask
8461 // so that we can OR them together.
8462 for (unsigned i = 0; i != 16; ++i) {
8463 int EltIdx = MaskVals[i];
8464 if (EltIdx < 0 || EltIdx >= 16)
8466 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8468 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8469 DAG.getNode(ISD::BUILD_VECTOR, dl,
8470 MVT::v16i8, pshufbMask));
8472 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8473 // the 2nd operand if it's undefined or zero.
8474 if (V2.getOpcode() == ISD::UNDEF ||
8475 ISD::isBuildVectorAllZeros(V2.getNode()))
8478 // Calculate the shuffle mask for the second input, shuffle it, and
8479 // OR it with the first shuffled input.
8481 for (unsigned i = 0; i != 16; ++i) {
8482 int EltIdx = MaskVals[i];
8483 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8484 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8486 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8487 DAG.getNode(ISD::BUILD_VECTOR, dl,
8488 MVT::v16i8, pshufbMask));
8489 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8492 // No SSSE3 - Calculate in place words and then fix all out of place words
8493 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8494 // the 16 different words that comprise the two doublequadword input vectors.
8495 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8496 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8498 for (int i = 0; i != 8; ++i) {
8499 int Elt0 = MaskVals[i*2];
8500 int Elt1 = MaskVals[i*2+1];
8502 // This word of the result is all undef, skip it.
8503 if (Elt0 < 0 && Elt1 < 0)
8506 // This word of the result is already in the correct place, skip it.
8507 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8510 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8511 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8514 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8515 // using a single extract together, load it and store it.
8516 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8517 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8518 DAG.getIntPtrConstant(Elt1 / 2));
8519 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8520 DAG.getIntPtrConstant(i));
8524 // If Elt1 is defined, extract it from the appropriate source. If the
8525 // source byte is not also odd, shift the extracted word left 8 bits
8526 // otherwise clear the bottom 8 bits if we need to do an or.
8528 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8529 DAG.getIntPtrConstant(Elt1 / 2));
8530 if ((Elt1 & 1) == 0)
8531 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8533 TLI.getShiftAmountTy(InsElt.getValueType())));
8535 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8536 DAG.getConstant(0xFF00, MVT::i16));
8538 // If Elt0 is defined, extract it from the appropriate source. If the
8539 // source byte is not also even, shift the extracted word right 8 bits. If
8540 // Elt1 was also defined, OR the extracted values together before
8541 // inserting them in the result.
8543 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8544 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8545 if ((Elt0 & 1) != 0)
8546 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8548 TLI.getShiftAmountTy(InsElt0.getValueType())));
8550 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8551 DAG.getConstant(0x00FF, MVT::i16));
8552 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8555 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8556 DAG.getIntPtrConstant(i));
8558 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8561 // v32i8 shuffles - Translate to VPSHUFB if possible.
8563 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8564 const X86Subtarget *Subtarget,
8565 SelectionDAG &DAG) {
8566 MVT VT = SVOp->getSimpleValueType(0);
8567 SDValue V1 = SVOp->getOperand(0);
8568 SDValue V2 = SVOp->getOperand(1);
8570 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8572 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8573 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8574 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8576 // VPSHUFB may be generated if
8577 // (1) one of input vector is undefined or zeroinitializer.
8578 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8579 // And (2) the mask indexes don't cross the 128-bit lane.
8580 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8581 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8584 if (V1IsAllZero && !V2IsAllZero) {
8585 CommuteVectorShuffleMask(MaskVals, 32);
8588 return getPSHUFB(MaskVals, V1, dl, DAG);
8591 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8592 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8593 /// done when every pair / quad of shuffle mask elements point to elements in
8594 /// the right sequence. e.g.
8595 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8597 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8598 SelectionDAG &DAG) {
8599 MVT VT = SVOp->getSimpleValueType(0);
8601 unsigned NumElems = VT.getVectorNumElements();
8604 switch (VT.SimpleTy) {
8605 default: llvm_unreachable("Unexpected!");
8608 return SDValue(SVOp, 0);
8609 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8610 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8611 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8612 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8613 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8614 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8617 SmallVector<int, 8> MaskVec;
8618 for (unsigned i = 0; i != NumElems; i += Scale) {
8620 for (unsigned j = 0; j != Scale; ++j) {
8621 int EltIdx = SVOp->getMaskElt(i+j);
8625 StartIdx = (EltIdx / Scale);
8626 if (EltIdx != (int)(StartIdx*Scale + j))
8629 MaskVec.push_back(StartIdx);
8632 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8633 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8634 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8637 /// getVZextMovL - Return a zero-extending vector move low node.
8639 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8640 SDValue SrcOp, SelectionDAG &DAG,
8641 const X86Subtarget *Subtarget, SDLoc dl) {
8642 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8643 LoadSDNode *LD = nullptr;
8644 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8645 LD = dyn_cast<LoadSDNode>(SrcOp);
8647 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8649 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8650 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8651 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8652 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8653 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8655 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8656 return DAG.getNode(ISD::BITCAST, dl, VT,
8657 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8658 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8666 return DAG.getNode(ISD::BITCAST, dl, VT,
8667 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8668 DAG.getNode(ISD::BITCAST, dl,
8672 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8673 /// which could not be matched by any known target speficic shuffle
8675 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8677 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8678 if (NewOp.getNode())
8681 MVT VT = SVOp->getSimpleValueType(0);
8683 unsigned NumElems = VT.getVectorNumElements();
8684 unsigned NumLaneElems = NumElems / 2;
8687 MVT EltVT = VT.getVectorElementType();
8688 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8691 SmallVector<int, 16> Mask;
8692 for (unsigned l = 0; l < 2; ++l) {
8693 // Build a shuffle mask for the output, discovering on the fly which
8694 // input vectors to use as shuffle operands (recorded in InputUsed).
8695 // If building a suitable shuffle vector proves too hard, then bail
8696 // out with UseBuildVector set.
8697 bool UseBuildVector = false;
8698 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8699 unsigned LaneStart = l * NumLaneElems;
8700 for (unsigned i = 0; i != NumLaneElems; ++i) {
8701 // The mask element. This indexes into the input.
8702 int Idx = SVOp->getMaskElt(i+LaneStart);
8704 // the mask element does not index into any input vector.
8709 // The input vector this mask element indexes into.
8710 int Input = Idx / NumLaneElems;
8712 // Turn the index into an offset from the start of the input vector.
8713 Idx -= Input * NumLaneElems;
8715 // Find or create a shuffle vector operand to hold this input.
8717 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8718 if (InputUsed[OpNo] == Input)
8719 // This input vector is already an operand.
8721 if (InputUsed[OpNo] < 0) {
8722 // Create a new operand for this input vector.
8723 InputUsed[OpNo] = Input;
8728 if (OpNo >= array_lengthof(InputUsed)) {
8729 // More than two input vectors used! Give up on trying to create a
8730 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8731 UseBuildVector = true;
8735 // Add the mask index for the new shuffle vector.
8736 Mask.push_back(Idx + OpNo * NumLaneElems);
8739 if (UseBuildVector) {
8740 SmallVector<SDValue, 16> SVOps;
8741 for (unsigned i = 0; i != NumLaneElems; ++i) {
8742 // The mask element. This indexes into the input.
8743 int Idx = SVOp->getMaskElt(i+LaneStart);
8745 SVOps.push_back(DAG.getUNDEF(EltVT));
8749 // The input vector this mask element indexes into.
8750 int Input = Idx / NumElems;
8752 // Turn the index into an offset from the start of the input vector.
8753 Idx -= Input * NumElems;
8755 // Extract the vector element by hand.
8756 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8757 SVOp->getOperand(Input),
8758 DAG.getIntPtrConstant(Idx)));
8761 // Construct the output using a BUILD_VECTOR.
8762 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8763 } else if (InputUsed[0] < 0) {
8764 // No input vectors were used! The result is undefined.
8765 Output[l] = DAG.getUNDEF(NVT);
8767 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8768 (InputUsed[0] % 2) * NumLaneElems,
8770 // If only one input was used, use an undefined vector for the other.
8771 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8772 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8773 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8774 // At least one input vector was used. Create a new shuffle vector.
8775 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8781 // Concatenate the result back
8782 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8785 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8786 /// 4 elements, and match them with several different shuffle types.
8788 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8789 SDValue V1 = SVOp->getOperand(0);
8790 SDValue V2 = SVOp->getOperand(1);
8792 MVT VT = SVOp->getSimpleValueType(0);
8794 assert(VT.is128BitVector() && "Unsupported vector size");
8796 std::pair<int, int> Locs[4];
8797 int Mask1[] = { -1, -1, -1, -1 };
8798 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8802 for (unsigned i = 0; i != 4; ++i) {
8803 int Idx = PermMask[i];
8805 Locs[i] = std::make_pair(-1, -1);
8807 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8809 Locs[i] = std::make_pair(0, NumLo);
8813 Locs[i] = std::make_pair(1, NumHi);
8815 Mask1[2+NumHi] = Idx;
8821 if (NumLo <= 2 && NumHi <= 2) {
8822 // If no more than two elements come from either vector. This can be
8823 // implemented with two shuffles. First shuffle gather the elements.
8824 // The second shuffle, which takes the first shuffle as both of its
8825 // vector operands, put the elements into the right order.
8826 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8828 int Mask2[] = { -1, -1, -1, -1 };
8830 for (unsigned i = 0; i != 4; ++i)
8831 if (Locs[i].first != -1) {
8832 unsigned Idx = (i < 2) ? 0 : 4;
8833 Idx += Locs[i].first * 2 + Locs[i].second;
8837 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8840 if (NumLo == 3 || NumHi == 3) {
8841 // Otherwise, we must have three elements from one vector, call it X, and
8842 // one element from the other, call it Y. First, use a shufps to build an
8843 // intermediate vector with the one element from Y and the element from X
8844 // that will be in the same half in the final destination (the indexes don't
8845 // matter). Then, use a shufps to build the final vector, taking the half
8846 // containing the element from Y from the intermediate, and the other half
8849 // Normalize it so the 3 elements come from V1.
8850 CommuteVectorShuffleMask(PermMask, 4);
8854 // Find the element from V2.
8856 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8857 int Val = PermMask[HiIndex];
8864 Mask1[0] = PermMask[HiIndex];
8866 Mask1[2] = PermMask[HiIndex^1];
8868 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8871 Mask1[0] = PermMask[0];
8872 Mask1[1] = PermMask[1];
8873 Mask1[2] = HiIndex & 1 ? 6 : 4;
8874 Mask1[3] = HiIndex & 1 ? 4 : 6;
8875 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8878 Mask1[0] = HiIndex & 1 ? 2 : 0;
8879 Mask1[1] = HiIndex & 1 ? 0 : 2;
8880 Mask1[2] = PermMask[2];
8881 Mask1[3] = PermMask[3];
8886 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8889 // Break it into (shuffle shuffle_hi, shuffle_lo).
8890 int LoMask[] = { -1, -1, -1, -1 };
8891 int HiMask[] = { -1, -1, -1, -1 };
8893 int *MaskPtr = LoMask;
8894 unsigned MaskIdx = 0;
8897 for (unsigned i = 0; i != 4; ++i) {
8904 int Idx = PermMask[i];
8906 Locs[i] = std::make_pair(-1, -1);
8907 } else if (Idx < 4) {
8908 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8909 MaskPtr[LoIdx] = Idx;
8912 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8913 MaskPtr[HiIdx] = Idx;
8918 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8919 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8920 int MaskOps[] = { -1, -1, -1, -1 };
8921 for (unsigned i = 0; i != 4; ++i)
8922 if (Locs[i].first != -1)
8923 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8924 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8927 static bool MayFoldVectorLoad(SDValue V) {
8928 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8929 V = V.getOperand(0);
8931 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8932 V = V.getOperand(0);
8933 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8934 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8935 // BUILD_VECTOR (load), undef
8936 V = V.getOperand(0);
8938 return MayFoldLoad(V);
8942 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8943 MVT VT = Op.getSimpleValueType();
8945 // Canonizalize to v2f64.
8946 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8947 return DAG.getNode(ISD::BITCAST, dl, VT,
8948 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8953 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8955 SDValue V1 = Op.getOperand(0);
8956 SDValue V2 = Op.getOperand(1);
8957 MVT VT = Op.getSimpleValueType();
8959 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8961 if (HasSSE2 && VT == MVT::v2f64)
8962 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8964 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8965 return DAG.getNode(ISD::BITCAST, dl, VT,
8966 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8967 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8968 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8972 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8973 SDValue V1 = Op.getOperand(0);
8974 SDValue V2 = Op.getOperand(1);
8975 MVT VT = Op.getSimpleValueType();
8977 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8978 "unsupported shuffle type");
8980 if (V2.getOpcode() == ISD::UNDEF)
8984 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8988 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8989 SDValue V1 = Op.getOperand(0);
8990 SDValue V2 = Op.getOperand(1);
8991 MVT VT = Op.getSimpleValueType();
8992 unsigned NumElems = VT.getVectorNumElements();
8994 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8995 // operand of these instructions is only memory, so check if there's a
8996 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8998 bool CanFoldLoad = false;
9000 // Trivial case, when V2 comes from a load.
9001 if (MayFoldVectorLoad(V2))
9004 // When V1 is a load, it can be folded later into a store in isel, example:
9005 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9007 // (MOVLPSmr addr:$src1, VR128:$src2)
9008 // So, recognize this potential and also use MOVLPS or MOVLPD
9009 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9012 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9014 if (HasSSE2 && NumElems == 2)
9015 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9018 // If we don't care about the second element, proceed to use movss.
9019 if (SVOp->getMaskElt(1) != -1)
9020 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9023 // movl and movlp will both match v2i64, but v2i64 is never matched by
9024 // movl earlier because we make it strict to avoid messing with the movlp load
9025 // folding logic (see the code above getMOVLP call). Match it here then,
9026 // this is horrible, but will stay like this until we move all shuffle
9027 // matching to x86 specific nodes. Note that for the 1st condition all
9028 // types are matched with movsd.
9030 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9031 // as to remove this logic from here, as much as possible
9032 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9033 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9034 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9037 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9039 // Invert the operand order and use SHUFPS to match it.
9040 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9041 getShuffleSHUFImmediate(SVOp), DAG);
9044 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9045 SelectionDAG &DAG) {
9047 MVT VT = Load->getSimpleValueType(0);
9048 MVT EVT = VT.getVectorElementType();
9049 SDValue Addr = Load->getOperand(1);
9050 SDValue NewAddr = DAG.getNode(
9051 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9052 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9055 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9056 DAG.getMachineFunction().getMachineMemOperand(
9057 Load->getMemOperand(), 0, EVT.getStoreSize()));
9061 // It is only safe to call this function if isINSERTPSMask is true for
9062 // this shufflevector mask.
9063 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9064 SelectionDAG &DAG) {
9065 // Generate an insertps instruction when inserting an f32 from memory onto a
9066 // v4f32 or when copying a member from one v4f32 to another.
9067 // We also use it for transferring i32 from one register to another,
9068 // since it simply copies the same bits.
9069 // If we're transferring an i32 from memory to a specific element in a
9070 // register, we output a generic DAG that will match the PINSRD
9072 MVT VT = SVOp->getSimpleValueType(0);
9073 MVT EVT = VT.getVectorElementType();
9074 SDValue V1 = SVOp->getOperand(0);
9075 SDValue V2 = SVOp->getOperand(1);
9076 auto Mask = SVOp->getMask();
9077 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9078 "unsupported vector type for insertps/pinsrd");
9080 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9081 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9082 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9090 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9093 // If we have 1 element from each vector, we have to check if we're
9094 // changing V1's element's place. If so, we're done. Otherwise, we
9095 // should assume we're changing V2's element's place and behave
9097 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9098 assert(DestIndex <= INT32_MAX && "truncated destination index");
9099 if (FromV1 == FromV2 &&
9100 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9104 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9107 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9108 "More than one element from V1 and from V2, or no elements from one "
9109 "of the vectors. This case should not have returned true from "
9114 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9117 // Get an index into the source vector in the range [0,4) (the mask is
9118 // in the range [0,8) because it can address V1 and V2)
9119 unsigned SrcIndex = Mask[DestIndex] % 4;
9120 if (MayFoldLoad(From)) {
9121 // Trivial case, when From comes from a load and is only used by the
9122 // shuffle. Make it use insertps from the vector that we need from that
9125 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9126 if (!NewLoad.getNode())
9129 if (EVT == MVT::f32) {
9130 // Create this as a scalar to vector to match the instruction pattern.
9131 SDValue LoadScalarToVector =
9132 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9133 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9134 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9136 } else { // EVT == MVT::i32
9137 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9138 // instruction, to match the PINSRD instruction, which loads an i32 to a
9139 // certain vector element.
9140 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9141 DAG.getConstant(DestIndex, MVT::i32));
9145 // Vector-element-to-vector
9146 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9147 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9150 // Reduce a vector shuffle to zext.
9151 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9152 SelectionDAG &DAG) {
9153 // PMOVZX is only available from SSE41.
9154 if (!Subtarget->hasSSE41())
9157 MVT VT = Op.getSimpleValueType();
9159 // Only AVX2 support 256-bit vector integer extending.
9160 if (!Subtarget->hasInt256() && VT.is256BitVector())
9163 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9165 SDValue V1 = Op.getOperand(0);
9166 SDValue V2 = Op.getOperand(1);
9167 unsigned NumElems = VT.getVectorNumElements();
9169 // Extending is an unary operation and the element type of the source vector
9170 // won't be equal to or larger than i64.
9171 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9172 VT.getVectorElementType() == MVT::i64)
9175 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9176 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9177 while ((1U << Shift) < NumElems) {
9178 if (SVOp->getMaskElt(1U << Shift) == 1)
9181 // The maximal ratio is 8, i.e. from i8 to i64.
9186 // Check the shuffle mask.
9187 unsigned Mask = (1U << Shift) - 1;
9188 for (unsigned i = 0; i != NumElems; ++i) {
9189 int EltIdx = SVOp->getMaskElt(i);
9190 if ((i & Mask) != 0 && EltIdx != -1)
9192 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9196 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9197 MVT NeVT = MVT::getIntegerVT(NBits);
9198 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9200 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9203 // Simplify the operand as it's prepared to be fed into shuffle.
9204 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9205 if (V1.getOpcode() == ISD::BITCAST &&
9206 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9207 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9208 V1.getOperand(0).getOperand(0)
9209 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9210 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9211 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9212 ConstantSDNode *CIdx =
9213 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9214 // If it's foldable, i.e. normal load with single use, we will let code
9215 // selection to fold it. Otherwise, we will short the conversion sequence.
9216 if (CIdx && CIdx->getZExtValue() == 0 &&
9217 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9218 MVT FullVT = V.getSimpleValueType();
9219 MVT V1VT = V1.getSimpleValueType();
9220 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9221 // The "ext_vec_elt" node is wider than the result node.
9222 // In this case we should extract subvector from V.
9223 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9224 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9225 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9226 FullVT.getVectorNumElements()/Ratio);
9227 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9228 DAG.getIntPtrConstant(0));
9230 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9234 return DAG.getNode(ISD::BITCAST, DL, VT,
9235 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9238 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9239 SelectionDAG &DAG) {
9240 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9241 MVT VT = Op.getSimpleValueType();
9243 SDValue V1 = Op.getOperand(0);
9244 SDValue V2 = Op.getOperand(1);
9246 if (isZeroShuffle(SVOp))
9247 return getZeroVector(VT, Subtarget, DAG, dl);
9249 // Handle splat operations
9250 if (SVOp->isSplat()) {
9251 // Use vbroadcast whenever the splat comes from a foldable load
9252 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9253 if (Broadcast.getNode())
9257 // Check integer expanding shuffles.
9258 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9259 if (NewOp.getNode())
9262 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9264 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9266 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9267 if (NewOp.getNode())
9268 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9269 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9270 // FIXME: Figure out a cleaner way to do this.
9271 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9272 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9273 if (NewOp.getNode()) {
9274 MVT NewVT = NewOp.getSimpleValueType();
9275 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9276 NewVT, true, false))
9277 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9280 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9281 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9282 if (NewOp.getNode()) {
9283 MVT NewVT = NewOp.getSimpleValueType();
9284 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9285 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9294 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9295 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9296 SDValue V1 = Op.getOperand(0);
9297 SDValue V2 = Op.getOperand(1);
9298 MVT VT = Op.getSimpleValueType();
9300 unsigned NumElems = VT.getVectorNumElements();
9301 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9302 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9303 bool V1IsSplat = false;
9304 bool V2IsSplat = false;
9305 bool HasSSE2 = Subtarget->hasSSE2();
9306 bool HasFp256 = Subtarget->hasFp256();
9307 bool HasInt256 = Subtarget->hasInt256();
9308 MachineFunction &MF = DAG.getMachineFunction();
9309 bool OptForSize = MF.getFunction()->getAttributes().
9310 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9312 // Check if we should use the experimental vector shuffle lowering. If so,
9313 // delegate completely to that code path.
9314 if (ExperimentalVectorShuffleLowering)
9315 return lowerVectorShuffle(Op, Subtarget, DAG);
9317 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9319 if (V1IsUndef && V2IsUndef)
9320 return DAG.getUNDEF(VT);
9322 // When we create a shuffle node we put the UNDEF node to second operand,
9323 // but in some cases the first operand may be transformed to UNDEF.
9324 // In this case we should just commute the node.
9326 return DAG.getCommutedVectorShuffle(*SVOp);
9328 // Vector shuffle lowering takes 3 steps:
9330 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9331 // narrowing and commutation of operands should be handled.
9332 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9334 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9335 // so the shuffle can be broken into other shuffles and the legalizer can
9336 // try the lowering again.
9338 // The general idea is that no vector_shuffle operation should be left to
9339 // be matched during isel, all of them must be converted to a target specific
9342 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9343 // narrowing and commutation of operands should be handled. The actual code
9344 // doesn't include all of those, work in progress...
9345 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9346 if (NewOp.getNode())
9349 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9351 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9352 // unpckh_undef). Only use pshufd if speed is more important than size.
9353 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9354 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9355 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9356 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9358 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9359 V2IsUndef && MayFoldVectorLoad(V1))
9360 return getMOVDDup(Op, dl, V1, DAG);
9362 if (isMOVHLPS_v_undef_Mask(M, VT))
9363 return getMOVHighToLow(Op, dl, DAG);
9365 // Use to match splats
9366 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9367 (VT == MVT::v2f64 || VT == MVT::v2i64))
9368 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9370 if (isPSHUFDMask(M, VT)) {
9371 // The actual implementation will match the mask in the if above and then
9372 // during isel it can match several different instructions, not only pshufd
9373 // as its name says, sad but true, emulate the behavior for now...
9374 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9375 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9377 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9379 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9380 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9382 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9383 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9386 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9390 if (isPALIGNRMask(M, VT, Subtarget))
9391 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9392 getShufflePALIGNRImmediate(SVOp),
9395 // Check if this can be converted into a logical shift.
9396 bool isLeft = false;
9399 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9400 if (isShift && ShVal.hasOneUse()) {
9401 // If the shifted value has multiple uses, it may be cheaper to use
9402 // v_set0 + movlhps or movhlps, etc.
9403 MVT EltVT = VT.getVectorElementType();
9404 ShAmt *= EltVT.getSizeInBits();
9405 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9408 if (isMOVLMask(M, VT)) {
9409 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9410 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9411 if (!isMOVLPMask(M, VT)) {
9412 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9413 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9415 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9416 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9420 // FIXME: fold these into legal mask.
9421 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9422 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9424 if (isMOVHLPSMask(M, VT))
9425 return getMOVHighToLow(Op, dl, DAG);
9427 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9428 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9430 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9431 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9433 if (isMOVLPMask(M, VT))
9434 return getMOVLP(Op, dl, DAG, HasSSE2);
9436 if (ShouldXformToMOVHLPS(M, VT) ||
9437 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9438 return DAG.getCommutedVectorShuffle(*SVOp);
9441 // No better options. Use a vshldq / vsrldq.
9442 MVT EltVT = VT.getVectorElementType();
9443 ShAmt *= EltVT.getSizeInBits();
9444 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9447 bool Commuted = false;
9448 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9449 // 1,1,1,1 -> v8i16 though.
9450 BitVector UndefElements;
9451 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9452 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9454 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9455 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9458 // Canonicalize the splat or undef, if present, to be on the RHS.
9459 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9460 CommuteVectorShuffleMask(M, NumElems);
9462 std::swap(V1IsSplat, V2IsSplat);
9466 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9467 // Shuffling low element of v1 into undef, just return v1.
9470 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9471 // the instruction selector will not match, so get a canonical MOVL with
9472 // swapped operands to undo the commute.
9473 return getMOVL(DAG, dl, VT, V2, V1);
9476 if (isUNPCKLMask(M, VT, HasInt256))
9477 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9479 if (isUNPCKHMask(M, VT, HasInt256))
9480 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9483 // Normalize mask so all entries that point to V2 points to its first
9484 // element then try to match unpck{h|l} again. If match, return a
9485 // new vector_shuffle with the corrected mask.p
9486 SmallVector<int, 8> NewMask(M.begin(), M.end());
9487 NormalizeMask(NewMask, NumElems);
9488 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9489 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9490 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9491 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9495 // Commute is back and try unpck* again.
9496 // FIXME: this seems wrong.
9497 CommuteVectorShuffleMask(M, NumElems);
9499 std::swap(V1IsSplat, V2IsSplat);
9501 if (isUNPCKLMask(M, VT, HasInt256))
9502 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9504 if (isUNPCKHMask(M, VT, HasInt256))
9505 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9508 // Normalize the node to match x86 shuffle ops if needed
9509 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9510 return DAG.getCommutedVectorShuffle(*SVOp);
9512 // The checks below are all present in isShuffleMaskLegal, but they are
9513 // inlined here right now to enable us to directly emit target specific
9514 // nodes, and remove one by one until they don't return Op anymore.
9516 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9517 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9518 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9519 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9522 if (isPSHUFHWMask(M, VT, HasInt256))
9523 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9524 getShufflePSHUFHWImmediate(SVOp),
9527 if (isPSHUFLWMask(M, VT, HasInt256))
9528 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9529 getShufflePSHUFLWImmediate(SVOp),
9533 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9535 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9537 if (isSHUFPMask(M, VT))
9538 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9539 getShuffleSHUFImmediate(SVOp), DAG);
9541 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9542 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9543 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9544 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9546 //===--------------------------------------------------------------------===//
9547 // Generate target specific nodes for 128 or 256-bit shuffles only
9548 // supported in the AVX instruction set.
9551 // Handle VMOVDDUPY permutations
9552 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9553 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9555 // Handle VPERMILPS/D* permutations
9556 if (isVPERMILPMask(M, VT)) {
9557 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9558 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9559 getShuffleSHUFImmediate(SVOp), DAG);
9560 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9561 getShuffleSHUFImmediate(SVOp), DAG);
9565 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9566 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9567 Idx*(NumElems/2), DAG, dl);
9569 // Handle VPERM2F128/VPERM2I128 permutations
9570 if (isVPERM2X128Mask(M, VT, HasFp256))
9571 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9572 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9574 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9575 return getINSERTPS(SVOp, dl, DAG);
9578 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9579 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9581 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9582 VT.is512BitVector()) {
9583 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9584 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9585 SmallVector<SDValue, 16> permclMask;
9586 for (unsigned i = 0; i != NumElems; ++i) {
9587 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9590 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9592 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9593 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9594 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9595 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9596 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9599 //===--------------------------------------------------------------------===//
9600 // Since no target specific shuffle was selected for this generic one,
9601 // lower it into other known shuffles. FIXME: this isn't true yet, but
9602 // this is the plan.
9605 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9606 if (VT == MVT::v8i16) {
9607 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9608 if (NewOp.getNode())
9612 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9613 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9614 if (NewOp.getNode())
9618 if (VT == MVT::v16i8) {
9619 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9620 if (NewOp.getNode())
9624 if (VT == MVT::v32i8) {
9625 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9626 if (NewOp.getNode())
9630 // Handle all 128-bit wide vectors with 4 elements, and match them with
9631 // several different shuffle types.
9632 if (NumElems == 4 && VT.is128BitVector())
9633 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9635 // Handle general 256-bit shuffles
9636 if (VT.is256BitVector())
9637 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9642 // This function assumes its argument is a BUILD_VECTOR of constants or
9643 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9645 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9646 unsigned &MaskValue) {
9648 unsigned NumElems = BuildVector->getNumOperands();
9649 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9650 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9651 unsigned NumElemsInLane = NumElems / NumLanes;
9653 // Blend for v16i16 should be symetric for the both lanes.
9654 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9655 SDValue EltCond = BuildVector->getOperand(i);
9656 SDValue SndLaneEltCond =
9657 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9659 int Lane1Cond = -1, Lane2Cond = -1;
9660 if (isa<ConstantSDNode>(EltCond))
9661 Lane1Cond = !isZero(EltCond);
9662 if (isa<ConstantSDNode>(SndLaneEltCond))
9663 Lane2Cond = !isZero(SndLaneEltCond);
9665 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9666 // Lane1Cond != 0, means we want the first argument.
9667 // Lane1Cond == 0, means we want the second argument.
9668 // The encoding of this argument is 0 for the first argument, 1
9669 // for the second. Therefore, invert the condition.
9670 MaskValue |= !Lane1Cond << i;
9671 else if (Lane1Cond < 0)
9672 MaskValue |= !Lane2Cond << i;
9679 // Try to lower a vselect node into a simple blend instruction.
9680 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9681 SelectionDAG &DAG) {
9682 SDValue Cond = Op.getOperand(0);
9683 SDValue LHS = Op.getOperand(1);
9684 SDValue RHS = Op.getOperand(2);
9686 MVT VT = Op.getSimpleValueType();
9687 MVT EltVT = VT.getVectorElementType();
9688 unsigned NumElems = VT.getVectorNumElements();
9690 // There is no blend with immediate in AVX-512.
9691 if (VT.is512BitVector())
9694 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9696 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9699 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9702 // Check the mask for BLEND and build the value.
9703 unsigned MaskValue = 0;
9704 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9707 // Convert i32 vectors to floating point if it is not AVX2.
9708 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9710 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9711 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9713 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9714 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9717 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9718 DAG.getConstant(MaskValue, MVT::i32));
9719 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9722 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9723 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9724 if (BlendOp.getNode())
9727 // Some types for vselect were previously set to Expand, not Legal or
9728 // Custom. Return an empty SDValue so we fall-through to Expand, after
9729 // the Custom lowering phase.
9730 MVT VT = Op.getSimpleValueType();
9731 switch (VT.SimpleTy) {
9739 // We couldn't create a "Blend with immediate" node.
9740 // This node should still be legal, but we'll have to emit a blendv*
9745 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9746 MVT VT = Op.getSimpleValueType();
9749 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9752 if (VT.getSizeInBits() == 8) {
9753 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9754 Op.getOperand(0), Op.getOperand(1));
9755 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9756 DAG.getValueType(VT));
9757 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9760 if (VT.getSizeInBits() == 16) {
9761 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9762 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9764 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9765 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9766 DAG.getNode(ISD::BITCAST, dl,
9770 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9771 Op.getOperand(0), Op.getOperand(1));
9772 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9773 DAG.getValueType(VT));
9774 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9777 if (VT == MVT::f32) {
9778 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9779 // the result back to FR32 register. It's only worth matching if the
9780 // result has a single use which is a store or a bitcast to i32. And in
9781 // the case of a store, it's not worth it if the index is a constant 0,
9782 // because a MOVSSmr can be used instead, which is smaller and faster.
9783 if (!Op.hasOneUse())
9785 SDNode *User = *Op.getNode()->use_begin();
9786 if ((User->getOpcode() != ISD::STORE ||
9787 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9788 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9789 (User->getOpcode() != ISD::BITCAST ||
9790 User->getValueType(0) != MVT::i32))
9792 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9793 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9796 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9799 if (VT == MVT::i32 || VT == MVT::i64) {
9800 // ExtractPS/pextrq works with constant index.
9801 if (isa<ConstantSDNode>(Op.getOperand(1)))
9807 /// Extract one bit from mask vector, like v16i1 or v8i1.
9808 /// AVX-512 feature.
9810 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9811 SDValue Vec = Op.getOperand(0);
9813 MVT VecVT = Vec.getSimpleValueType();
9814 SDValue Idx = Op.getOperand(1);
9815 MVT EltVT = Op.getSimpleValueType();
9817 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9819 // variable index can't be handled in mask registers,
9820 // extend vector to VR512
9821 if (!isa<ConstantSDNode>(Idx)) {
9822 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9823 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9824 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9825 ExtVT.getVectorElementType(), Ext, Idx);
9826 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9829 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9830 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9831 unsigned MaxSift = rc->getSize()*8 - 1;
9832 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9833 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9834 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9835 DAG.getConstant(MaxSift, MVT::i8));
9836 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9837 DAG.getIntPtrConstant(0));
9841 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9842 SelectionDAG &DAG) const {
9844 SDValue Vec = Op.getOperand(0);
9845 MVT VecVT = Vec.getSimpleValueType();
9846 SDValue Idx = Op.getOperand(1);
9848 if (Op.getSimpleValueType() == MVT::i1)
9849 return ExtractBitFromMaskVector(Op, DAG);
9851 if (!isa<ConstantSDNode>(Idx)) {
9852 if (VecVT.is512BitVector() ||
9853 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9854 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9857 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9858 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9859 MaskEltVT.getSizeInBits());
9861 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9862 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9863 getZeroVector(MaskVT, Subtarget, DAG, dl),
9864 Idx, DAG.getConstant(0, getPointerTy()));
9865 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9866 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9867 Perm, DAG.getConstant(0, getPointerTy()));
9872 // If this is a 256-bit vector result, first extract the 128-bit vector and
9873 // then extract the element from the 128-bit vector.
9874 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9876 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9877 // Get the 128-bit vector.
9878 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9879 MVT EltVT = VecVT.getVectorElementType();
9881 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9883 //if (IdxVal >= NumElems/2)
9884 // IdxVal -= NumElems/2;
9885 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9886 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9887 DAG.getConstant(IdxVal, MVT::i32));
9890 assert(VecVT.is128BitVector() && "Unexpected vector length");
9892 if (Subtarget->hasSSE41()) {
9893 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9898 MVT VT = Op.getSimpleValueType();
9899 // TODO: handle v16i8.
9900 if (VT.getSizeInBits() == 16) {
9901 SDValue Vec = Op.getOperand(0);
9902 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9904 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9905 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9906 DAG.getNode(ISD::BITCAST, dl,
9909 // Transform it so it match pextrw which produces a 32-bit result.
9910 MVT EltVT = MVT::i32;
9911 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9912 Op.getOperand(0), Op.getOperand(1));
9913 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9914 DAG.getValueType(VT));
9915 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9918 if (VT.getSizeInBits() == 32) {
9919 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9923 // SHUFPS the element to the lowest double word, then movss.
9924 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9925 MVT VVT = Op.getOperand(0).getSimpleValueType();
9926 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9927 DAG.getUNDEF(VVT), Mask);
9928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9929 DAG.getIntPtrConstant(0));
9932 if (VT.getSizeInBits() == 64) {
9933 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9934 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9935 // to match extract_elt for f64.
9936 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9940 // UNPCKHPD the element to the lowest double word, then movsd.
9941 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9942 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9943 int Mask[2] = { 1, -1 };
9944 MVT VVT = Op.getOperand(0).getSimpleValueType();
9945 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9946 DAG.getUNDEF(VVT), Mask);
9947 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9948 DAG.getIntPtrConstant(0));
9954 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9955 MVT VT = Op.getSimpleValueType();
9956 MVT EltVT = VT.getVectorElementType();
9959 SDValue N0 = Op.getOperand(0);
9960 SDValue N1 = Op.getOperand(1);
9961 SDValue N2 = Op.getOperand(2);
9963 if (!VT.is128BitVector())
9966 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9967 isa<ConstantSDNode>(N2)) {
9969 if (VT == MVT::v8i16)
9970 Opc = X86ISD::PINSRW;
9971 else if (VT == MVT::v16i8)
9972 Opc = X86ISD::PINSRB;
9974 Opc = X86ISD::PINSRB;
9976 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9978 if (N1.getValueType() != MVT::i32)
9979 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9980 if (N2.getValueType() != MVT::i32)
9981 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9982 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9985 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9986 // Bits [7:6] of the constant are the source select. This will always be
9987 // zero here. The DAG Combiner may combine an extract_elt index into these
9988 // bits. For example (insert (extract, 3), 2) could be matched by putting
9989 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9990 // Bits [5:4] of the constant are the destination select. This is the
9991 // value of the incoming immediate.
9992 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9993 // combine either bitwise AND or insert of float 0.0 to set these bits.
9994 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9995 // Create this as a scalar to vector..
9996 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9997 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10000 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10001 // PINSR* works with constant index.
10007 /// Insert one bit to mask vector, like v16i1 or v8i1.
10008 /// AVX-512 feature.
10010 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10012 SDValue Vec = Op.getOperand(0);
10013 SDValue Elt = Op.getOperand(1);
10014 SDValue Idx = Op.getOperand(2);
10015 MVT VecVT = Vec.getSimpleValueType();
10017 if (!isa<ConstantSDNode>(Idx)) {
10018 // Non constant index. Extend source and destination,
10019 // insert element and then truncate the result.
10020 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10021 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10022 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10023 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10024 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10025 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10028 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10029 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10030 if (Vec.getOpcode() == ISD::UNDEF)
10031 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10032 DAG.getConstant(IdxVal, MVT::i8));
10033 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10034 unsigned MaxSift = rc->getSize()*8 - 1;
10035 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10036 DAG.getConstant(MaxSift, MVT::i8));
10037 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10038 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10039 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10042 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10043 MVT VT = Op.getSimpleValueType();
10044 MVT EltVT = VT.getVectorElementType();
10046 if (EltVT == MVT::i1)
10047 return InsertBitToMaskVector(Op, DAG);
10050 SDValue N0 = Op.getOperand(0);
10051 SDValue N1 = Op.getOperand(1);
10052 SDValue N2 = Op.getOperand(2);
10054 // If this is a 256-bit vector result, first extract the 128-bit vector,
10055 // insert the element into the extracted half and then place it back.
10056 if (VT.is256BitVector() || VT.is512BitVector()) {
10057 if (!isa<ConstantSDNode>(N2))
10060 // Get the desired 128-bit vector half.
10061 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10062 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10064 // Insert the element into the desired half.
10065 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10066 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10068 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10069 DAG.getConstant(IdxIn128, MVT::i32));
10071 // Insert the changed part back to the 256-bit vector
10072 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10075 if (Subtarget->hasSSE41())
10076 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10078 if (EltVT == MVT::i8)
10081 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10082 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10083 // as its second argument.
10084 if (N1.getValueType() != MVT::i32)
10085 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10086 if (N2.getValueType() != MVT::i32)
10087 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10088 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10093 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10095 MVT OpVT = Op.getSimpleValueType();
10097 // If this is a 256-bit vector result, first insert into a 128-bit
10098 // vector and then insert into the 256-bit vector.
10099 if (!OpVT.is128BitVector()) {
10100 // Insert into a 128-bit vector.
10101 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10102 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10103 OpVT.getVectorNumElements() / SizeFactor);
10105 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10107 // Insert the 128-bit vector.
10108 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10111 if (OpVT == MVT::v1i64 &&
10112 Op.getOperand(0).getValueType() == MVT::i64)
10113 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10115 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10116 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10117 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10118 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10121 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10122 // a simple subregister reference or explicit instructions to grab
10123 // upper bits of a vector.
10124 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10125 SelectionDAG &DAG) {
10127 SDValue In = Op.getOperand(0);
10128 SDValue Idx = Op.getOperand(1);
10129 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10130 MVT ResVT = Op.getSimpleValueType();
10131 MVT InVT = In.getSimpleValueType();
10133 if (Subtarget->hasFp256()) {
10134 if (ResVT.is128BitVector() &&
10135 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10136 isa<ConstantSDNode>(Idx)) {
10137 return Extract128BitVector(In, IdxVal, DAG, dl);
10139 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10140 isa<ConstantSDNode>(Idx)) {
10141 return Extract256BitVector(In, IdxVal, DAG, dl);
10147 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10148 // simple superregister reference or explicit instructions to insert
10149 // the upper bits of a vector.
10150 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10151 SelectionDAG &DAG) {
10152 if (Subtarget->hasFp256()) {
10153 SDLoc dl(Op.getNode());
10154 SDValue Vec = Op.getNode()->getOperand(0);
10155 SDValue SubVec = Op.getNode()->getOperand(1);
10156 SDValue Idx = Op.getNode()->getOperand(2);
10158 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10159 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10160 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10161 isa<ConstantSDNode>(Idx)) {
10162 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10163 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10166 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10167 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10168 isa<ConstantSDNode>(Idx)) {
10169 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10170 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10176 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10177 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10178 // one of the above mentioned nodes. It has to be wrapped because otherwise
10179 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10180 // be used to form addressing mode. These wrapped nodes will be selected
10183 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10184 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10186 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10187 // global base reg.
10188 unsigned char OpFlag = 0;
10189 unsigned WrapperKind = X86ISD::Wrapper;
10190 CodeModel::Model M = DAG.getTarget().getCodeModel();
10192 if (Subtarget->isPICStyleRIPRel() &&
10193 (M == CodeModel::Small || M == CodeModel::Kernel))
10194 WrapperKind = X86ISD::WrapperRIP;
10195 else if (Subtarget->isPICStyleGOT())
10196 OpFlag = X86II::MO_GOTOFF;
10197 else if (Subtarget->isPICStyleStubPIC())
10198 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10200 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10201 CP->getAlignment(),
10202 CP->getOffset(), OpFlag);
10204 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10205 // With PIC, the address is actually $g + Offset.
10207 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10208 DAG.getNode(X86ISD::GlobalBaseReg,
10209 SDLoc(), getPointerTy()),
10216 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10217 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10219 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10220 // global base reg.
10221 unsigned char OpFlag = 0;
10222 unsigned WrapperKind = X86ISD::Wrapper;
10223 CodeModel::Model M = DAG.getTarget().getCodeModel();
10225 if (Subtarget->isPICStyleRIPRel() &&
10226 (M == CodeModel::Small || M == CodeModel::Kernel))
10227 WrapperKind = X86ISD::WrapperRIP;
10228 else if (Subtarget->isPICStyleGOT())
10229 OpFlag = X86II::MO_GOTOFF;
10230 else if (Subtarget->isPICStyleStubPIC())
10231 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10233 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10236 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10238 // With PIC, the address is actually $g + Offset.
10240 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10241 DAG.getNode(X86ISD::GlobalBaseReg,
10242 SDLoc(), getPointerTy()),
10249 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10250 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10252 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10253 // global base reg.
10254 unsigned char OpFlag = 0;
10255 unsigned WrapperKind = X86ISD::Wrapper;
10256 CodeModel::Model M = DAG.getTarget().getCodeModel();
10258 if (Subtarget->isPICStyleRIPRel() &&
10259 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10260 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10261 OpFlag = X86II::MO_GOTPCREL;
10262 WrapperKind = X86ISD::WrapperRIP;
10263 } else if (Subtarget->isPICStyleGOT()) {
10264 OpFlag = X86II::MO_GOT;
10265 } else if (Subtarget->isPICStyleStubPIC()) {
10266 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10267 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10268 OpFlag = X86II::MO_DARWIN_NONLAZY;
10271 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10274 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10276 // With PIC, the address is actually $g + Offset.
10277 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10278 !Subtarget->is64Bit()) {
10279 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10280 DAG.getNode(X86ISD::GlobalBaseReg,
10281 SDLoc(), getPointerTy()),
10285 // For symbols that require a load from a stub to get the address, emit the
10287 if (isGlobalStubReference(OpFlag))
10288 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10289 MachinePointerInfo::getGOT(), false, false, false, 0);
10295 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10296 // Create the TargetBlockAddressAddress node.
10297 unsigned char OpFlags =
10298 Subtarget->ClassifyBlockAddressReference();
10299 CodeModel::Model M = DAG.getTarget().getCodeModel();
10300 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10301 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10303 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10306 if (Subtarget->isPICStyleRIPRel() &&
10307 (M == CodeModel::Small || M == CodeModel::Kernel))
10308 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10310 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10312 // With PIC, the address is actually $g + Offset.
10313 if (isGlobalRelativeToPICBase(OpFlags)) {
10314 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10315 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10323 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10324 int64_t Offset, SelectionDAG &DAG) const {
10325 // Create the TargetGlobalAddress node, folding in the constant
10326 // offset if it is legal.
10327 unsigned char OpFlags =
10328 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10329 CodeModel::Model M = DAG.getTarget().getCodeModel();
10331 if (OpFlags == X86II::MO_NO_FLAG &&
10332 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10333 // A direct static reference to a global.
10334 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10337 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10340 if (Subtarget->isPICStyleRIPRel() &&
10341 (M == CodeModel::Small || M == CodeModel::Kernel))
10342 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10344 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10346 // With PIC, the address is actually $g + Offset.
10347 if (isGlobalRelativeToPICBase(OpFlags)) {
10348 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10349 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10353 // For globals that require a load from a stub to get the address, emit the
10355 if (isGlobalStubReference(OpFlags))
10356 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10357 MachinePointerInfo::getGOT(), false, false, false, 0);
10359 // If there was a non-zero offset that we didn't fold, create an explicit
10360 // addition for it.
10362 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10363 DAG.getConstant(Offset, getPointerTy()));
10369 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10370 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10371 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10372 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10376 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10377 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10378 unsigned char OperandFlags, bool LocalDynamic = false) {
10379 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10380 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10382 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10383 GA->getValueType(0),
10387 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10391 SDValue Ops[] = { Chain, TGA, *InFlag };
10392 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10394 SDValue Ops[] = { Chain, TGA };
10395 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10398 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10399 MFI->setAdjustsStack(true);
10401 SDValue Flag = Chain.getValue(1);
10402 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10405 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10407 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10410 SDLoc dl(GA); // ? function entry point might be better
10411 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10412 DAG.getNode(X86ISD::GlobalBaseReg,
10413 SDLoc(), PtrVT), InFlag);
10414 InFlag = Chain.getValue(1);
10416 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10419 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10421 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10423 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10424 X86::RAX, X86II::MO_TLSGD);
10427 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10433 // Get the start address of the TLS block for this module.
10434 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10435 .getInfo<X86MachineFunctionInfo>();
10436 MFI->incNumLocalDynamicTLSAccesses();
10440 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10441 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10444 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10445 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10446 InFlag = Chain.getValue(1);
10447 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10448 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10451 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10455 unsigned char OperandFlags = X86II::MO_DTPOFF;
10456 unsigned WrapperKind = X86ISD::Wrapper;
10457 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10458 GA->getValueType(0),
10459 GA->getOffset(), OperandFlags);
10460 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10462 // Add x@dtpoff with the base.
10463 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10466 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10467 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10468 const EVT PtrVT, TLSModel::Model model,
10469 bool is64Bit, bool isPIC) {
10472 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10473 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10474 is64Bit ? 257 : 256));
10476 SDValue ThreadPointer =
10477 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10478 MachinePointerInfo(Ptr), false, false, false, 0);
10480 unsigned char OperandFlags = 0;
10481 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10483 unsigned WrapperKind = X86ISD::Wrapper;
10484 if (model == TLSModel::LocalExec) {
10485 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10486 } else if (model == TLSModel::InitialExec) {
10488 OperandFlags = X86II::MO_GOTTPOFF;
10489 WrapperKind = X86ISD::WrapperRIP;
10491 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10494 llvm_unreachable("Unexpected model");
10497 // emit "addl x@ntpoff,%eax" (local exec)
10498 // or "addl x@indntpoff,%eax" (initial exec)
10499 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10501 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10502 GA->getOffset(), OperandFlags);
10503 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10505 if (model == TLSModel::InitialExec) {
10506 if (isPIC && !is64Bit) {
10507 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10508 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10512 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10513 MachinePointerInfo::getGOT(), false, false, false, 0);
10516 // The address of the thread local variable is the add of the thread
10517 // pointer with the offset of the variable.
10518 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10522 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10524 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10525 const GlobalValue *GV = GA->getGlobal();
10527 if (Subtarget->isTargetELF()) {
10528 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10531 case TLSModel::GeneralDynamic:
10532 if (Subtarget->is64Bit())
10533 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10534 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10535 case TLSModel::LocalDynamic:
10536 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10537 Subtarget->is64Bit());
10538 case TLSModel::InitialExec:
10539 case TLSModel::LocalExec:
10540 return LowerToTLSExecModel(
10541 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10542 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10544 llvm_unreachable("Unknown TLS model.");
10547 if (Subtarget->isTargetDarwin()) {
10548 // Darwin only has one model of TLS. Lower to that.
10549 unsigned char OpFlag = 0;
10550 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10551 X86ISD::WrapperRIP : X86ISD::Wrapper;
10553 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10554 // global base reg.
10555 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10556 !Subtarget->is64Bit();
10558 OpFlag = X86II::MO_TLVP_PIC_BASE;
10560 OpFlag = X86II::MO_TLVP;
10562 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10563 GA->getValueType(0),
10564 GA->getOffset(), OpFlag);
10565 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10567 // With PIC32, the address is actually $g + Offset.
10569 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10570 DAG.getNode(X86ISD::GlobalBaseReg,
10571 SDLoc(), getPointerTy()),
10574 // Lowering the machine isd will make sure everything is in the right
10576 SDValue Chain = DAG.getEntryNode();
10577 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10578 SDValue Args[] = { Chain, Offset };
10579 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10581 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10582 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10583 MFI->setAdjustsStack(true);
10585 // And our return value (tls address) is in the standard call return value
10587 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10588 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10589 Chain.getValue(1));
10592 if (Subtarget->isTargetKnownWindowsMSVC() ||
10593 Subtarget->isTargetWindowsGNU()) {
10594 // Just use the implicit TLS architecture
10595 // Need to generate someting similar to:
10596 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10598 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10599 // mov rcx, qword [rdx+rcx*8]
10600 // mov eax, .tls$:tlsvar
10601 // [rax+rcx] contains the address
10602 // Windows 64bit: gs:0x58
10603 // Windows 32bit: fs:__tls_array
10606 SDValue Chain = DAG.getEntryNode();
10608 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10609 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10610 // use its literal value of 0x2C.
10611 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10612 ? Type::getInt8PtrTy(*DAG.getContext(),
10614 : Type::getInt32PtrTy(*DAG.getContext(),
10618 Subtarget->is64Bit()
10619 ? DAG.getIntPtrConstant(0x58)
10620 : (Subtarget->isTargetWindowsGNU()
10621 ? DAG.getIntPtrConstant(0x2C)
10622 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10624 SDValue ThreadPointer =
10625 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10626 MachinePointerInfo(Ptr), false, false, false, 0);
10628 // Load the _tls_index variable
10629 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10630 if (Subtarget->is64Bit())
10631 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10632 IDX, MachinePointerInfo(), MVT::i32,
10635 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10636 false, false, false, 0);
10638 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10640 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10642 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10643 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10644 false, false, false, 0);
10646 // Get the offset of start of .tls section
10647 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10648 GA->getValueType(0),
10649 GA->getOffset(), X86II::MO_SECREL);
10650 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10652 // The address of the thread local variable is the add of the thread
10653 // pointer with the offset of the variable.
10654 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10657 llvm_unreachable("TLS not implemented for this target.");
10660 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10661 /// and take a 2 x i32 value to shift plus a shift amount.
10662 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10663 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10664 MVT VT = Op.getSimpleValueType();
10665 unsigned VTBits = VT.getSizeInBits();
10667 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10668 SDValue ShOpLo = Op.getOperand(0);
10669 SDValue ShOpHi = Op.getOperand(1);
10670 SDValue ShAmt = Op.getOperand(2);
10671 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10672 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10674 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10675 DAG.getConstant(VTBits - 1, MVT::i8));
10676 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10677 DAG.getConstant(VTBits - 1, MVT::i8))
10678 : DAG.getConstant(0, VT);
10680 SDValue Tmp2, Tmp3;
10681 if (Op.getOpcode() == ISD::SHL_PARTS) {
10682 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10683 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10685 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10686 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10689 // If the shift amount is larger or equal than the width of a part we can't
10690 // rely on the results of shld/shrd. Insert a test and select the appropriate
10691 // values for large shift amounts.
10692 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10693 DAG.getConstant(VTBits, MVT::i8));
10694 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10695 AndNode, DAG.getConstant(0, MVT::i8));
10698 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10699 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10700 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10702 if (Op.getOpcode() == ISD::SHL_PARTS) {
10703 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10704 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10706 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10707 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10710 SDValue Ops[2] = { Lo, Hi };
10711 return DAG.getMergeValues(Ops, dl);
10714 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10715 SelectionDAG &DAG) const {
10716 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10718 if (SrcVT.isVector())
10721 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10722 "Unknown SINT_TO_FP to lower!");
10724 // These are really Legal; return the operand so the caller accepts it as
10726 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10728 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10729 Subtarget->is64Bit()) {
10734 unsigned Size = SrcVT.getSizeInBits()/8;
10735 MachineFunction &MF = DAG.getMachineFunction();
10736 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10737 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10738 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10740 MachinePointerInfo::getFixedStack(SSFI),
10742 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10745 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10747 SelectionDAG &DAG) const {
10751 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10753 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10755 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10757 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10759 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10760 MachineMemOperand *MMO;
10762 int SSFI = FI->getIndex();
10764 DAG.getMachineFunction()
10765 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10766 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10768 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10769 StackSlot = StackSlot.getOperand(1);
10771 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10772 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10774 Tys, Ops, SrcVT, MMO);
10777 Chain = Result.getValue(1);
10778 SDValue InFlag = Result.getValue(2);
10780 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10781 // shouldn't be necessary except that RFP cannot be live across
10782 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10783 MachineFunction &MF = DAG.getMachineFunction();
10784 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10785 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10786 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10787 Tys = DAG.getVTList(MVT::Other);
10789 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10791 MachineMemOperand *MMO =
10792 DAG.getMachineFunction()
10793 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10794 MachineMemOperand::MOStore, SSFISize, SSFISize);
10796 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10797 Ops, Op.getValueType(), MMO);
10798 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10799 MachinePointerInfo::getFixedStack(SSFI),
10800 false, false, false, 0);
10806 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10807 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10808 SelectionDAG &DAG) const {
10809 // This algorithm is not obvious. Here it is what we're trying to output:
10812 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10813 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10815 haddpd %xmm0, %xmm0
10817 pshufd $0x4e, %xmm0, %xmm1
10823 LLVMContext *Context = DAG.getContext();
10825 // Build some magic constants.
10826 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10827 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10828 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10830 SmallVector<Constant*,2> CV1;
10832 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10833 APInt(64, 0x4330000000000000ULL))));
10835 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10836 APInt(64, 0x4530000000000000ULL))));
10837 Constant *C1 = ConstantVector::get(CV1);
10838 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10840 // Load the 64-bit value into an XMM register.
10841 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10843 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10844 MachinePointerInfo::getConstantPool(),
10845 false, false, false, 16);
10846 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10847 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10850 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10851 MachinePointerInfo::getConstantPool(),
10852 false, false, false, 16);
10853 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10854 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10857 if (Subtarget->hasSSE3()) {
10858 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10859 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10861 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10862 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10864 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10865 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10869 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10870 DAG.getIntPtrConstant(0));
10873 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10874 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10875 SelectionDAG &DAG) const {
10877 // FP constant to bias correct the final result.
10878 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10881 // Load the 32-bit value into an XMM register.
10882 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10885 // Zero out the upper parts of the register.
10886 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10888 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10889 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10890 DAG.getIntPtrConstant(0));
10892 // Or the load with the bias.
10893 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10894 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10895 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10896 MVT::v2f64, Load)),
10897 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10898 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10899 MVT::v2f64, Bias)));
10900 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10901 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10902 DAG.getIntPtrConstant(0));
10904 // Subtract the bias.
10905 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10907 // Handle final rounding.
10908 EVT DestVT = Op.getValueType();
10910 if (DestVT.bitsLT(MVT::f64))
10911 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10912 DAG.getIntPtrConstant(0));
10913 if (DestVT.bitsGT(MVT::f64))
10914 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10916 // Handle final rounding.
10920 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10921 SelectionDAG &DAG) const {
10922 SDValue N0 = Op.getOperand(0);
10923 MVT SVT = N0.getSimpleValueType();
10926 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10927 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10928 "Custom UINT_TO_FP is not supported!");
10930 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10931 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10932 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10935 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10936 SelectionDAG &DAG) const {
10937 SDValue N0 = Op.getOperand(0);
10940 if (Op.getValueType().isVector())
10941 return lowerUINT_TO_FP_vec(Op, DAG);
10943 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10944 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10945 // the optimization here.
10946 if (DAG.SignBitIsZero(N0))
10947 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10949 MVT SrcVT = N0.getSimpleValueType();
10950 MVT DstVT = Op.getSimpleValueType();
10951 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10952 return LowerUINT_TO_FP_i64(Op, DAG);
10953 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10954 return LowerUINT_TO_FP_i32(Op, DAG);
10955 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10958 // Make a 64-bit buffer, and use it to build an FILD.
10959 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10960 if (SrcVT == MVT::i32) {
10961 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10962 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10963 getPointerTy(), StackSlot, WordOff);
10964 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10965 StackSlot, MachinePointerInfo(),
10967 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10968 OffsetSlot, MachinePointerInfo(),
10970 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10974 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10975 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10976 StackSlot, MachinePointerInfo(),
10978 // For i64 source, we need to add the appropriate power of 2 if the input
10979 // was negative. This is the same as the optimization in
10980 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10981 // we must be careful to do the computation in x87 extended precision, not
10982 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10983 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10984 MachineMemOperand *MMO =
10985 DAG.getMachineFunction()
10986 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10987 MachineMemOperand::MOLoad, 8, 8);
10989 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10990 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10991 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10994 APInt FF(32, 0x5F800000ULL);
10996 // Check whether the sign bit is set.
10997 SDValue SignSet = DAG.getSetCC(dl,
10998 getSetCCResultType(*DAG.getContext(), MVT::i64),
10999 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11002 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11003 SDValue FudgePtr = DAG.getConstantPool(
11004 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11007 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11008 SDValue Zero = DAG.getIntPtrConstant(0);
11009 SDValue Four = DAG.getIntPtrConstant(4);
11010 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11012 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11014 // Load the value out, extending it from f32 to f80.
11015 // FIXME: Avoid the extend by constructing the right constant pool?
11016 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11017 FudgePtr, MachinePointerInfo::getConstantPool(),
11018 MVT::f32, false, false, 4);
11019 // Extend everything to 80 bits to force it to be done on x87.
11020 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11021 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11024 std::pair<SDValue,SDValue>
11025 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11026 bool IsSigned, bool IsReplace) const {
11029 EVT DstTy = Op.getValueType();
11031 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11032 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11036 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11037 DstTy.getSimpleVT() >= MVT::i16 &&
11038 "Unknown FP_TO_INT to lower!");
11040 // These are really Legal.
11041 if (DstTy == MVT::i32 &&
11042 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11043 return std::make_pair(SDValue(), SDValue());
11044 if (Subtarget->is64Bit() &&
11045 DstTy == MVT::i64 &&
11046 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11047 return std::make_pair(SDValue(), SDValue());
11049 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11050 // stack slot, or into the FTOL runtime function.
11051 MachineFunction &MF = DAG.getMachineFunction();
11052 unsigned MemSize = DstTy.getSizeInBits()/8;
11053 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11054 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11057 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11058 Opc = X86ISD::WIN_FTOL;
11060 switch (DstTy.getSimpleVT().SimpleTy) {
11061 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11062 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11063 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11064 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11067 SDValue Chain = DAG.getEntryNode();
11068 SDValue Value = Op.getOperand(0);
11069 EVT TheVT = Op.getOperand(0).getValueType();
11070 // FIXME This causes a redundant load/store if the SSE-class value is already
11071 // in memory, such as if it is on the callstack.
11072 if (isScalarFPTypeInSSEReg(TheVT)) {
11073 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11074 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11075 MachinePointerInfo::getFixedStack(SSFI),
11077 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11079 Chain, StackSlot, DAG.getValueType(TheVT)
11082 MachineMemOperand *MMO =
11083 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11084 MachineMemOperand::MOLoad, MemSize, MemSize);
11085 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11086 Chain = Value.getValue(1);
11087 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11088 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11091 MachineMemOperand *MMO =
11092 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11093 MachineMemOperand::MOStore, MemSize, MemSize);
11095 if (Opc != X86ISD::WIN_FTOL) {
11096 // Build the FP_TO_INT*_IN_MEM
11097 SDValue Ops[] = { Chain, Value, StackSlot };
11098 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11100 return std::make_pair(FIST, StackSlot);
11102 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11103 DAG.getVTList(MVT::Other, MVT::Glue),
11105 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11106 MVT::i32, ftol.getValue(1));
11107 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11108 MVT::i32, eax.getValue(2));
11109 SDValue Ops[] = { eax, edx };
11110 SDValue pair = IsReplace
11111 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11112 : DAG.getMergeValues(Ops, DL);
11113 return std::make_pair(pair, SDValue());
11117 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11118 const X86Subtarget *Subtarget) {
11119 MVT VT = Op->getSimpleValueType(0);
11120 SDValue In = Op->getOperand(0);
11121 MVT InVT = In.getSimpleValueType();
11124 // Optimize vectors in AVX mode:
11127 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11128 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11129 // Concat upper and lower parts.
11132 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11133 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11134 // Concat upper and lower parts.
11137 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11138 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11139 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11142 if (Subtarget->hasInt256())
11143 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11145 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11146 SDValue Undef = DAG.getUNDEF(InVT);
11147 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11148 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11149 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11151 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11152 VT.getVectorNumElements()/2);
11154 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11155 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11157 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11160 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11161 SelectionDAG &DAG) {
11162 MVT VT = Op->getSimpleValueType(0);
11163 SDValue In = Op->getOperand(0);
11164 MVT InVT = In.getSimpleValueType();
11166 unsigned int NumElts = VT.getVectorNumElements();
11167 if (NumElts != 8 && NumElts != 16)
11170 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11171 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11173 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11175 // Now we have only mask extension
11176 assert(InVT.getVectorElementType() == MVT::i1);
11177 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11178 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11179 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11180 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11181 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11182 MachinePointerInfo::getConstantPool(),
11183 false, false, false, Alignment);
11185 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11186 if (VT.is512BitVector())
11188 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11191 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11192 SelectionDAG &DAG) {
11193 if (Subtarget->hasFp256()) {
11194 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11202 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11203 SelectionDAG &DAG) {
11205 MVT VT = Op.getSimpleValueType();
11206 SDValue In = Op.getOperand(0);
11207 MVT SVT = In.getSimpleValueType();
11209 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11210 return LowerZERO_EXTEND_AVX512(Op, DAG);
11212 if (Subtarget->hasFp256()) {
11213 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11218 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11219 VT.getVectorNumElements() != SVT.getVectorNumElements());
11223 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11225 MVT VT = Op.getSimpleValueType();
11226 SDValue In = Op.getOperand(0);
11227 MVT InVT = In.getSimpleValueType();
11229 if (VT == MVT::i1) {
11230 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11231 "Invalid scalar TRUNCATE operation");
11232 if (InVT == MVT::i32)
11234 if (InVT.getSizeInBits() == 64)
11235 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11236 else if (InVT.getSizeInBits() < 32)
11237 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11238 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11240 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11241 "Invalid TRUNCATE operation");
11243 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11244 if (VT.getVectorElementType().getSizeInBits() >=8)
11245 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11247 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11248 unsigned NumElts = InVT.getVectorNumElements();
11249 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11250 if (InVT.getSizeInBits() < 512) {
11251 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11252 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11256 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11257 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11258 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11259 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11260 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11261 MachinePointerInfo::getConstantPool(),
11262 false, false, false, Alignment);
11263 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11264 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11265 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11268 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11269 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11270 if (Subtarget->hasInt256()) {
11271 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11272 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11273 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11275 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11276 DAG.getIntPtrConstant(0));
11279 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11280 DAG.getIntPtrConstant(0));
11281 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11282 DAG.getIntPtrConstant(2));
11283 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11284 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11285 static const int ShufMask[] = {0, 2, 4, 6};
11286 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11289 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11290 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11291 if (Subtarget->hasInt256()) {
11292 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11294 SmallVector<SDValue,32> pshufbMask;
11295 for (unsigned i = 0; i < 2; ++i) {
11296 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11297 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11298 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11299 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11300 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11301 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11302 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11303 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11304 for (unsigned j = 0; j < 8; ++j)
11305 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11307 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11308 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11309 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11311 static const int ShufMask[] = {0, 2, -1, -1};
11312 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11314 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11315 DAG.getIntPtrConstant(0));
11316 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11319 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11320 DAG.getIntPtrConstant(0));
11322 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11323 DAG.getIntPtrConstant(4));
11325 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11326 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11328 // The PSHUFB mask:
11329 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11330 -1, -1, -1, -1, -1, -1, -1, -1};
11332 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11333 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11334 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11336 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11337 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11339 // The MOVLHPS Mask:
11340 static const int ShufMask2[] = {0, 1, 4, 5};
11341 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11342 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11345 // Handle truncation of V256 to V128 using shuffles.
11346 if (!VT.is128BitVector() || !InVT.is256BitVector())
11349 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11351 unsigned NumElems = VT.getVectorNumElements();
11352 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11354 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11355 // Prepare truncation shuffle mask
11356 for (unsigned i = 0; i != NumElems; ++i)
11357 MaskVec[i] = i * 2;
11358 SDValue V = DAG.getVectorShuffle(NVT, DL,
11359 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11360 DAG.getUNDEF(NVT), &MaskVec[0]);
11361 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11362 DAG.getIntPtrConstant(0));
11365 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11366 SelectionDAG &DAG) const {
11367 assert(!Op.getSimpleValueType().isVector());
11369 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11370 /*IsSigned=*/ true, /*IsReplace=*/ false);
11371 SDValue FIST = Vals.first, StackSlot = Vals.second;
11372 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11373 if (!FIST.getNode()) return Op;
11375 if (StackSlot.getNode())
11376 // Load the result.
11377 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11378 FIST, StackSlot, MachinePointerInfo(),
11379 false, false, false, 0);
11381 // The node is the result.
11385 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11386 SelectionDAG &DAG) const {
11387 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11388 /*IsSigned=*/ false, /*IsReplace=*/ false);
11389 SDValue FIST = Vals.first, StackSlot = Vals.second;
11390 assert(FIST.getNode() && "Unexpected failure");
11392 if (StackSlot.getNode())
11393 // Load the result.
11394 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11395 FIST, StackSlot, MachinePointerInfo(),
11396 false, false, false, 0);
11398 // The node is the result.
11402 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11404 MVT VT = Op.getSimpleValueType();
11405 SDValue In = Op.getOperand(0);
11406 MVT SVT = In.getSimpleValueType();
11408 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11410 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11411 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11412 In, DAG.getUNDEF(SVT)));
11415 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11416 LLVMContext *Context = DAG.getContext();
11418 MVT VT = Op.getSimpleValueType();
11420 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11421 if (VT.isVector()) {
11422 EltVT = VT.getVectorElementType();
11423 NumElts = VT.getVectorNumElements();
11426 if (EltVT == MVT::f64)
11427 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11428 APInt(64, ~(1ULL << 63))));
11430 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11431 APInt(32, ~(1U << 31))));
11432 C = ConstantVector::getSplat(NumElts, C);
11433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11434 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11435 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11436 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11437 MachinePointerInfo::getConstantPool(),
11438 false, false, false, Alignment);
11439 if (VT.isVector()) {
11440 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11441 return DAG.getNode(ISD::BITCAST, dl, VT,
11442 DAG.getNode(ISD::AND, dl, ANDVT,
11443 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11445 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11447 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11450 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11451 LLVMContext *Context = DAG.getContext();
11453 MVT VT = Op.getSimpleValueType();
11455 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11456 if (VT.isVector()) {
11457 EltVT = VT.getVectorElementType();
11458 NumElts = VT.getVectorNumElements();
11461 if (EltVT == MVT::f64)
11462 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11463 APInt(64, 1ULL << 63)));
11465 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11466 APInt(32, 1U << 31)));
11467 C = ConstantVector::getSplat(NumElts, C);
11468 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11469 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11470 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11471 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11472 MachinePointerInfo::getConstantPool(),
11473 false, false, false, Alignment);
11474 if (VT.isVector()) {
11475 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11476 return DAG.getNode(ISD::BITCAST, dl, VT,
11477 DAG.getNode(ISD::XOR, dl, XORVT,
11478 DAG.getNode(ISD::BITCAST, dl, XORVT,
11480 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11483 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11486 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11487 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11488 LLVMContext *Context = DAG.getContext();
11489 SDValue Op0 = Op.getOperand(0);
11490 SDValue Op1 = Op.getOperand(1);
11492 MVT VT = Op.getSimpleValueType();
11493 MVT SrcVT = Op1.getSimpleValueType();
11495 // If second operand is smaller, extend it first.
11496 if (SrcVT.bitsLT(VT)) {
11497 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11500 // And if it is bigger, shrink it first.
11501 if (SrcVT.bitsGT(VT)) {
11502 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11506 // At this point the operands and the result should have the same
11507 // type, and that won't be f80 since that is not custom lowered.
11509 // First get the sign bit of second operand.
11510 SmallVector<Constant*,4> CV;
11511 if (SrcVT == MVT::f64) {
11512 const fltSemantics &Sem = APFloat::IEEEdouble;
11513 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11514 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11516 const fltSemantics &Sem = APFloat::IEEEsingle;
11517 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11518 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11519 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11520 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11522 Constant *C = ConstantVector::get(CV);
11523 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11524 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11525 MachinePointerInfo::getConstantPool(),
11526 false, false, false, 16);
11527 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11529 // Shift sign bit right or left if the two operands have different types.
11530 if (SrcVT.bitsGT(VT)) {
11531 // Op0 is MVT::f32, Op1 is MVT::f64.
11532 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11533 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11534 DAG.getConstant(32, MVT::i32));
11535 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11536 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11537 DAG.getIntPtrConstant(0));
11540 // Clear first operand sign bit.
11542 if (VT == MVT::f64) {
11543 const fltSemantics &Sem = APFloat::IEEEdouble;
11544 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11545 APInt(64, ~(1ULL << 63)))));
11546 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11548 const fltSemantics &Sem = APFloat::IEEEsingle;
11549 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11550 APInt(32, ~(1U << 31)))));
11551 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11552 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11553 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11555 C = ConstantVector::get(CV);
11556 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11557 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11558 MachinePointerInfo::getConstantPool(),
11559 false, false, false, 16);
11560 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11562 // Or the value with the sign bit.
11563 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11566 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11567 SDValue N0 = Op.getOperand(0);
11569 MVT VT = Op.getSimpleValueType();
11571 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11572 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11573 DAG.getConstant(1, VT));
11574 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11577 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11579 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11580 SelectionDAG &DAG) {
11581 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11583 if (!Subtarget->hasSSE41())
11586 if (!Op->hasOneUse())
11589 SDNode *N = Op.getNode();
11592 SmallVector<SDValue, 8> Opnds;
11593 DenseMap<SDValue, unsigned> VecInMap;
11594 SmallVector<SDValue, 8> VecIns;
11595 EVT VT = MVT::Other;
11597 // Recognize a special case where a vector is casted into wide integer to
11599 Opnds.push_back(N->getOperand(0));
11600 Opnds.push_back(N->getOperand(1));
11602 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11603 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11604 // BFS traverse all OR'd operands.
11605 if (I->getOpcode() == ISD::OR) {
11606 Opnds.push_back(I->getOperand(0));
11607 Opnds.push_back(I->getOperand(1));
11608 // Re-evaluate the number of nodes to be traversed.
11609 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11613 // Quit if a non-EXTRACT_VECTOR_ELT
11614 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11617 // Quit if without a constant index.
11618 SDValue Idx = I->getOperand(1);
11619 if (!isa<ConstantSDNode>(Idx))
11622 SDValue ExtractedFromVec = I->getOperand(0);
11623 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11624 if (M == VecInMap.end()) {
11625 VT = ExtractedFromVec.getValueType();
11626 // Quit if not 128/256-bit vector.
11627 if (!VT.is128BitVector() && !VT.is256BitVector())
11629 // Quit if not the same type.
11630 if (VecInMap.begin() != VecInMap.end() &&
11631 VT != VecInMap.begin()->first.getValueType())
11633 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11634 VecIns.push_back(ExtractedFromVec);
11636 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11639 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11640 "Not extracted from 128-/256-bit vector.");
11642 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11644 for (DenseMap<SDValue, unsigned>::const_iterator
11645 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11646 // Quit if not all elements are used.
11647 if (I->second != FullMask)
11651 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11653 // Cast all vectors into TestVT for PTEST.
11654 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11655 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11657 // If more than one full vectors are evaluated, OR them first before PTEST.
11658 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11659 // Each iteration will OR 2 nodes and append the result until there is only
11660 // 1 node left, i.e. the final OR'd value of all vectors.
11661 SDValue LHS = VecIns[Slot];
11662 SDValue RHS = VecIns[Slot + 1];
11663 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11666 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11667 VecIns.back(), VecIns.back());
11670 /// \brief return true if \c Op has a use that doesn't just read flags.
11671 static bool hasNonFlagsUse(SDValue Op) {
11672 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11674 SDNode *User = *UI;
11675 unsigned UOpNo = UI.getOperandNo();
11676 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11677 // Look pass truncate.
11678 UOpNo = User->use_begin().getOperandNo();
11679 User = *User->use_begin();
11682 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11683 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11689 /// Emit nodes that will be selected as "test Op0,Op0", or something
11691 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11692 SelectionDAG &DAG) const {
11693 if (Op.getValueType() == MVT::i1)
11694 // KORTEST instruction should be selected
11695 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11696 DAG.getConstant(0, Op.getValueType()));
11698 // CF and OF aren't always set the way we want. Determine which
11699 // of these we need.
11700 bool NeedCF = false;
11701 bool NeedOF = false;
11704 case X86::COND_A: case X86::COND_AE:
11705 case X86::COND_B: case X86::COND_BE:
11708 case X86::COND_G: case X86::COND_GE:
11709 case X86::COND_L: case X86::COND_LE:
11710 case X86::COND_O: case X86::COND_NO: {
11711 // Check if we really need to set the
11712 // Overflow flag. If NoSignedWrap is present
11713 // that is not actually needed.
11714 switch (Op->getOpcode()) {
11719 const BinaryWithFlagsSDNode *BinNode =
11720 cast<BinaryWithFlagsSDNode>(Op.getNode());
11721 if (BinNode->hasNoSignedWrap())
11731 // See if we can use the EFLAGS value from the operand instead of
11732 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11733 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11734 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11735 // Emit a CMP with 0, which is the TEST pattern.
11736 //if (Op.getValueType() == MVT::i1)
11737 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11738 // DAG.getConstant(0, MVT::i1));
11739 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11740 DAG.getConstant(0, Op.getValueType()));
11742 unsigned Opcode = 0;
11743 unsigned NumOperands = 0;
11745 // Truncate operations may prevent the merge of the SETCC instruction
11746 // and the arithmetic instruction before it. Attempt to truncate the operands
11747 // of the arithmetic instruction and use a reduced bit-width instruction.
11748 bool NeedTruncation = false;
11749 SDValue ArithOp = Op;
11750 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11751 SDValue Arith = Op->getOperand(0);
11752 // Both the trunc and the arithmetic op need to have one user each.
11753 if (Arith->hasOneUse())
11754 switch (Arith.getOpcode()) {
11761 NeedTruncation = true;
11767 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11768 // which may be the result of a CAST. We use the variable 'Op', which is the
11769 // non-casted variable when we check for possible users.
11770 switch (ArithOp.getOpcode()) {
11772 // Due to an isel shortcoming, be conservative if this add is likely to be
11773 // selected as part of a load-modify-store instruction. When the root node
11774 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11775 // uses of other nodes in the match, such as the ADD in this case. This
11776 // leads to the ADD being left around and reselected, with the result being
11777 // two adds in the output. Alas, even if none our users are stores, that
11778 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11779 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11780 // climbing the DAG back to the root, and it doesn't seem to be worth the
11782 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11783 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11784 if (UI->getOpcode() != ISD::CopyToReg &&
11785 UI->getOpcode() != ISD::SETCC &&
11786 UI->getOpcode() != ISD::STORE)
11789 if (ConstantSDNode *C =
11790 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11791 // An add of one will be selected as an INC.
11792 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11793 Opcode = X86ISD::INC;
11798 // An add of negative one (subtract of one) will be selected as a DEC.
11799 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11800 Opcode = X86ISD::DEC;
11806 // Otherwise use a regular EFLAGS-setting add.
11807 Opcode = X86ISD::ADD;
11812 // If we have a constant logical shift that's only used in a comparison
11813 // against zero turn it into an equivalent AND. This allows turning it into
11814 // a TEST instruction later.
11815 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11816 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11817 EVT VT = Op.getValueType();
11818 unsigned BitWidth = VT.getSizeInBits();
11819 unsigned ShAmt = Op->getConstantOperandVal(1);
11820 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11822 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11823 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11824 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11825 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11827 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11828 DAG.getConstant(Mask, VT));
11829 DAG.ReplaceAllUsesWith(Op, New);
11835 // If the primary and result isn't used, don't bother using X86ISD::AND,
11836 // because a TEST instruction will be better.
11837 if (!hasNonFlagsUse(Op))
11843 // Due to the ISEL shortcoming noted above, be conservative if this op is
11844 // likely to be selected as part of a load-modify-store instruction.
11845 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11846 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11847 if (UI->getOpcode() == ISD::STORE)
11850 // Otherwise use a regular EFLAGS-setting instruction.
11851 switch (ArithOp.getOpcode()) {
11852 default: llvm_unreachable("unexpected operator!");
11853 case ISD::SUB: Opcode = X86ISD::SUB; break;
11854 case ISD::XOR: Opcode = X86ISD::XOR; break;
11855 case ISD::AND: Opcode = X86ISD::AND; break;
11857 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11858 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11859 if (EFLAGS.getNode())
11862 Opcode = X86ISD::OR;
11876 return SDValue(Op.getNode(), 1);
11882 // If we found that truncation is beneficial, perform the truncation and
11884 if (NeedTruncation) {
11885 EVT VT = Op.getValueType();
11886 SDValue WideVal = Op->getOperand(0);
11887 EVT WideVT = WideVal.getValueType();
11888 unsigned ConvertedOp = 0;
11889 // Use a target machine opcode to prevent further DAGCombine
11890 // optimizations that may separate the arithmetic operations
11891 // from the setcc node.
11892 switch (WideVal.getOpcode()) {
11894 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11895 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11896 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11897 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11898 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11903 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11904 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11905 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11906 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11912 // Emit a CMP with 0, which is the TEST pattern.
11913 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11914 DAG.getConstant(0, Op.getValueType()));
11916 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11917 SmallVector<SDValue, 4> Ops;
11918 for (unsigned i = 0; i != NumOperands; ++i)
11919 Ops.push_back(Op.getOperand(i));
11921 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11922 DAG.ReplaceAllUsesWith(Op, New);
11923 return SDValue(New.getNode(), 1);
11926 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11928 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11929 SDLoc dl, SelectionDAG &DAG) const {
11930 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11931 if (C->getAPIntValue() == 0)
11932 return EmitTest(Op0, X86CC, dl, DAG);
11934 if (Op0.getValueType() == MVT::i1)
11935 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11938 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11939 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11940 // Do the comparison at i32 if it's smaller, besides the Atom case.
11941 // This avoids subregister aliasing issues. Keep the smaller reference
11942 // if we're optimizing for size, however, as that'll allow better folding
11943 // of memory operations.
11944 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11945 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11946 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11947 !Subtarget->isAtom()) {
11948 unsigned ExtendOp =
11949 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11950 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11951 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11953 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11954 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11955 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11957 return SDValue(Sub.getNode(), 1);
11959 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11962 /// Convert a comparison if required by the subtarget.
11963 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11964 SelectionDAG &DAG) const {
11965 // If the subtarget does not support the FUCOMI instruction, floating-point
11966 // comparisons have to be converted.
11967 if (Subtarget->hasCMov() ||
11968 Cmp.getOpcode() != X86ISD::CMP ||
11969 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11970 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11973 // The instruction selector will select an FUCOM instruction instead of
11974 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11975 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11976 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11978 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11979 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11980 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11981 DAG.getConstant(8, MVT::i8));
11982 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11983 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11986 static bool isAllOnes(SDValue V) {
11987 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11988 return C && C->isAllOnesValue();
11991 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11992 /// if it's possible.
11993 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11994 SDLoc dl, SelectionDAG &DAG) const {
11995 SDValue Op0 = And.getOperand(0);
11996 SDValue Op1 = And.getOperand(1);
11997 if (Op0.getOpcode() == ISD::TRUNCATE)
11998 Op0 = Op0.getOperand(0);
11999 if (Op1.getOpcode() == ISD::TRUNCATE)
12000 Op1 = Op1.getOperand(0);
12003 if (Op1.getOpcode() == ISD::SHL)
12004 std::swap(Op0, Op1);
12005 if (Op0.getOpcode() == ISD::SHL) {
12006 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12007 if (And00C->getZExtValue() == 1) {
12008 // If we looked past a truncate, check that it's only truncating away
12010 unsigned BitWidth = Op0.getValueSizeInBits();
12011 unsigned AndBitWidth = And.getValueSizeInBits();
12012 if (BitWidth > AndBitWidth) {
12014 DAG.computeKnownBits(Op0, Zeros, Ones);
12015 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12019 RHS = Op0.getOperand(1);
12021 } else if (Op1.getOpcode() == ISD::Constant) {
12022 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12023 uint64_t AndRHSVal = AndRHS->getZExtValue();
12024 SDValue AndLHS = Op0;
12026 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12027 LHS = AndLHS.getOperand(0);
12028 RHS = AndLHS.getOperand(1);
12031 // Use BT if the immediate can't be encoded in a TEST instruction.
12032 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12034 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12038 if (LHS.getNode()) {
12039 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12040 // instruction. Since the shift amount is in-range-or-undefined, we know
12041 // that doing a bittest on the i32 value is ok. We extend to i32 because
12042 // the encoding for the i16 version is larger than the i32 version.
12043 // Also promote i16 to i32 for performance / code size reason.
12044 if (LHS.getValueType() == MVT::i8 ||
12045 LHS.getValueType() == MVT::i16)
12046 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12048 // If the operand types disagree, extend the shift amount to match. Since
12049 // BT ignores high bits (like shifts) we can use anyextend.
12050 if (LHS.getValueType() != RHS.getValueType())
12051 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12053 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12054 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12055 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12056 DAG.getConstant(Cond, MVT::i8), BT);
12062 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12064 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12069 // SSE Condition code mapping:
12078 switch (SetCCOpcode) {
12079 default: llvm_unreachable("Unexpected SETCC condition");
12081 case ISD::SETEQ: SSECC = 0; break;
12083 case ISD::SETGT: Swap = true; // Fallthrough
12085 case ISD::SETOLT: SSECC = 1; break;
12087 case ISD::SETGE: Swap = true; // Fallthrough
12089 case ISD::SETOLE: SSECC = 2; break;
12090 case ISD::SETUO: SSECC = 3; break;
12092 case ISD::SETNE: SSECC = 4; break;
12093 case ISD::SETULE: Swap = true; // Fallthrough
12094 case ISD::SETUGE: SSECC = 5; break;
12095 case ISD::SETULT: Swap = true; // Fallthrough
12096 case ISD::SETUGT: SSECC = 6; break;
12097 case ISD::SETO: SSECC = 7; break;
12099 case ISD::SETONE: SSECC = 8; break;
12102 std::swap(Op0, Op1);
12107 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12108 // ones, and then concatenate the result back.
12109 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12110 MVT VT = Op.getSimpleValueType();
12112 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12113 "Unsupported value type for operation");
12115 unsigned NumElems = VT.getVectorNumElements();
12117 SDValue CC = Op.getOperand(2);
12119 // Extract the LHS vectors
12120 SDValue LHS = Op.getOperand(0);
12121 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12122 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12124 // Extract the RHS vectors
12125 SDValue RHS = Op.getOperand(1);
12126 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12127 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12129 // Issue the operation on the smaller types and concatenate the result back
12130 MVT EltVT = VT.getVectorElementType();
12131 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12132 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12133 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12134 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12137 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12138 const X86Subtarget *Subtarget) {
12139 SDValue Op0 = Op.getOperand(0);
12140 SDValue Op1 = Op.getOperand(1);
12141 SDValue CC = Op.getOperand(2);
12142 MVT VT = Op.getSimpleValueType();
12145 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12146 Op.getValueType().getScalarType() == MVT::i1 &&
12147 "Cannot set masked compare for this operation");
12149 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12151 bool Unsigned = false;
12154 switch (SetCCOpcode) {
12155 default: llvm_unreachable("Unexpected SETCC condition");
12156 case ISD::SETNE: SSECC = 4; break;
12157 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12158 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12159 case ISD::SETLT: Swap = true; //fall-through
12160 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12161 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12162 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12163 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12164 case ISD::SETULE: Unsigned = true; //fall-through
12165 case ISD::SETLE: SSECC = 2; break;
12169 std::swap(Op0, Op1);
12171 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12172 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12173 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12174 DAG.getConstant(SSECC, MVT::i8));
12177 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12178 /// operand \p Op1. If non-trivial (for example because it's not constant)
12179 /// return an empty value.
12180 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12182 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12186 MVT VT = Op1.getSimpleValueType();
12187 MVT EVT = VT.getVectorElementType();
12188 unsigned n = VT.getVectorNumElements();
12189 SmallVector<SDValue, 8> ULTOp1;
12191 for (unsigned i = 0; i < n; ++i) {
12192 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12193 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12196 // Avoid underflow.
12197 APInt Val = Elt->getAPIntValue();
12201 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12204 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12207 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12208 SelectionDAG &DAG) {
12209 SDValue Op0 = Op.getOperand(0);
12210 SDValue Op1 = Op.getOperand(1);
12211 SDValue CC = Op.getOperand(2);
12212 MVT VT = Op.getSimpleValueType();
12213 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12214 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12219 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12220 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12223 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12224 unsigned Opc = X86ISD::CMPP;
12225 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12226 assert(VT.getVectorNumElements() <= 16);
12227 Opc = X86ISD::CMPM;
12229 // In the two special cases we can't handle, emit two comparisons.
12232 unsigned CombineOpc;
12233 if (SetCCOpcode == ISD::SETUEQ) {
12234 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12236 assert(SetCCOpcode == ISD::SETONE);
12237 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12240 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12241 DAG.getConstant(CC0, MVT::i8));
12242 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12243 DAG.getConstant(CC1, MVT::i8));
12244 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12246 // Handle all other FP comparisons here.
12247 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12248 DAG.getConstant(SSECC, MVT::i8));
12251 // Break 256-bit integer vector compare into smaller ones.
12252 if (VT.is256BitVector() && !Subtarget->hasInt256())
12253 return Lower256IntVSETCC(Op, DAG);
12255 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12256 EVT OpVT = Op1.getValueType();
12257 if (Subtarget->hasAVX512()) {
12258 if (Op1.getValueType().is512BitVector() ||
12259 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12260 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12262 // In AVX-512 architecture setcc returns mask with i1 elements,
12263 // But there is no compare instruction for i8 and i16 elements.
12264 // We are not talking about 512-bit operands in this case, these
12265 // types are illegal.
12267 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12268 OpVT.getVectorElementType().getSizeInBits() >= 8))
12269 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12270 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12273 // We are handling one of the integer comparisons here. Since SSE only has
12274 // GT and EQ comparisons for integer, swapping operands and multiple
12275 // operations may be required for some comparisons.
12277 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12278 bool Subus = false;
12280 switch (SetCCOpcode) {
12281 default: llvm_unreachable("Unexpected SETCC condition");
12282 case ISD::SETNE: Invert = true;
12283 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12284 case ISD::SETLT: Swap = true;
12285 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12286 case ISD::SETGE: Swap = true;
12287 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12288 Invert = true; break;
12289 case ISD::SETULT: Swap = true;
12290 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12291 FlipSigns = true; break;
12292 case ISD::SETUGE: Swap = true;
12293 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12294 FlipSigns = true; Invert = true; break;
12297 // Special case: Use min/max operations for SETULE/SETUGE
12298 MVT VET = VT.getVectorElementType();
12300 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12301 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12304 switch (SetCCOpcode) {
12306 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12307 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12310 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12313 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12314 if (!MinMax && hasSubus) {
12315 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12317 // t = psubus Op0, Op1
12318 // pcmpeq t, <0..0>
12319 switch (SetCCOpcode) {
12321 case ISD::SETULT: {
12322 // If the comparison is against a constant we can turn this into a
12323 // setule. With psubus, setule does not require a swap. This is
12324 // beneficial because the constant in the register is no longer
12325 // destructed as the destination so it can be hoisted out of a loop.
12326 // Only do this pre-AVX since vpcmp* is no longer destructive.
12327 if (Subtarget->hasAVX())
12329 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12330 if (ULEOp1.getNode()) {
12332 Subus = true; Invert = false; Swap = false;
12336 // Psubus is better than flip-sign because it requires no inversion.
12337 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12338 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12342 Opc = X86ISD::SUBUS;
12348 std::swap(Op0, Op1);
12350 // Check that the operation in question is available (most are plain SSE2,
12351 // but PCMPGTQ and PCMPEQQ have different requirements).
12352 if (VT == MVT::v2i64) {
12353 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12354 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12356 // First cast everything to the right type.
12357 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12358 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12360 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12361 // bits of the inputs before performing those operations. The lower
12362 // compare is always unsigned.
12365 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12367 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12368 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12369 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12370 Sign, Zero, Sign, Zero);
12372 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12373 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12375 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12376 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12377 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12379 // Create masks for only the low parts/high parts of the 64 bit integers.
12380 static const int MaskHi[] = { 1, 1, 3, 3 };
12381 static const int MaskLo[] = { 0, 0, 2, 2 };
12382 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12383 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12384 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12386 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12387 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12390 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12392 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12395 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12396 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12397 // pcmpeqd + pshufd + pand.
12398 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12400 // First cast everything to the right type.
12401 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12402 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12405 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12407 // Make sure the lower and upper halves are both all-ones.
12408 static const int Mask[] = { 1, 0, 3, 2 };
12409 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12410 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12413 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12415 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12419 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12420 // bits of the inputs before performing those operations.
12422 EVT EltVT = VT.getVectorElementType();
12423 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12424 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12425 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12428 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12430 // If the logical-not of the result is required, perform that now.
12432 Result = DAG.getNOT(dl, Result, VT);
12435 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12438 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12439 getZeroVector(VT, Subtarget, DAG, dl));
12444 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12446 MVT VT = Op.getSimpleValueType();
12448 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12450 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12451 && "SetCC type must be 8-bit or 1-bit integer");
12452 SDValue Op0 = Op.getOperand(0);
12453 SDValue Op1 = Op.getOperand(1);
12455 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12457 // Optimize to BT if possible.
12458 // Lower (X & (1 << N)) == 0 to BT(X, N).
12459 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12460 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12461 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12462 Op1.getOpcode() == ISD::Constant &&
12463 cast<ConstantSDNode>(Op1)->isNullValue() &&
12464 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12465 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12466 if (NewSetCC.getNode())
12470 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12472 if (Op1.getOpcode() == ISD::Constant &&
12473 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12474 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12475 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12477 // If the input is a setcc, then reuse the input setcc or use a new one with
12478 // the inverted condition.
12479 if (Op0.getOpcode() == X86ISD::SETCC) {
12480 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12481 bool Invert = (CC == ISD::SETNE) ^
12482 cast<ConstantSDNode>(Op1)->isNullValue();
12486 CCode = X86::GetOppositeBranchCondition(CCode);
12487 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12488 DAG.getConstant(CCode, MVT::i8),
12489 Op0.getOperand(1));
12491 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12495 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12496 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12497 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12499 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12500 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12503 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12504 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12505 if (X86CC == X86::COND_INVALID)
12508 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12509 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12510 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12511 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12513 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12517 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12518 static bool isX86LogicalCmp(SDValue Op) {
12519 unsigned Opc = Op.getNode()->getOpcode();
12520 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12521 Opc == X86ISD::SAHF)
12523 if (Op.getResNo() == 1 &&
12524 (Opc == X86ISD::ADD ||
12525 Opc == X86ISD::SUB ||
12526 Opc == X86ISD::ADC ||
12527 Opc == X86ISD::SBB ||
12528 Opc == X86ISD::SMUL ||
12529 Opc == X86ISD::UMUL ||
12530 Opc == X86ISD::INC ||
12531 Opc == X86ISD::DEC ||
12532 Opc == X86ISD::OR ||
12533 Opc == X86ISD::XOR ||
12534 Opc == X86ISD::AND))
12537 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12543 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12544 if (V.getOpcode() != ISD::TRUNCATE)
12547 SDValue VOp0 = V.getOperand(0);
12548 unsigned InBits = VOp0.getValueSizeInBits();
12549 unsigned Bits = V.getValueSizeInBits();
12550 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12553 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12554 bool addTest = true;
12555 SDValue Cond = Op.getOperand(0);
12556 SDValue Op1 = Op.getOperand(1);
12557 SDValue Op2 = Op.getOperand(2);
12559 EVT VT = Op1.getValueType();
12562 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12563 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12564 // sequence later on.
12565 if (Cond.getOpcode() == ISD::SETCC &&
12566 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12567 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12568 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12569 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12570 int SSECC = translateX86FSETCC(
12571 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12574 if (Subtarget->hasAVX512()) {
12575 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12576 DAG.getConstant(SSECC, MVT::i8));
12577 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12579 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12580 DAG.getConstant(SSECC, MVT::i8));
12581 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12582 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12583 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12587 if (Cond.getOpcode() == ISD::SETCC) {
12588 SDValue NewCond = LowerSETCC(Cond, DAG);
12589 if (NewCond.getNode())
12593 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12594 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12595 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12596 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12597 if (Cond.getOpcode() == X86ISD::SETCC &&
12598 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12599 isZero(Cond.getOperand(1).getOperand(1))) {
12600 SDValue Cmp = Cond.getOperand(1);
12602 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12604 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12605 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12606 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12608 SDValue CmpOp0 = Cmp.getOperand(0);
12609 // Apply further optimizations for special cases
12610 // (select (x != 0), -1, 0) -> neg & sbb
12611 // (select (x == 0), 0, -1) -> neg & sbb
12612 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12613 if (YC->isNullValue() &&
12614 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12615 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12616 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12617 DAG.getConstant(0, CmpOp0.getValueType()),
12619 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12620 DAG.getConstant(X86::COND_B, MVT::i8),
12621 SDValue(Neg.getNode(), 1));
12625 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12626 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12627 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12629 SDValue Res = // Res = 0 or -1.
12630 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12631 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12633 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12634 Res = DAG.getNOT(DL, Res, Res.getValueType());
12636 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12637 if (!N2C || !N2C->isNullValue())
12638 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12643 // Look past (and (setcc_carry (cmp ...)), 1).
12644 if (Cond.getOpcode() == ISD::AND &&
12645 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12646 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12647 if (C && C->getAPIntValue() == 1)
12648 Cond = Cond.getOperand(0);
12651 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12652 // setting operand in place of the X86ISD::SETCC.
12653 unsigned CondOpcode = Cond.getOpcode();
12654 if (CondOpcode == X86ISD::SETCC ||
12655 CondOpcode == X86ISD::SETCC_CARRY) {
12656 CC = Cond.getOperand(0);
12658 SDValue Cmp = Cond.getOperand(1);
12659 unsigned Opc = Cmp.getOpcode();
12660 MVT VT = Op.getSimpleValueType();
12662 bool IllegalFPCMov = false;
12663 if (VT.isFloatingPoint() && !VT.isVector() &&
12664 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12665 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12667 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12668 Opc == X86ISD::BT) { // FIXME
12672 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12673 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12674 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12675 Cond.getOperand(0).getValueType() != MVT::i8)) {
12676 SDValue LHS = Cond.getOperand(0);
12677 SDValue RHS = Cond.getOperand(1);
12678 unsigned X86Opcode;
12681 switch (CondOpcode) {
12682 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12683 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12684 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12685 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12686 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12687 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12688 default: llvm_unreachable("unexpected overflowing operator");
12690 if (CondOpcode == ISD::UMULO)
12691 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12694 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12696 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12698 if (CondOpcode == ISD::UMULO)
12699 Cond = X86Op.getValue(2);
12701 Cond = X86Op.getValue(1);
12703 CC = DAG.getConstant(X86Cond, MVT::i8);
12708 // Look pass the truncate if the high bits are known zero.
12709 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12710 Cond = Cond.getOperand(0);
12712 // We know the result of AND is compared against zero. Try to match
12714 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12715 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12716 if (NewSetCC.getNode()) {
12717 CC = NewSetCC.getOperand(0);
12718 Cond = NewSetCC.getOperand(1);
12725 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12726 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12729 // a < b ? -1 : 0 -> RES = ~setcc_carry
12730 // a < b ? 0 : -1 -> RES = setcc_carry
12731 // a >= b ? -1 : 0 -> RES = setcc_carry
12732 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12733 if (Cond.getOpcode() == X86ISD::SUB) {
12734 Cond = ConvertCmpIfNecessary(Cond, DAG);
12735 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12737 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12738 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12739 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12740 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12741 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12742 return DAG.getNOT(DL, Res, Res.getValueType());
12747 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12748 // widen the cmov and push the truncate through. This avoids introducing a new
12749 // branch during isel and doesn't add any extensions.
12750 if (Op.getValueType() == MVT::i8 &&
12751 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12752 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12753 if (T1.getValueType() == T2.getValueType() &&
12754 // Blacklist CopyFromReg to avoid partial register stalls.
12755 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12756 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12757 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12758 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12762 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12763 // condition is true.
12764 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12765 SDValue Ops[] = { Op2, Op1, CC, Cond };
12766 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12769 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12770 MVT VT = Op->getSimpleValueType(0);
12771 SDValue In = Op->getOperand(0);
12772 MVT InVT = In.getSimpleValueType();
12775 unsigned int NumElts = VT.getVectorNumElements();
12776 if (NumElts != 8 && NumElts != 16)
12779 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12780 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12782 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12783 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12785 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12786 Constant *C = ConstantInt::get(*DAG.getContext(),
12787 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12789 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12790 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12791 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12792 MachinePointerInfo::getConstantPool(),
12793 false, false, false, Alignment);
12794 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12795 if (VT.is512BitVector())
12797 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12800 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12801 SelectionDAG &DAG) {
12802 MVT VT = Op->getSimpleValueType(0);
12803 SDValue In = Op->getOperand(0);
12804 MVT InVT = In.getSimpleValueType();
12807 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12808 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12810 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12811 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12812 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12815 if (Subtarget->hasInt256())
12816 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12818 // Optimize vectors in AVX mode
12819 // Sign extend v8i16 to v8i32 and
12822 // Divide input vector into two parts
12823 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12824 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12825 // concat the vectors to original VT
12827 unsigned NumElems = InVT.getVectorNumElements();
12828 SDValue Undef = DAG.getUNDEF(InVT);
12830 SmallVector<int,8> ShufMask1(NumElems, -1);
12831 for (unsigned i = 0; i != NumElems/2; ++i)
12834 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12836 SmallVector<int,8> ShufMask2(NumElems, -1);
12837 for (unsigned i = 0; i != NumElems/2; ++i)
12838 ShufMask2[i] = i + NumElems/2;
12840 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12842 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12843 VT.getVectorNumElements()/2);
12845 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12846 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12848 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12851 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
12852 // may emit an illegal shuffle but the expansion is still better than scalar
12853 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
12854 // we'll emit a shuffle and a arithmetic shift.
12855 // TODO: It is possible to support ZExt by zeroing the undef values during
12856 // the shuffle phase or after the shuffle.
12857 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
12858 SelectionDAG &DAG) {
12859 MVT RegVT = Op.getSimpleValueType();
12860 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
12861 assert(RegVT.isInteger() &&
12862 "We only custom lower integer vector sext loads.");
12864 // Nothing useful we can do without SSE2 shuffles.
12865 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
12867 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
12869 EVT MemVT = Ld->getMemoryVT();
12870 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12871 unsigned RegSz = RegVT.getSizeInBits();
12873 ISD::LoadExtType Ext = Ld->getExtensionType();
12875 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
12876 && "Only anyext and sext are currently implemented.");
12877 assert(MemVT != RegVT && "Cannot extend to the same type");
12878 assert(MemVT.isVector() && "Must load a vector from memory");
12880 unsigned NumElems = RegVT.getVectorNumElements();
12881 unsigned MemSz = MemVT.getSizeInBits();
12882 assert(RegSz > MemSz && "Register size must be greater than the mem size");
12884 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
12885 // The only way in which we have a legal 256-bit vector result but not the
12886 // integer 256-bit operations needed to directly lower a sextload is if we
12887 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
12888 // a 128-bit vector and a normal sign_extend to 256-bits that should get
12889 // correctly legalized. We do this late to allow the canonical form of
12890 // sextload to persist throughout the rest of the DAG combiner -- it wants
12891 // to fold together any extensions it can, and so will fuse a sign_extend
12892 // of an sextload into an sextload targeting a wider value.
12894 if (MemSz == 128) {
12895 // Just switch this to a normal load.
12896 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
12897 "it must be a legal 128-bit vector "
12899 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
12900 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
12901 Ld->isInvariant(), Ld->getAlignment());
12903 assert(MemSz < 128 &&
12904 "Can't extend a type wider than 128 bits to a 256 bit vector!");
12905 // Do an sext load to a 128-bit vector type. We want to use the same
12906 // number of elements, but elements half as wide. This will end up being
12907 // recursively lowered by this routine, but will succeed as we definitely
12908 // have all the necessary features if we're using AVX1.
12910 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
12911 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
12913 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
12914 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
12915 Ld->isNonTemporal(), Ld->getAlignment());
12918 // Replace chain users with the new chain.
12919 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
12920 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
12922 // Finally, do a normal sign-extend to the desired register.
12923 return DAG.getSExtOrTrunc(Load, dl, RegVT);
12926 // All sizes must be a power of two.
12927 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
12928 "Non-power-of-two elements are not custom lowered!");
12930 // Attempt to load the original value using scalar loads.
12931 // Find the largest scalar type that divides the total loaded size.
12932 MVT SclrLoadTy = MVT::i8;
12933 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
12934 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
12935 MVT Tp = (MVT::SimpleValueType)tp;
12936 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
12941 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
12942 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
12944 SclrLoadTy = MVT::f64;
12946 // Calculate the number of scalar loads that we need to perform
12947 // in order to load our vector from memory.
12948 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
12950 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
12951 "Can only lower sext loads with a single scalar load!");
12953 unsigned loadRegZize = RegSz;
12954 if (Ext == ISD::SEXTLOAD && RegSz == 256)
12957 // Represent our vector as a sequence of elements which are the
12958 // largest scalar that we can load.
12959 EVT LoadUnitVecVT = EVT::getVectorVT(
12960 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
12962 // Represent the data using the same element type that is stored in
12963 // memory. In practice, we ''widen'' MemVT.
12965 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
12966 loadRegZize / MemVT.getScalarType().getSizeInBits());
12968 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
12969 "Invalid vector type");
12971 // We can't shuffle using an illegal type.
12972 assert(TLI.isTypeLegal(WideVecVT) &&
12973 "We only lower types that form legal widened vector types");
12975 SmallVector<SDValue, 8> Chains;
12976 SDValue Ptr = Ld->getBasePtr();
12977 SDValue Increment =
12978 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
12979 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
12981 for (unsigned i = 0; i < NumLoads; ++i) {
12982 // Perform a single load.
12983 SDValue ScalarLoad =
12984 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
12985 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
12986 Ld->getAlignment());
12987 Chains.push_back(ScalarLoad.getValue(1));
12988 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
12989 // another round of DAGCombining.
12991 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
12993 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
12994 ScalarLoad, DAG.getIntPtrConstant(i));
12996 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12999 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13001 // Bitcast the loaded value to a vector of the original element type, in
13002 // the size of the target vector type.
13003 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13004 unsigned SizeRatio = RegSz / MemSz;
13006 if (Ext == ISD::SEXTLOAD) {
13007 // If we have SSE4.1 we can directly emit a VSEXT node.
13008 if (Subtarget->hasSSE41()) {
13009 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13010 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13014 // Otherwise we'll shuffle the small elements in the high bits of the
13015 // larger type and perform an arithmetic shift. If the shift is not legal
13016 // it's better to scalarize.
13017 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13018 "We can't implement an sext load without a arithmetic right shift!");
13020 // Redistribute the loaded elements into the different locations.
13021 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13022 for (unsigned i = 0; i != NumElems; ++i)
13023 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13025 SDValue Shuff = DAG.getVectorShuffle(
13026 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13028 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13030 // Build the arithmetic shift.
13031 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13032 MemVT.getVectorElementType().getSizeInBits();
13034 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13036 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13040 // Redistribute the loaded elements into the different locations.
13041 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13042 for (unsigned i = 0; i != NumElems; ++i)
13043 ShuffleVec[i * SizeRatio] = i;
13045 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13046 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13048 // Bitcast to the requested type.
13049 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13050 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13054 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13055 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13056 // from the AND / OR.
13057 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13058 Opc = Op.getOpcode();
13059 if (Opc != ISD::OR && Opc != ISD::AND)
13061 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13062 Op.getOperand(0).hasOneUse() &&
13063 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13064 Op.getOperand(1).hasOneUse());
13067 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13068 // 1 and that the SETCC node has a single use.
13069 static bool isXor1OfSetCC(SDValue Op) {
13070 if (Op.getOpcode() != ISD::XOR)
13072 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13073 if (N1C && N1C->getAPIntValue() == 1) {
13074 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13075 Op.getOperand(0).hasOneUse();
13080 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13081 bool addTest = true;
13082 SDValue Chain = Op.getOperand(0);
13083 SDValue Cond = Op.getOperand(1);
13084 SDValue Dest = Op.getOperand(2);
13087 bool Inverted = false;
13089 if (Cond.getOpcode() == ISD::SETCC) {
13090 // Check for setcc([su]{add,sub,mul}o == 0).
13091 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13092 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13093 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13094 Cond.getOperand(0).getResNo() == 1 &&
13095 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13096 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13097 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13098 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13099 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13100 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13102 Cond = Cond.getOperand(0);
13104 SDValue NewCond = LowerSETCC(Cond, DAG);
13105 if (NewCond.getNode())
13110 // FIXME: LowerXALUO doesn't handle these!!
13111 else if (Cond.getOpcode() == X86ISD::ADD ||
13112 Cond.getOpcode() == X86ISD::SUB ||
13113 Cond.getOpcode() == X86ISD::SMUL ||
13114 Cond.getOpcode() == X86ISD::UMUL)
13115 Cond = LowerXALUO(Cond, DAG);
13118 // Look pass (and (setcc_carry (cmp ...)), 1).
13119 if (Cond.getOpcode() == ISD::AND &&
13120 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13121 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13122 if (C && C->getAPIntValue() == 1)
13123 Cond = Cond.getOperand(0);
13126 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13127 // setting operand in place of the X86ISD::SETCC.
13128 unsigned CondOpcode = Cond.getOpcode();
13129 if (CondOpcode == X86ISD::SETCC ||
13130 CondOpcode == X86ISD::SETCC_CARRY) {
13131 CC = Cond.getOperand(0);
13133 SDValue Cmp = Cond.getOperand(1);
13134 unsigned Opc = Cmp.getOpcode();
13135 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13136 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13140 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13144 // These can only come from an arithmetic instruction with overflow,
13145 // e.g. SADDO, UADDO.
13146 Cond = Cond.getNode()->getOperand(1);
13152 CondOpcode = Cond.getOpcode();
13153 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13154 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13155 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13156 Cond.getOperand(0).getValueType() != MVT::i8)) {
13157 SDValue LHS = Cond.getOperand(0);
13158 SDValue RHS = Cond.getOperand(1);
13159 unsigned X86Opcode;
13162 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13163 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13165 switch (CondOpcode) {
13166 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13170 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13173 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13174 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13178 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13181 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13182 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13183 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13184 default: llvm_unreachable("unexpected overflowing operator");
13187 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13188 if (CondOpcode == ISD::UMULO)
13189 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13192 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13194 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13196 if (CondOpcode == ISD::UMULO)
13197 Cond = X86Op.getValue(2);
13199 Cond = X86Op.getValue(1);
13201 CC = DAG.getConstant(X86Cond, MVT::i8);
13205 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13206 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13207 if (CondOpc == ISD::OR) {
13208 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13209 // two branches instead of an explicit OR instruction with a
13211 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13212 isX86LogicalCmp(Cmp)) {
13213 CC = Cond.getOperand(0).getOperand(0);
13214 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13215 Chain, Dest, CC, Cmp);
13216 CC = Cond.getOperand(1).getOperand(0);
13220 } else { // ISD::AND
13221 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13222 // two branches instead of an explicit AND instruction with a
13223 // separate test. However, we only do this if this block doesn't
13224 // have a fall-through edge, because this requires an explicit
13225 // jmp when the condition is false.
13226 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13227 isX86LogicalCmp(Cmp) &&
13228 Op.getNode()->hasOneUse()) {
13229 X86::CondCode CCode =
13230 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13231 CCode = X86::GetOppositeBranchCondition(CCode);
13232 CC = DAG.getConstant(CCode, MVT::i8);
13233 SDNode *User = *Op.getNode()->use_begin();
13234 // Look for an unconditional branch following this conditional branch.
13235 // We need this because we need to reverse the successors in order
13236 // to implement FCMP_OEQ.
13237 if (User->getOpcode() == ISD::BR) {
13238 SDValue FalseBB = User->getOperand(1);
13240 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13241 assert(NewBR == User);
13245 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13246 Chain, Dest, CC, Cmp);
13247 X86::CondCode CCode =
13248 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13249 CCode = X86::GetOppositeBranchCondition(CCode);
13250 CC = DAG.getConstant(CCode, MVT::i8);
13256 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13257 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13258 // It should be transformed during dag combiner except when the condition
13259 // is set by a arithmetics with overflow node.
13260 X86::CondCode CCode =
13261 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13262 CCode = X86::GetOppositeBranchCondition(CCode);
13263 CC = DAG.getConstant(CCode, MVT::i8);
13264 Cond = Cond.getOperand(0).getOperand(1);
13266 } else if (Cond.getOpcode() == ISD::SETCC &&
13267 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13268 // For FCMP_OEQ, we can emit
13269 // two branches instead of an explicit AND instruction with a
13270 // separate test. However, we only do this if this block doesn't
13271 // have a fall-through edge, because this requires an explicit
13272 // jmp when the condition is false.
13273 if (Op.getNode()->hasOneUse()) {
13274 SDNode *User = *Op.getNode()->use_begin();
13275 // Look for an unconditional branch following this conditional branch.
13276 // We need this because we need to reverse the successors in order
13277 // to implement FCMP_OEQ.
13278 if (User->getOpcode() == ISD::BR) {
13279 SDValue FalseBB = User->getOperand(1);
13281 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13282 assert(NewBR == User);
13286 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13287 Cond.getOperand(0), Cond.getOperand(1));
13288 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13289 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13290 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13291 Chain, Dest, CC, Cmp);
13292 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13297 } else if (Cond.getOpcode() == ISD::SETCC &&
13298 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13299 // For FCMP_UNE, we can emit
13300 // two branches instead of an explicit AND instruction with a
13301 // separate test. However, we only do this if this block doesn't
13302 // have a fall-through edge, because this requires an explicit
13303 // jmp when the condition is false.
13304 if (Op.getNode()->hasOneUse()) {
13305 SDNode *User = *Op.getNode()->use_begin();
13306 // Look for an unconditional branch following this conditional branch.
13307 // We need this because we need to reverse the successors in order
13308 // to implement FCMP_UNE.
13309 if (User->getOpcode() == ISD::BR) {
13310 SDValue FalseBB = User->getOperand(1);
13312 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13313 assert(NewBR == User);
13316 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13317 Cond.getOperand(0), Cond.getOperand(1));
13318 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13319 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13320 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13321 Chain, Dest, CC, Cmp);
13322 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13332 // Look pass the truncate if the high bits are known zero.
13333 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13334 Cond = Cond.getOperand(0);
13336 // We know the result of AND is compared against zero. Try to match
13338 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13339 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13340 if (NewSetCC.getNode()) {
13341 CC = NewSetCC.getOperand(0);
13342 Cond = NewSetCC.getOperand(1);
13349 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13350 CC = DAG.getConstant(X86Cond, MVT::i8);
13351 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13353 Cond = ConvertCmpIfNecessary(Cond, DAG);
13354 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13355 Chain, Dest, CC, Cond);
13358 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13359 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13360 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13361 // that the guard pages used by the OS virtual memory manager are allocated in
13362 // correct sequence.
13364 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13365 SelectionDAG &DAG) const {
13366 MachineFunction &MF = DAG.getMachineFunction();
13367 bool SplitStack = MF.shouldSplitStack();
13368 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13373 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13374 SDNode* Node = Op.getNode();
13376 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13377 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13378 " not tell us which reg is the stack pointer!");
13379 EVT VT = Node->getValueType(0);
13380 SDValue Tmp1 = SDValue(Node, 0);
13381 SDValue Tmp2 = SDValue(Node, 1);
13382 SDValue Tmp3 = Node->getOperand(2);
13383 SDValue Chain = Tmp1.getOperand(0);
13385 // Chain the dynamic stack allocation so that it doesn't modify the stack
13386 // pointer when other instructions are using the stack.
13387 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13390 SDValue Size = Tmp2.getOperand(1);
13391 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13392 Chain = SP.getValue(1);
13393 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13394 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13395 unsigned StackAlign = TFI.getStackAlignment();
13396 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13397 if (Align > StackAlign)
13398 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13399 DAG.getConstant(-(uint64_t)Align, VT));
13400 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13402 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13403 DAG.getIntPtrConstant(0, true), SDValue(),
13406 SDValue Ops[2] = { Tmp1, Tmp2 };
13407 return DAG.getMergeValues(Ops, dl);
13411 SDValue Chain = Op.getOperand(0);
13412 SDValue Size = Op.getOperand(1);
13413 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13414 EVT VT = Op.getNode()->getValueType(0);
13416 bool Is64Bit = Subtarget->is64Bit();
13417 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13420 MachineRegisterInfo &MRI = MF.getRegInfo();
13423 // The 64 bit implementation of segmented stacks needs to clobber both r10
13424 // r11. This makes it impossible to use it along with nested parameters.
13425 const Function *F = MF.getFunction();
13427 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13429 if (I->hasNestAttr())
13430 report_fatal_error("Cannot use segmented stacks with functions that "
13431 "have nested arguments.");
13434 const TargetRegisterClass *AddrRegClass =
13435 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13436 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13437 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13438 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13439 DAG.getRegister(Vreg, SPTy));
13440 SDValue Ops1[2] = { Value, Chain };
13441 return DAG.getMergeValues(Ops1, dl);
13444 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13446 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13447 Flag = Chain.getValue(1);
13448 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13450 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13452 const X86RegisterInfo *RegInfo =
13453 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13454 unsigned SPReg = RegInfo->getStackRegister();
13455 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13456 Chain = SP.getValue(1);
13459 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13460 DAG.getConstant(-(uint64_t)Align, VT));
13461 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13464 SDValue Ops1[2] = { SP, Chain };
13465 return DAG.getMergeValues(Ops1, dl);
13469 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13470 MachineFunction &MF = DAG.getMachineFunction();
13471 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13473 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13476 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13477 // vastart just stores the address of the VarArgsFrameIndex slot into the
13478 // memory location argument.
13479 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13481 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13482 MachinePointerInfo(SV), false, false, 0);
13486 // gp_offset (0 - 6 * 8)
13487 // fp_offset (48 - 48 + 8 * 16)
13488 // overflow_arg_area (point to parameters coming in memory).
13490 SmallVector<SDValue, 8> MemOps;
13491 SDValue FIN = Op.getOperand(1);
13493 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13494 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13496 FIN, MachinePointerInfo(SV), false, false, 0);
13497 MemOps.push_back(Store);
13500 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13501 FIN, DAG.getIntPtrConstant(4));
13502 Store = DAG.getStore(Op.getOperand(0), DL,
13503 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13505 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13506 MemOps.push_back(Store);
13508 // Store ptr to overflow_arg_area
13509 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13510 FIN, DAG.getIntPtrConstant(4));
13511 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13513 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13514 MachinePointerInfo(SV, 8),
13516 MemOps.push_back(Store);
13518 // Store ptr to reg_save_area.
13519 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13520 FIN, DAG.getIntPtrConstant(8));
13521 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13523 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13524 MachinePointerInfo(SV, 16), false, false, 0);
13525 MemOps.push_back(Store);
13526 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13529 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13530 assert(Subtarget->is64Bit() &&
13531 "LowerVAARG only handles 64-bit va_arg!");
13532 assert((Subtarget->isTargetLinux() ||
13533 Subtarget->isTargetDarwin()) &&
13534 "Unhandled target in LowerVAARG");
13535 assert(Op.getNode()->getNumOperands() == 4);
13536 SDValue Chain = Op.getOperand(0);
13537 SDValue SrcPtr = Op.getOperand(1);
13538 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13539 unsigned Align = Op.getConstantOperandVal(3);
13542 EVT ArgVT = Op.getNode()->getValueType(0);
13543 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13544 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13547 // Decide which area this value should be read from.
13548 // TODO: Implement the AMD64 ABI in its entirety. This simple
13549 // selection mechanism works only for the basic types.
13550 if (ArgVT == MVT::f80) {
13551 llvm_unreachable("va_arg for f80 not yet implemented");
13552 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13553 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13554 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13555 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13557 llvm_unreachable("Unhandled argument type in LowerVAARG");
13560 if (ArgMode == 2) {
13561 // Sanity Check: Make sure using fp_offset makes sense.
13562 assert(!DAG.getTarget().Options.UseSoftFloat &&
13563 !(DAG.getMachineFunction()
13564 .getFunction()->getAttributes()
13565 .hasAttribute(AttributeSet::FunctionIndex,
13566 Attribute::NoImplicitFloat)) &&
13567 Subtarget->hasSSE1());
13570 // Insert VAARG_64 node into the DAG
13571 // VAARG_64 returns two values: Variable Argument Address, Chain
13572 SmallVector<SDValue, 11> InstOps;
13573 InstOps.push_back(Chain);
13574 InstOps.push_back(SrcPtr);
13575 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13576 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13577 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13578 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13579 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13580 VTs, InstOps, MVT::i64,
13581 MachinePointerInfo(SV),
13583 /*Volatile=*/false,
13585 /*WriteMem=*/true);
13586 Chain = VAARG.getValue(1);
13588 // Load the next argument and return it
13589 return DAG.getLoad(ArgVT, dl,
13592 MachinePointerInfo(),
13593 false, false, false, 0);
13596 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13597 SelectionDAG &DAG) {
13598 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13599 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13600 SDValue Chain = Op.getOperand(0);
13601 SDValue DstPtr = Op.getOperand(1);
13602 SDValue SrcPtr = Op.getOperand(2);
13603 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13604 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13607 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13608 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13610 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13613 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13614 // amount is a constant. Takes immediate version of shift as input.
13615 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13616 SDValue SrcOp, uint64_t ShiftAmt,
13617 SelectionDAG &DAG) {
13618 MVT ElementType = VT.getVectorElementType();
13620 // Fold this packed shift into its first operand if ShiftAmt is 0.
13624 // Check for ShiftAmt >= element width
13625 if (ShiftAmt >= ElementType.getSizeInBits()) {
13626 if (Opc == X86ISD::VSRAI)
13627 ShiftAmt = ElementType.getSizeInBits() - 1;
13629 return DAG.getConstant(0, VT);
13632 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13633 && "Unknown target vector shift-by-constant node");
13635 // Fold this packed vector shift into a build vector if SrcOp is a
13636 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13637 if (VT == SrcOp.getSimpleValueType() &&
13638 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13639 SmallVector<SDValue, 8> Elts;
13640 unsigned NumElts = SrcOp->getNumOperands();
13641 ConstantSDNode *ND;
13644 default: llvm_unreachable(nullptr);
13645 case X86ISD::VSHLI:
13646 for (unsigned i=0; i!=NumElts; ++i) {
13647 SDValue CurrentOp = SrcOp->getOperand(i);
13648 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13649 Elts.push_back(CurrentOp);
13652 ND = cast<ConstantSDNode>(CurrentOp);
13653 const APInt &C = ND->getAPIntValue();
13654 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13657 case X86ISD::VSRLI:
13658 for (unsigned i=0; i!=NumElts; ++i) {
13659 SDValue CurrentOp = SrcOp->getOperand(i);
13660 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13661 Elts.push_back(CurrentOp);
13664 ND = cast<ConstantSDNode>(CurrentOp);
13665 const APInt &C = ND->getAPIntValue();
13666 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13669 case X86ISD::VSRAI:
13670 for (unsigned i=0; i!=NumElts; ++i) {
13671 SDValue CurrentOp = SrcOp->getOperand(i);
13672 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13673 Elts.push_back(CurrentOp);
13676 ND = cast<ConstantSDNode>(CurrentOp);
13677 const APInt &C = ND->getAPIntValue();
13678 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13683 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13686 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13689 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13690 // may or may not be a constant. Takes immediate version of shift as input.
13691 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13692 SDValue SrcOp, SDValue ShAmt,
13693 SelectionDAG &DAG) {
13694 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13696 // Catch shift-by-constant.
13697 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13698 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13699 CShAmt->getZExtValue(), DAG);
13701 // Change opcode to non-immediate version
13703 default: llvm_unreachable("Unknown target vector shift node");
13704 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13705 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13706 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13709 // Need to build a vector containing shift amount
13710 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13713 ShOps[1] = DAG.getConstant(0, MVT::i32);
13714 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13715 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13717 // The return type has to be a 128-bit type with the same element
13718 // type as the input type.
13719 MVT EltVT = VT.getVectorElementType();
13720 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13722 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13723 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13726 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13728 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13730 default: return SDValue(); // Don't custom lower most intrinsics.
13731 // Comparison intrinsics.
13732 case Intrinsic::x86_sse_comieq_ss:
13733 case Intrinsic::x86_sse_comilt_ss:
13734 case Intrinsic::x86_sse_comile_ss:
13735 case Intrinsic::x86_sse_comigt_ss:
13736 case Intrinsic::x86_sse_comige_ss:
13737 case Intrinsic::x86_sse_comineq_ss:
13738 case Intrinsic::x86_sse_ucomieq_ss:
13739 case Intrinsic::x86_sse_ucomilt_ss:
13740 case Intrinsic::x86_sse_ucomile_ss:
13741 case Intrinsic::x86_sse_ucomigt_ss:
13742 case Intrinsic::x86_sse_ucomige_ss:
13743 case Intrinsic::x86_sse_ucomineq_ss:
13744 case Intrinsic::x86_sse2_comieq_sd:
13745 case Intrinsic::x86_sse2_comilt_sd:
13746 case Intrinsic::x86_sse2_comile_sd:
13747 case Intrinsic::x86_sse2_comigt_sd:
13748 case Intrinsic::x86_sse2_comige_sd:
13749 case Intrinsic::x86_sse2_comineq_sd:
13750 case Intrinsic::x86_sse2_ucomieq_sd:
13751 case Intrinsic::x86_sse2_ucomilt_sd:
13752 case Intrinsic::x86_sse2_ucomile_sd:
13753 case Intrinsic::x86_sse2_ucomigt_sd:
13754 case Intrinsic::x86_sse2_ucomige_sd:
13755 case Intrinsic::x86_sse2_ucomineq_sd: {
13759 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13760 case Intrinsic::x86_sse_comieq_ss:
13761 case Intrinsic::x86_sse2_comieq_sd:
13762 Opc = X86ISD::COMI;
13765 case Intrinsic::x86_sse_comilt_ss:
13766 case Intrinsic::x86_sse2_comilt_sd:
13767 Opc = X86ISD::COMI;
13770 case Intrinsic::x86_sse_comile_ss:
13771 case Intrinsic::x86_sse2_comile_sd:
13772 Opc = X86ISD::COMI;
13775 case Intrinsic::x86_sse_comigt_ss:
13776 case Intrinsic::x86_sse2_comigt_sd:
13777 Opc = X86ISD::COMI;
13780 case Intrinsic::x86_sse_comige_ss:
13781 case Intrinsic::x86_sse2_comige_sd:
13782 Opc = X86ISD::COMI;
13785 case Intrinsic::x86_sse_comineq_ss:
13786 case Intrinsic::x86_sse2_comineq_sd:
13787 Opc = X86ISD::COMI;
13790 case Intrinsic::x86_sse_ucomieq_ss:
13791 case Intrinsic::x86_sse2_ucomieq_sd:
13792 Opc = X86ISD::UCOMI;
13795 case Intrinsic::x86_sse_ucomilt_ss:
13796 case Intrinsic::x86_sse2_ucomilt_sd:
13797 Opc = X86ISD::UCOMI;
13800 case Intrinsic::x86_sse_ucomile_ss:
13801 case Intrinsic::x86_sse2_ucomile_sd:
13802 Opc = X86ISD::UCOMI;
13805 case Intrinsic::x86_sse_ucomigt_ss:
13806 case Intrinsic::x86_sse2_ucomigt_sd:
13807 Opc = X86ISD::UCOMI;
13810 case Intrinsic::x86_sse_ucomige_ss:
13811 case Intrinsic::x86_sse2_ucomige_sd:
13812 Opc = X86ISD::UCOMI;
13815 case Intrinsic::x86_sse_ucomineq_ss:
13816 case Intrinsic::x86_sse2_ucomineq_sd:
13817 Opc = X86ISD::UCOMI;
13822 SDValue LHS = Op.getOperand(1);
13823 SDValue RHS = Op.getOperand(2);
13824 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13825 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13826 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13827 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13828 DAG.getConstant(X86CC, MVT::i8), Cond);
13829 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13832 // Arithmetic intrinsics.
13833 case Intrinsic::x86_sse2_pmulu_dq:
13834 case Intrinsic::x86_avx2_pmulu_dq:
13835 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13836 Op.getOperand(1), Op.getOperand(2));
13838 case Intrinsic::x86_sse41_pmuldq:
13839 case Intrinsic::x86_avx2_pmul_dq:
13840 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13841 Op.getOperand(1), Op.getOperand(2));
13843 case Intrinsic::x86_sse2_pmulhu_w:
13844 case Intrinsic::x86_avx2_pmulhu_w:
13845 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13846 Op.getOperand(1), Op.getOperand(2));
13848 case Intrinsic::x86_sse2_pmulh_w:
13849 case Intrinsic::x86_avx2_pmulh_w:
13850 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13851 Op.getOperand(1), Op.getOperand(2));
13853 // SSE2/AVX2 sub with unsigned saturation intrinsics
13854 case Intrinsic::x86_sse2_psubus_b:
13855 case Intrinsic::x86_sse2_psubus_w:
13856 case Intrinsic::x86_avx2_psubus_b:
13857 case Intrinsic::x86_avx2_psubus_w:
13858 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13859 Op.getOperand(1), Op.getOperand(2));
13861 // SSE3/AVX horizontal add/sub intrinsics
13862 case Intrinsic::x86_sse3_hadd_ps:
13863 case Intrinsic::x86_sse3_hadd_pd:
13864 case Intrinsic::x86_avx_hadd_ps_256:
13865 case Intrinsic::x86_avx_hadd_pd_256:
13866 case Intrinsic::x86_sse3_hsub_ps:
13867 case Intrinsic::x86_sse3_hsub_pd:
13868 case Intrinsic::x86_avx_hsub_ps_256:
13869 case Intrinsic::x86_avx_hsub_pd_256:
13870 case Intrinsic::x86_ssse3_phadd_w_128:
13871 case Intrinsic::x86_ssse3_phadd_d_128:
13872 case Intrinsic::x86_avx2_phadd_w:
13873 case Intrinsic::x86_avx2_phadd_d:
13874 case Intrinsic::x86_ssse3_phsub_w_128:
13875 case Intrinsic::x86_ssse3_phsub_d_128:
13876 case Intrinsic::x86_avx2_phsub_w:
13877 case Intrinsic::x86_avx2_phsub_d: {
13880 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13881 case Intrinsic::x86_sse3_hadd_ps:
13882 case Intrinsic::x86_sse3_hadd_pd:
13883 case Intrinsic::x86_avx_hadd_ps_256:
13884 case Intrinsic::x86_avx_hadd_pd_256:
13885 Opcode = X86ISD::FHADD;
13887 case Intrinsic::x86_sse3_hsub_ps:
13888 case Intrinsic::x86_sse3_hsub_pd:
13889 case Intrinsic::x86_avx_hsub_ps_256:
13890 case Intrinsic::x86_avx_hsub_pd_256:
13891 Opcode = X86ISD::FHSUB;
13893 case Intrinsic::x86_ssse3_phadd_w_128:
13894 case Intrinsic::x86_ssse3_phadd_d_128:
13895 case Intrinsic::x86_avx2_phadd_w:
13896 case Intrinsic::x86_avx2_phadd_d:
13897 Opcode = X86ISD::HADD;
13899 case Intrinsic::x86_ssse3_phsub_w_128:
13900 case Intrinsic::x86_ssse3_phsub_d_128:
13901 case Intrinsic::x86_avx2_phsub_w:
13902 case Intrinsic::x86_avx2_phsub_d:
13903 Opcode = X86ISD::HSUB;
13906 return DAG.getNode(Opcode, dl, Op.getValueType(),
13907 Op.getOperand(1), Op.getOperand(2));
13910 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13911 case Intrinsic::x86_sse2_pmaxu_b:
13912 case Intrinsic::x86_sse41_pmaxuw:
13913 case Intrinsic::x86_sse41_pmaxud:
13914 case Intrinsic::x86_avx2_pmaxu_b:
13915 case Intrinsic::x86_avx2_pmaxu_w:
13916 case Intrinsic::x86_avx2_pmaxu_d:
13917 case Intrinsic::x86_sse2_pminu_b:
13918 case Intrinsic::x86_sse41_pminuw:
13919 case Intrinsic::x86_sse41_pminud:
13920 case Intrinsic::x86_avx2_pminu_b:
13921 case Intrinsic::x86_avx2_pminu_w:
13922 case Intrinsic::x86_avx2_pminu_d:
13923 case Intrinsic::x86_sse41_pmaxsb:
13924 case Intrinsic::x86_sse2_pmaxs_w:
13925 case Intrinsic::x86_sse41_pmaxsd:
13926 case Intrinsic::x86_avx2_pmaxs_b:
13927 case Intrinsic::x86_avx2_pmaxs_w:
13928 case Intrinsic::x86_avx2_pmaxs_d:
13929 case Intrinsic::x86_sse41_pminsb:
13930 case Intrinsic::x86_sse2_pmins_w:
13931 case Intrinsic::x86_sse41_pminsd:
13932 case Intrinsic::x86_avx2_pmins_b:
13933 case Intrinsic::x86_avx2_pmins_w:
13934 case Intrinsic::x86_avx2_pmins_d: {
13937 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13938 case Intrinsic::x86_sse2_pmaxu_b:
13939 case Intrinsic::x86_sse41_pmaxuw:
13940 case Intrinsic::x86_sse41_pmaxud:
13941 case Intrinsic::x86_avx2_pmaxu_b:
13942 case Intrinsic::x86_avx2_pmaxu_w:
13943 case Intrinsic::x86_avx2_pmaxu_d:
13944 Opcode = X86ISD::UMAX;
13946 case Intrinsic::x86_sse2_pminu_b:
13947 case Intrinsic::x86_sse41_pminuw:
13948 case Intrinsic::x86_sse41_pminud:
13949 case Intrinsic::x86_avx2_pminu_b:
13950 case Intrinsic::x86_avx2_pminu_w:
13951 case Intrinsic::x86_avx2_pminu_d:
13952 Opcode = X86ISD::UMIN;
13954 case Intrinsic::x86_sse41_pmaxsb:
13955 case Intrinsic::x86_sse2_pmaxs_w:
13956 case Intrinsic::x86_sse41_pmaxsd:
13957 case Intrinsic::x86_avx2_pmaxs_b:
13958 case Intrinsic::x86_avx2_pmaxs_w:
13959 case Intrinsic::x86_avx2_pmaxs_d:
13960 Opcode = X86ISD::SMAX;
13962 case Intrinsic::x86_sse41_pminsb:
13963 case Intrinsic::x86_sse2_pmins_w:
13964 case Intrinsic::x86_sse41_pminsd:
13965 case Intrinsic::x86_avx2_pmins_b:
13966 case Intrinsic::x86_avx2_pmins_w:
13967 case Intrinsic::x86_avx2_pmins_d:
13968 Opcode = X86ISD::SMIN;
13971 return DAG.getNode(Opcode, dl, Op.getValueType(),
13972 Op.getOperand(1), Op.getOperand(2));
13975 // SSE/SSE2/AVX floating point max/min intrinsics.
13976 case Intrinsic::x86_sse_max_ps:
13977 case Intrinsic::x86_sse2_max_pd:
13978 case Intrinsic::x86_avx_max_ps_256:
13979 case Intrinsic::x86_avx_max_pd_256:
13980 case Intrinsic::x86_sse_min_ps:
13981 case Intrinsic::x86_sse2_min_pd:
13982 case Intrinsic::x86_avx_min_ps_256:
13983 case Intrinsic::x86_avx_min_pd_256: {
13986 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13987 case Intrinsic::x86_sse_max_ps:
13988 case Intrinsic::x86_sse2_max_pd:
13989 case Intrinsic::x86_avx_max_ps_256:
13990 case Intrinsic::x86_avx_max_pd_256:
13991 Opcode = X86ISD::FMAX;
13993 case Intrinsic::x86_sse_min_ps:
13994 case Intrinsic::x86_sse2_min_pd:
13995 case Intrinsic::x86_avx_min_ps_256:
13996 case Intrinsic::x86_avx_min_pd_256:
13997 Opcode = X86ISD::FMIN;
14000 return DAG.getNode(Opcode, dl, Op.getValueType(),
14001 Op.getOperand(1), Op.getOperand(2));
14004 // AVX2 variable shift intrinsics
14005 case Intrinsic::x86_avx2_psllv_d:
14006 case Intrinsic::x86_avx2_psllv_q:
14007 case Intrinsic::x86_avx2_psllv_d_256:
14008 case Intrinsic::x86_avx2_psllv_q_256:
14009 case Intrinsic::x86_avx2_psrlv_d:
14010 case Intrinsic::x86_avx2_psrlv_q:
14011 case Intrinsic::x86_avx2_psrlv_d_256:
14012 case Intrinsic::x86_avx2_psrlv_q_256:
14013 case Intrinsic::x86_avx2_psrav_d:
14014 case Intrinsic::x86_avx2_psrav_d_256: {
14017 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14018 case Intrinsic::x86_avx2_psllv_d:
14019 case Intrinsic::x86_avx2_psllv_q:
14020 case Intrinsic::x86_avx2_psllv_d_256:
14021 case Intrinsic::x86_avx2_psllv_q_256:
14024 case Intrinsic::x86_avx2_psrlv_d:
14025 case Intrinsic::x86_avx2_psrlv_q:
14026 case Intrinsic::x86_avx2_psrlv_d_256:
14027 case Intrinsic::x86_avx2_psrlv_q_256:
14030 case Intrinsic::x86_avx2_psrav_d:
14031 case Intrinsic::x86_avx2_psrav_d_256:
14035 return DAG.getNode(Opcode, dl, Op.getValueType(),
14036 Op.getOperand(1), Op.getOperand(2));
14039 case Intrinsic::x86_sse2_packssdw_128:
14040 case Intrinsic::x86_sse2_packsswb_128:
14041 case Intrinsic::x86_avx2_packssdw:
14042 case Intrinsic::x86_avx2_packsswb:
14043 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14044 Op.getOperand(1), Op.getOperand(2));
14046 case Intrinsic::x86_sse2_packuswb_128:
14047 case Intrinsic::x86_sse41_packusdw:
14048 case Intrinsic::x86_avx2_packuswb:
14049 case Intrinsic::x86_avx2_packusdw:
14050 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14051 Op.getOperand(1), Op.getOperand(2));
14053 case Intrinsic::x86_ssse3_pshuf_b_128:
14054 case Intrinsic::x86_avx2_pshuf_b:
14055 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14056 Op.getOperand(1), Op.getOperand(2));
14058 case Intrinsic::x86_sse2_pshuf_d:
14059 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14060 Op.getOperand(1), Op.getOperand(2));
14062 case Intrinsic::x86_sse2_pshufl_w:
14063 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14064 Op.getOperand(1), Op.getOperand(2));
14066 case Intrinsic::x86_sse2_pshufh_w:
14067 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14068 Op.getOperand(1), Op.getOperand(2));
14070 case Intrinsic::x86_ssse3_psign_b_128:
14071 case Intrinsic::x86_ssse3_psign_w_128:
14072 case Intrinsic::x86_ssse3_psign_d_128:
14073 case Intrinsic::x86_avx2_psign_b:
14074 case Intrinsic::x86_avx2_psign_w:
14075 case Intrinsic::x86_avx2_psign_d:
14076 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14077 Op.getOperand(1), Op.getOperand(2));
14079 case Intrinsic::x86_sse41_insertps:
14080 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14081 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14083 case Intrinsic::x86_avx_vperm2f128_ps_256:
14084 case Intrinsic::x86_avx_vperm2f128_pd_256:
14085 case Intrinsic::x86_avx_vperm2f128_si_256:
14086 case Intrinsic::x86_avx2_vperm2i128:
14087 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14088 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14090 case Intrinsic::x86_avx2_permd:
14091 case Intrinsic::x86_avx2_permps:
14092 // Operands intentionally swapped. Mask is last operand to intrinsic,
14093 // but second operand for node/instruction.
14094 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14095 Op.getOperand(2), Op.getOperand(1));
14097 case Intrinsic::x86_sse_sqrt_ps:
14098 case Intrinsic::x86_sse2_sqrt_pd:
14099 case Intrinsic::x86_avx_sqrt_ps_256:
14100 case Intrinsic::x86_avx_sqrt_pd_256:
14101 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14103 // ptest and testp intrinsics. The intrinsic these come from are designed to
14104 // return an integer value, not just an instruction so lower it to the ptest
14105 // or testp pattern and a setcc for the result.
14106 case Intrinsic::x86_sse41_ptestz:
14107 case Intrinsic::x86_sse41_ptestc:
14108 case Intrinsic::x86_sse41_ptestnzc:
14109 case Intrinsic::x86_avx_ptestz_256:
14110 case Intrinsic::x86_avx_ptestc_256:
14111 case Intrinsic::x86_avx_ptestnzc_256:
14112 case Intrinsic::x86_avx_vtestz_ps:
14113 case Intrinsic::x86_avx_vtestc_ps:
14114 case Intrinsic::x86_avx_vtestnzc_ps:
14115 case Intrinsic::x86_avx_vtestz_pd:
14116 case Intrinsic::x86_avx_vtestc_pd:
14117 case Intrinsic::x86_avx_vtestnzc_pd:
14118 case Intrinsic::x86_avx_vtestz_ps_256:
14119 case Intrinsic::x86_avx_vtestc_ps_256:
14120 case Intrinsic::x86_avx_vtestnzc_ps_256:
14121 case Intrinsic::x86_avx_vtestz_pd_256:
14122 case Intrinsic::x86_avx_vtestc_pd_256:
14123 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14124 bool IsTestPacked = false;
14127 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14128 case Intrinsic::x86_avx_vtestz_ps:
14129 case Intrinsic::x86_avx_vtestz_pd:
14130 case Intrinsic::x86_avx_vtestz_ps_256:
14131 case Intrinsic::x86_avx_vtestz_pd_256:
14132 IsTestPacked = true; // Fallthrough
14133 case Intrinsic::x86_sse41_ptestz:
14134 case Intrinsic::x86_avx_ptestz_256:
14136 X86CC = X86::COND_E;
14138 case Intrinsic::x86_avx_vtestc_ps:
14139 case Intrinsic::x86_avx_vtestc_pd:
14140 case Intrinsic::x86_avx_vtestc_ps_256:
14141 case Intrinsic::x86_avx_vtestc_pd_256:
14142 IsTestPacked = true; // Fallthrough
14143 case Intrinsic::x86_sse41_ptestc:
14144 case Intrinsic::x86_avx_ptestc_256:
14146 X86CC = X86::COND_B;
14148 case Intrinsic::x86_avx_vtestnzc_ps:
14149 case Intrinsic::x86_avx_vtestnzc_pd:
14150 case Intrinsic::x86_avx_vtestnzc_ps_256:
14151 case Intrinsic::x86_avx_vtestnzc_pd_256:
14152 IsTestPacked = true; // Fallthrough
14153 case Intrinsic::x86_sse41_ptestnzc:
14154 case Intrinsic::x86_avx_ptestnzc_256:
14156 X86CC = X86::COND_A;
14160 SDValue LHS = Op.getOperand(1);
14161 SDValue RHS = Op.getOperand(2);
14162 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14163 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14164 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14165 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14166 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14168 case Intrinsic::x86_avx512_kortestz_w:
14169 case Intrinsic::x86_avx512_kortestc_w: {
14170 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14171 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14172 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14173 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14174 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14175 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14176 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14179 // SSE/AVX shift intrinsics
14180 case Intrinsic::x86_sse2_psll_w:
14181 case Intrinsic::x86_sse2_psll_d:
14182 case Intrinsic::x86_sse2_psll_q:
14183 case Intrinsic::x86_avx2_psll_w:
14184 case Intrinsic::x86_avx2_psll_d:
14185 case Intrinsic::x86_avx2_psll_q:
14186 case Intrinsic::x86_sse2_psrl_w:
14187 case Intrinsic::x86_sse2_psrl_d:
14188 case Intrinsic::x86_sse2_psrl_q:
14189 case Intrinsic::x86_avx2_psrl_w:
14190 case Intrinsic::x86_avx2_psrl_d:
14191 case Intrinsic::x86_avx2_psrl_q:
14192 case Intrinsic::x86_sse2_psra_w:
14193 case Intrinsic::x86_sse2_psra_d:
14194 case Intrinsic::x86_avx2_psra_w:
14195 case Intrinsic::x86_avx2_psra_d: {
14198 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14199 case Intrinsic::x86_sse2_psll_w:
14200 case Intrinsic::x86_sse2_psll_d:
14201 case Intrinsic::x86_sse2_psll_q:
14202 case Intrinsic::x86_avx2_psll_w:
14203 case Intrinsic::x86_avx2_psll_d:
14204 case Intrinsic::x86_avx2_psll_q:
14205 Opcode = X86ISD::VSHL;
14207 case Intrinsic::x86_sse2_psrl_w:
14208 case Intrinsic::x86_sse2_psrl_d:
14209 case Intrinsic::x86_sse2_psrl_q:
14210 case Intrinsic::x86_avx2_psrl_w:
14211 case Intrinsic::x86_avx2_psrl_d:
14212 case Intrinsic::x86_avx2_psrl_q:
14213 Opcode = X86ISD::VSRL;
14215 case Intrinsic::x86_sse2_psra_w:
14216 case Intrinsic::x86_sse2_psra_d:
14217 case Intrinsic::x86_avx2_psra_w:
14218 case Intrinsic::x86_avx2_psra_d:
14219 Opcode = X86ISD::VSRA;
14222 return DAG.getNode(Opcode, dl, Op.getValueType(),
14223 Op.getOperand(1), Op.getOperand(2));
14226 // SSE/AVX immediate shift intrinsics
14227 case Intrinsic::x86_sse2_pslli_w:
14228 case Intrinsic::x86_sse2_pslli_d:
14229 case Intrinsic::x86_sse2_pslli_q:
14230 case Intrinsic::x86_avx2_pslli_w:
14231 case Intrinsic::x86_avx2_pslli_d:
14232 case Intrinsic::x86_avx2_pslli_q:
14233 case Intrinsic::x86_sse2_psrli_w:
14234 case Intrinsic::x86_sse2_psrli_d:
14235 case Intrinsic::x86_sse2_psrli_q:
14236 case Intrinsic::x86_avx2_psrli_w:
14237 case Intrinsic::x86_avx2_psrli_d:
14238 case Intrinsic::x86_avx2_psrli_q:
14239 case Intrinsic::x86_sse2_psrai_w:
14240 case Intrinsic::x86_sse2_psrai_d:
14241 case Intrinsic::x86_avx2_psrai_w:
14242 case Intrinsic::x86_avx2_psrai_d: {
14245 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14246 case Intrinsic::x86_sse2_pslli_w:
14247 case Intrinsic::x86_sse2_pslli_d:
14248 case Intrinsic::x86_sse2_pslli_q:
14249 case Intrinsic::x86_avx2_pslli_w:
14250 case Intrinsic::x86_avx2_pslli_d:
14251 case Intrinsic::x86_avx2_pslli_q:
14252 Opcode = X86ISD::VSHLI;
14254 case Intrinsic::x86_sse2_psrli_w:
14255 case Intrinsic::x86_sse2_psrli_d:
14256 case Intrinsic::x86_sse2_psrli_q:
14257 case Intrinsic::x86_avx2_psrli_w:
14258 case Intrinsic::x86_avx2_psrli_d:
14259 case Intrinsic::x86_avx2_psrli_q:
14260 Opcode = X86ISD::VSRLI;
14262 case Intrinsic::x86_sse2_psrai_w:
14263 case Intrinsic::x86_sse2_psrai_d:
14264 case Intrinsic::x86_avx2_psrai_w:
14265 case Intrinsic::x86_avx2_psrai_d:
14266 Opcode = X86ISD::VSRAI;
14269 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14270 Op.getOperand(1), Op.getOperand(2), DAG);
14273 case Intrinsic::x86_sse42_pcmpistria128:
14274 case Intrinsic::x86_sse42_pcmpestria128:
14275 case Intrinsic::x86_sse42_pcmpistric128:
14276 case Intrinsic::x86_sse42_pcmpestric128:
14277 case Intrinsic::x86_sse42_pcmpistrio128:
14278 case Intrinsic::x86_sse42_pcmpestrio128:
14279 case Intrinsic::x86_sse42_pcmpistris128:
14280 case Intrinsic::x86_sse42_pcmpestris128:
14281 case Intrinsic::x86_sse42_pcmpistriz128:
14282 case Intrinsic::x86_sse42_pcmpestriz128: {
14286 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14287 case Intrinsic::x86_sse42_pcmpistria128:
14288 Opcode = X86ISD::PCMPISTRI;
14289 X86CC = X86::COND_A;
14291 case Intrinsic::x86_sse42_pcmpestria128:
14292 Opcode = X86ISD::PCMPESTRI;
14293 X86CC = X86::COND_A;
14295 case Intrinsic::x86_sse42_pcmpistric128:
14296 Opcode = X86ISD::PCMPISTRI;
14297 X86CC = X86::COND_B;
14299 case Intrinsic::x86_sse42_pcmpestric128:
14300 Opcode = X86ISD::PCMPESTRI;
14301 X86CC = X86::COND_B;
14303 case Intrinsic::x86_sse42_pcmpistrio128:
14304 Opcode = X86ISD::PCMPISTRI;
14305 X86CC = X86::COND_O;
14307 case Intrinsic::x86_sse42_pcmpestrio128:
14308 Opcode = X86ISD::PCMPESTRI;
14309 X86CC = X86::COND_O;
14311 case Intrinsic::x86_sse42_pcmpistris128:
14312 Opcode = X86ISD::PCMPISTRI;
14313 X86CC = X86::COND_S;
14315 case Intrinsic::x86_sse42_pcmpestris128:
14316 Opcode = X86ISD::PCMPESTRI;
14317 X86CC = X86::COND_S;
14319 case Intrinsic::x86_sse42_pcmpistriz128:
14320 Opcode = X86ISD::PCMPISTRI;
14321 X86CC = X86::COND_E;
14323 case Intrinsic::x86_sse42_pcmpestriz128:
14324 Opcode = X86ISD::PCMPESTRI;
14325 X86CC = X86::COND_E;
14328 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14329 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14330 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14331 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14332 DAG.getConstant(X86CC, MVT::i8),
14333 SDValue(PCMP.getNode(), 1));
14334 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14337 case Intrinsic::x86_sse42_pcmpistri128:
14338 case Intrinsic::x86_sse42_pcmpestri128: {
14340 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14341 Opcode = X86ISD::PCMPISTRI;
14343 Opcode = X86ISD::PCMPESTRI;
14345 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14346 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14347 return DAG.getNode(Opcode, dl, VTs, NewOps);
14349 case Intrinsic::x86_fma_vfmadd_ps:
14350 case Intrinsic::x86_fma_vfmadd_pd:
14351 case Intrinsic::x86_fma_vfmsub_ps:
14352 case Intrinsic::x86_fma_vfmsub_pd:
14353 case Intrinsic::x86_fma_vfnmadd_ps:
14354 case Intrinsic::x86_fma_vfnmadd_pd:
14355 case Intrinsic::x86_fma_vfnmsub_ps:
14356 case Intrinsic::x86_fma_vfnmsub_pd:
14357 case Intrinsic::x86_fma_vfmaddsub_ps:
14358 case Intrinsic::x86_fma_vfmaddsub_pd:
14359 case Intrinsic::x86_fma_vfmsubadd_ps:
14360 case Intrinsic::x86_fma_vfmsubadd_pd:
14361 case Intrinsic::x86_fma_vfmadd_ps_256:
14362 case Intrinsic::x86_fma_vfmadd_pd_256:
14363 case Intrinsic::x86_fma_vfmsub_ps_256:
14364 case Intrinsic::x86_fma_vfmsub_pd_256:
14365 case Intrinsic::x86_fma_vfnmadd_ps_256:
14366 case Intrinsic::x86_fma_vfnmadd_pd_256:
14367 case Intrinsic::x86_fma_vfnmsub_ps_256:
14368 case Intrinsic::x86_fma_vfnmsub_pd_256:
14369 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14370 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14371 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14372 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14373 case Intrinsic::x86_fma_vfmadd_ps_512:
14374 case Intrinsic::x86_fma_vfmadd_pd_512:
14375 case Intrinsic::x86_fma_vfmsub_ps_512:
14376 case Intrinsic::x86_fma_vfmsub_pd_512:
14377 case Intrinsic::x86_fma_vfnmadd_ps_512:
14378 case Intrinsic::x86_fma_vfnmadd_pd_512:
14379 case Intrinsic::x86_fma_vfnmsub_ps_512:
14380 case Intrinsic::x86_fma_vfnmsub_pd_512:
14381 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14382 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14383 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14384 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14387 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14388 case Intrinsic::x86_fma_vfmadd_ps:
14389 case Intrinsic::x86_fma_vfmadd_pd:
14390 case Intrinsic::x86_fma_vfmadd_ps_256:
14391 case Intrinsic::x86_fma_vfmadd_pd_256:
14392 case Intrinsic::x86_fma_vfmadd_ps_512:
14393 case Intrinsic::x86_fma_vfmadd_pd_512:
14394 Opc = X86ISD::FMADD;
14396 case Intrinsic::x86_fma_vfmsub_ps:
14397 case Intrinsic::x86_fma_vfmsub_pd:
14398 case Intrinsic::x86_fma_vfmsub_ps_256:
14399 case Intrinsic::x86_fma_vfmsub_pd_256:
14400 case Intrinsic::x86_fma_vfmsub_ps_512:
14401 case Intrinsic::x86_fma_vfmsub_pd_512:
14402 Opc = X86ISD::FMSUB;
14404 case Intrinsic::x86_fma_vfnmadd_ps:
14405 case Intrinsic::x86_fma_vfnmadd_pd:
14406 case Intrinsic::x86_fma_vfnmadd_ps_256:
14407 case Intrinsic::x86_fma_vfnmadd_pd_256:
14408 case Intrinsic::x86_fma_vfnmadd_ps_512:
14409 case Intrinsic::x86_fma_vfnmadd_pd_512:
14410 Opc = X86ISD::FNMADD;
14412 case Intrinsic::x86_fma_vfnmsub_ps:
14413 case Intrinsic::x86_fma_vfnmsub_pd:
14414 case Intrinsic::x86_fma_vfnmsub_ps_256:
14415 case Intrinsic::x86_fma_vfnmsub_pd_256:
14416 case Intrinsic::x86_fma_vfnmsub_ps_512:
14417 case Intrinsic::x86_fma_vfnmsub_pd_512:
14418 Opc = X86ISD::FNMSUB;
14420 case Intrinsic::x86_fma_vfmaddsub_ps:
14421 case Intrinsic::x86_fma_vfmaddsub_pd:
14422 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14423 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14424 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14425 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14426 Opc = X86ISD::FMADDSUB;
14428 case Intrinsic::x86_fma_vfmsubadd_ps:
14429 case Intrinsic::x86_fma_vfmsubadd_pd:
14430 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14431 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14432 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14433 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14434 Opc = X86ISD::FMSUBADD;
14438 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14439 Op.getOperand(2), Op.getOperand(3));
14444 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14445 SDValue Src, SDValue Mask, SDValue Base,
14446 SDValue Index, SDValue ScaleOp, SDValue Chain,
14447 const X86Subtarget * Subtarget) {
14449 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14450 assert(C && "Invalid scale type");
14451 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14452 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14453 Index.getSimpleValueType().getVectorNumElements());
14455 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14457 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14459 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14460 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14461 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14462 SDValue Segment = DAG.getRegister(0, MVT::i32);
14463 if (Src.getOpcode() == ISD::UNDEF)
14464 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14465 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14466 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14467 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14468 return DAG.getMergeValues(RetOps, dl);
14471 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14472 SDValue Src, SDValue Mask, SDValue Base,
14473 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14475 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14476 assert(C && "Invalid scale type");
14477 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14478 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14479 SDValue Segment = DAG.getRegister(0, MVT::i32);
14480 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14481 Index.getSimpleValueType().getVectorNumElements());
14483 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14485 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14487 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14488 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14489 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14490 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14491 return SDValue(Res, 1);
14494 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14495 SDValue Mask, SDValue Base, SDValue Index,
14496 SDValue ScaleOp, SDValue Chain) {
14498 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14499 assert(C && "Invalid scale type");
14500 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14501 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14502 SDValue Segment = DAG.getRegister(0, MVT::i32);
14504 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14506 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14508 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14510 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14511 //SDVTList VTs = DAG.getVTList(MVT::Other);
14512 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14513 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14514 return SDValue(Res, 0);
14517 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14518 // read performance monitor counters (x86_rdpmc).
14519 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14520 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14521 SmallVectorImpl<SDValue> &Results) {
14522 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14523 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14526 // The ECX register is used to select the index of the performance counter
14528 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14530 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14532 // Reads the content of a 64-bit performance counter and returns it in the
14533 // registers EDX:EAX.
14534 if (Subtarget->is64Bit()) {
14535 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14536 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14539 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14540 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14543 Chain = HI.getValue(1);
14545 if (Subtarget->is64Bit()) {
14546 // The EAX register is loaded with the low-order 32 bits. The EDX register
14547 // is loaded with the supported high-order bits of the counter.
14548 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14549 DAG.getConstant(32, MVT::i8));
14550 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14551 Results.push_back(Chain);
14555 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14556 SDValue Ops[] = { LO, HI };
14557 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14558 Results.push_back(Pair);
14559 Results.push_back(Chain);
14562 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14563 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14564 // also used to custom lower READCYCLECOUNTER nodes.
14565 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14566 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14567 SmallVectorImpl<SDValue> &Results) {
14568 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14569 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14572 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14573 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14574 // and the EAX register is loaded with the low-order 32 bits.
14575 if (Subtarget->is64Bit()) {
14576 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14577 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14580 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14581 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14584 SDValue Chain = HI.getValue(1);
14586 if (Opcode == X86ISD::RDTSCP_DAG) {
14587 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14589 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14590 // the ECX register. Add 'ecx' explicitly to the chain.
14591 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14593 // Explicitly store the content of ECX at the location passed in input
14594 // to the 'rdtscp' intrinsic.
14595 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14596 MachinePointerInfo(), false, false, 0);
14599 if (Subtarget->is64Bit()) {
14600 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14601 // the EAX register is loaded with the low-order 32 bits.
14602 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14603 DAG.getConstant(32, MVT::i8));
14604 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14605 Results.push_back(Chain);
14609 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14610 SDValue Ops[] = { LO, HI };
14611 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14612 Results.push_back(Pair);
14613 Results.push_back(Chain);
14616 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14617 SelectionDAG &DAG) {
14618 SmallVector<SDValue, 2> Results;
14620 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14622 return DAG.getMergeValues(Results, DL);
14625 enum IntrinsicType {
14626 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14629 struct IntrinsicData {
14630 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14631 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14632 IntrinsicType Type;
14637 std::map < unsigned, IntrinsicData> IntrMap;
14638 static void InitIntinsicsMap() {
14639 static bool Initialized = false;
14642 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14643 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14644 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14645 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14646 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14647 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14648 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14649 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14650 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14651 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14652 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14653 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14654 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14655 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14656 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14657 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14658 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14659 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14661 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14662 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14663 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14664 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14665 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14666 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14667 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14668 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14669 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14670 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14671 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14672 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14673 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14674 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14675 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14676 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14678 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14679 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14680 X86::VGATHERPF1QPSm)));
14681 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14682 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14683 X86::VGATHERPF1QPDm)));
14684 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14685 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14686 X86::VGATHERPF1DPDm)));
14687 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14688 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14689 X86::VGATHERPF1DPSm)));
14690 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14691 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14692 X86::VSCATTERPF1QPSm)));
14693 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14694 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14695 X86::VSCATTERPF1QPDm)));
14696 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14697 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14698 X86::VSCATTERPF1DPDm)));
14699 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14700 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14701 X86::VSCATTERPF1DPSm)));
14702 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14703 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14704 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14705 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14706 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14707 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14708 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14709 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14710 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14711 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14712 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14713 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14714 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14715 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14716 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14717 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14718 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14719 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14720 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14721 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14722 Initialized = true;
14725 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14726 SelectionDAG &DAG) {
14727 InitIntinsicsMap();
14728 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14729 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14730 if (itr == IntrMap.end())
14734 IntrinsicData Intr = itr->second;
14735 switch(Intr.Type) {
14738 // Emit the node with the right value type.
14739 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14740 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14742 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14743 // Otherwise return the value from Rand, which is always 0, casted to i32.
14744 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14745 DAG.getConstant(1, Op->getValueType(1)),
14746 DAG.getConstant(X86::COND_B, MVT::i32),
14747 SDValue(Result.getNode(), 1) };
14748 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14749 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14752 // Return { result, isValid, chain }.
14753 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14754 SDValue(Result.getNode(), 2));
14757 //gather(v1, mask, index, base, scale);
14758 SDValue Chain = Op.getOperand(0);
14759 SDValue Src = Op.getOperand(2);
14760 SDValue Base = Op.getOperand(3);
14761 SDValue Index = Op.getOperand(4);
14762 SDValue Mask = Op.getOperand(5);
14763 SDValue Scale = Op.getOperand(6);
14764 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14768 //scatter(base, mask, index, v1, scale);
14769 SDValue Chain = Op.getOperand(0);
14770 SDValue Base = Op.getOperand(2);
14771 SDValue Mask = Op.getOperand(3);
14772 SDValue Index = Op.getOperand(4);
14773 SDValue Src = Op.getOperand(5);
14774 SDValue Scale = Op.getOperand(6);
14775 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14778 SDValue Hint = Op.getOperand(6);
14780 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14781 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14782 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14783 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14784 SDValue Chain = Op.getOperand(0);
14785 SDValue Mask = Op.getOperand(2);
14786 SDValue Index = Op.getOperand(3);
14787 SDValue Base = Op.getOperand(4);
14788 SDValue Scale = Op.getOperand(5);
14789 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14791 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14793 SmallVector<SDValue, 2> Results;
14794 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14795 return DAG.getMergeValues(Results, dl);
14797 // Read Performance Monitoring Counters.
14799 SmallVector<SDValue, 2> Results;
14800 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14801 return DAG.getMergeValues(Results, dl);
14803 // XTEST intrinsics.
14805 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14806 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14807 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14808 DAG.getConstant(X86::COND_NE, MVT::i8),
14810 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14811 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14812 Ret, SDValue(InTrans.getNode(), 1));
14815 llvm_unreachable("Unknown Intrinsic Type");
14818 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14819 SelectionDAG &DAG) const {
14820 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14821 MFI->setReturnAddressIsTaken(true);
14823 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14826 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14828 EVT PtrVT = getPointerTy();
14831 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14832 const X86RegisterInfo *RegInfo =
14833 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14834 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14835 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14836 DAG.getNode(ISD::ADD, dl, PtrVT,
14837 FrameAddr, Offset),
14838 MachinePointerInfo(), false, false, false, 0);
14841 // Just load the return address.
14842 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14843 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14844 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14847 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14848 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14849 MFI->setFrameAddressIsTaken(true);
14851 EVT VT = Op.getValueType();
14852 SDLoc dl(Op); // FIXME probably not meaningful
14853 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14854 const X86RegisterInfo *RegInfo =
14855 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14856 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14857 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14858 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14859 "Invalid Frame Register!");
14860 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14862 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14863 MachinePointerInfo(),
14864 false, false, false, 0);
14868 // FIXME? Maybe this could be a TableGen attribute on some registers and
14869 // this table could be generated automatically from RegInfo.
14870 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14872 unsigned Reg = StringSwitch<unsigned>(RegName)
14873 .Case("esp", X86::ESP)
14874 .Case("rsp", X86::RSP)
14878 report_fatal_error("Invalid register name global variable");
14881 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14882 SelectionDAG &DAG) const {
14883 const X86RegisterInfo *RegInfo =
14884 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14885 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14888 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14889 SDValue Chain = Op.getOperand(0);
14890 SDValue Offset = Op.getOperand(1);
14891 SDValue Handler = Op.getOperand(2);
14894 EVT PtrVT = getPointerTy();
14895 const X86RegisterInfo *RegInfo =
14896 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14897 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14898 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14899 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14900 "Invalid Frame Register!");
14901 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14902 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14904 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14905 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14906 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14907 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14909 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14911 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14912 DAG.getRegister(StoreAddrReg, PtrVT));
14915 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14916 SelectionDAG &DAG) const {
14918 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14919 DAG.getVTList(MVT::i32, MVT::Other),
14920 Op.getOperand(0), Op.getOperand(1));
14923 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14924 SelectionDAG &DAG) const {
14926 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14927 Op.getOperand(0), Op.getOperand(1));
14930 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14931 return Op.getOperand(0);
14934 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14935 SelectionDAG &DAG) const {
14936 SDValue Root = Op.getOperand(0);
14937 SDValue Trmp = Op.getOperand(1); // trampoline
14938 SDValue FPtr = Op.getOperand(2); // nested function
14939 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14942 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14943 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14945 if (Subtarget->is64Bit()) {
14946 SDValue OutChains[6];
14948 // Large code-model.
14949 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14950 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14952 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14953 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14955 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14957 // Load the pointer to the nested function into R11.
14958 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14959 SDValue Addr = Trmp;
14960 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14961 Addr, MachinePointerInfo(TrmpAddr),
14964 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14965 DAG.getConstant(2, MVT::i64));
14966 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14967 MachinePointerInfo(TrmpAddr, 2),
14970 // Load the 'nest' parameter value into R10.
14971 // R10 is specified in X86CallingConv.td
14972 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14973 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14974 DAG.getConstant(10, MVT::i64));
14975 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14976 Addr, MachinePointerInfo(TrmpAddr, 10),
14979 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14980 DAG.getConstant(12, MVT::i64));
14981 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14982 MachinePointerInfo(TrmpAddr, 12),
14985 // Jump to the nested function.
14986 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14987 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14988 DAG.getConstant(20, MVT::i64));
14989 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14990 Addr, MachinePointerInfo(TrmpAddr, 20),
14993 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14994 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14995 DAG.getConstant(22, MVT::i64));
14996 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14997 MachinePointerInfo(TrmpAddr, 22),
15000 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15002 const Function *Func =
15003 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15004 CallingConv::ID CC = Func->getCallingConv();
15009 llvm_unreachable("Unsupported calling convention");
15010 case CallingConv::C:
15011 case CallingConv::X86_StdCall: {
15012 // Pass 'nest' parameter in ECX.
15013 // Must be kept in sync with X86CallingConv.td
15014 NestReg = X86::ECX;
15016 // Check that ECX wasn't needed by an 'inreg' parameter.
15017 FunctionType *FTy = Func->getFunctionType();
15018 const AttributeSet &Attrs = Func->getAttributes();
15020 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15021 unsigned InRegCount = 0;
15024 for (FunctionType::param_iterator I = FTy->param_begin(),
15025 E = FTy->param_end(); I != E; ++I, ++Idx)
15026 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15027 // FIXME: should only count parameters that are lowered to integers.
15028 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15030 if (InRegCount > 2) {
15031 report_fatal_error("Nest register in use - reduce number of inreg"
15037 case CallingConv::X86_FastCall:
15038 case CallingConv::X86_ThisCall:
15039 case CallingConv::Fast:
15040 // Pass 'nest' parameter in EAX.
15041 // Must be kept in sync with X86CallingConv.td
15042 NestReg = X86::EAX;
15046 SDValue OutChains[4];
15047 SDValue Addr, Disp;
15049 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15050 DAG.getConstant(10, MVT::i32));
15051 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15053 // This is storing the opcode for MOV32ri.
15054 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15055 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15056 OutChains[0] = DAG.getStore(Root, dl,
15057 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15058 Trmp, MachinePointerInfo(TrmpAddr),
15061 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15062 DAG.getConstant(1, MVT::i32));
15063 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15064 MachinePointerInfo(TrmpAddr, 1),
15067 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15068 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15069 DAG.getConstant(5, MVT::i32));
15070 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15071 MachinePointerInfo(TrmpAddr, 5),
15074 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15075 DAG.getConstant(6, MVT::i32));
15076 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15077 MachinePointerInfo(TrmpAddr, 6),
15080 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15084 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15085 SelectionDAG &DAG) const {
15087 The rounding mode is in bits 11:10 of FPSR, and has the following
15089 00 Round to nearest
15094 FLT_ROUNDS, on the other hand, expects the following:
15101 To perform the conversion, we do:
15102 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15105 MachineFunction &MF = DAG.getMachineFunction();
15106 const TargetMachine &TM = MF.getTarget();
15107 const TargetFrameLowering &TFI = *TM.getFrameLowering();
15108 unsigned StackAlignment = TFI.getStackAlignment();
15109 MVT VT = Op.getSimpleValueType();
15112 // Save FP Control Word to stack slot
15113 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15114 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15116 MachineMemOperand *MMO =
15117 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15118 MachineMemOperand::MOStore, 2, 2);
15120 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15121 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15122 DAG.getVTList(MVT::Other),
15123 Ops, MVT::i16, MMO);
15125 // Load FP Control Word from stack slot
15126 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15127 MachinePointerInfo(), false, false, false, 0);
15129 // Transform as necessary
15131 DAG.getNode(ISD::SRL, DL, MVT::i16,
15132 DAG.getNode(ISD::AND, DL, MVT::i16,
15133 CWD, DAG.getConstant(0x800, MVT::i16)),
15134 DAG.getConstant(11, MVT::i8));
15136 DAG.getNode(ISD::SRL, DL, MVT::i16,
15137 DAG.getNode(ISD::AND, DL, MVT::i16,
15138 CWD, DAG.getConstant(0x400, MVT::i16)),
15139 DAG.getConstant(9, MVT::i8));
15142 DAG.getNode(ISD::AND, DL, MVT::i16,
15143 DAG.getNode(ISD::ADD, DL, MVT::i16,
15144 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15145 DAG.getConstant(1, MVT::i16)),
15146 DAG.getConstant(3, MVT::i16));
15148 return DAG.getNode((VT.getSizeInBits() < 16 ?
15149 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15152 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15153 MVT VT = Op.getSimpleValueType();
15155 unsigned NumBits = VT.getSizeInBits();
15158 Op = Op.getOperand(0);
15159 if (VT == MVT::i8) {
15160 // Zero extend to i32 since there is not an i8 bsr.
15162 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15165 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15166 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15167 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15169 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15172 DAG.getConstant(NumBits+NumBits-1, OpVT),
15173 DAG.getConstant(X86::COND_E, MVT::i8),
15176 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15178 // Finally xor with NumBits-1.
15179 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15182 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15186 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15187 MVT VT = Op.getSimpleValueType();
15189 unsigned NumBits = VT.getSizeInBits();
15192 Op = Op.getOperand(0);
15193 if (VT == MVT::i8) {
15194 // Zero extend to i32 since there is not an i8 bsr.
15196 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15199 // Issue a bsr (scan bits in reverse).
15200 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15201 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15203 // And xor with NumBits-1.
15204 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15207 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15211 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15212 MVT VT = Op.getSimpleValueType();
15213 unsigned NumBits = VT.getSizeInBits();
15215 Op = Op.getOperand(0);
15217 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15218 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15219 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15221 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15224 DAG.getConstant(NumBits, VT),
15225 DAG.getConstant(X86::COND_E, MVT::i8),
15228 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15231 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15232 // ones, and then concatenate the result back.
15233 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15234 MVT VT = Op.getSimpleValueType();
15236 assert(VT.is256BitVector() && VT.isInteger() &&
15237 "Unsupported value type for operation");
15239 unsigned NumElems = VT.getVectorNumElements();
15242 // Extract the LHS vectors
15243 SDValue LHS = Op.getOperand(0);
15244 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15245 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15247 // Extract the RHS vectors
15248 SDValue RHS = Op.getOperand(1);
15249 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15250 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15252 MVT EltVT = VT.getVectorElementType();
15253 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15255 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15256 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15257 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15260 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15261 assert(Op.getSimpleValueType().is256BitVector() &&
15262 Op.getSimpleValueType().isInteger() &&
15263 "Only handle AVX 256-bit vector integer operation");
15264 return Lower256IntArith(Op, DAG);
15267 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15268 assert(Op.getSimpleValueType().is256BitVector() &&
15269 Op.getSimpleValueType().isInteger() &&
15270 "Only handle AVX 256-bit vector integer operation");
15271 return Lower256IntArith(Op, DAG);
15274 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15275 SelectionDAG &DAG) {
15277 MVT VT = Op.getSimpleValueType();
15279 // Decompose 256-bit ops into smaller 128-bit ops.
15280 if (VT.is256BitVector() && !Subtarget->hasInt256())
15281 return Lower256IntArith(Op, DAG);
15283 SDValue A = Op.getOperand(0);
15284 SDValue B = Op.getOperand(1);
15286 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15287 if (VT == MVT::v4i32) {
15288 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15289 "Should not custom lower when pmuldq is available!");
15291 // Extract the odd parts.
15292 static const int UnpackMask[] = { 1, -1, 3, -1 };
15293 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15294 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15296 // Multiply the even parts.
15297 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15298 // Now multiply odd parts.
15299 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15301 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15302 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15304 // Merge the two vectors back together with a shuffle. This expands into 2
15306 static const int ShufMask[] = { 0, 4, 2, 6 };
15307 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15310 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15311 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15313 // Ahi = psrlqi(a, 32);
15314 // Bhi = psrlqi(b, 32);
15316 // AloBlo = pmuludq(a, b);
15317 // AloBhi = pmuludq(a, Bhi);
15318 // AhiBlo = pmuludq(Ahi, b);
15320 // AloBhi = psllqi(AloBhi, 32);
15321 // AhiBlo = psllqi(AhiBlo, 32);
15322 // return AloBlo + AloBhi + AhiBlo;
15324 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15325 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15327 // Bit cast to 32-bit vectors for MULUDQ
15328 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15329 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15330 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15331 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15332 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15333 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15335 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15336 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15337 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15339 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15340 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15342 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15343 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15346 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15347 assert(Subtarget->isTargetWin64() && "Unexpected target");
15348 EVT VT = Op.getValueType();
15349 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15350 "Unexpected return type for lowering");
15354 switch (Op->getOpcode()) {
15355 default: llvm_unreachable("Unexpected request for libcall!");
15356 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15357 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15358 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15359 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15360 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15361 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15365 SDValue InChain = DAG.getEntryNode();
15367 TargetLowering::ArgListTy Args;
15368 TargetLowering::ArgListEntry Entry;
15369 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15370 EVT ArgVT = Op->getOperand(i).getValueType();
15371 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15372 "Unexpected argument type for lowering");
15373 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15374 Entry.Node = StackPtr;
15375 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15377 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15378 Entry.Ty = PointerType::get(ArgTy,0);
15379 Entry.isSExt = false;
15380 Entry.isZExt = false;
15381 Args.push_back(Entry);
15384 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15387 TargetLowering::CallLoweringInfo CLI(DAG);
15388 CLI.setDebugLoc(dl).setChain(InChain)
15389 .setCallee(getLibcallCallingConv(LC),
15390 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15391 Callee, std::move(Args), 0)
15392 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15394 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15395 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15398 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15399 SelectionDAG &DAG) {
15400 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15401 EVT VT = Op0.getValueType();
15404 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15405 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15407 // PMULxD operations multiply each even value (starting at 0) of LHS with
15408 // the related value of RHS and produce a widen result.
15409 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15410 // => <2 x i64> <ae|cg>
15412 // In other word, to have all the results, we need to perform two PMULxD:
15413 // 1. one with the even values.
15414 // 2. one with the odd values.
15415 // To achieve #2, with need to place the odd values at an even position.
15417 // Place the odd value at an even position (basically, shift all values 1
15418 // step to the left):
15419 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15420 // <a|b|c|d> => <b|undef|d|undef>
15421 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15422 // <e|f|g|h> => <f|undef|h|undef>
15423 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15425 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15427 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15428 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15430 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15431 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15432 // => <2 x i64> <ae|cg>
15433 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15434 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15435 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15436 // => <2 x i64> <bf|dh>
15437 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15438 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15440 // Shuffle it back into the right order.
15441 // The internal representation is big endian.
15442 // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15443 // and its low part at index 1.
15444 // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15445 // Vector index 0 1 ; 2 3
15446 // We want <ae|bf|cg|dh>
15447 // Vector index 0 2 1 3
15448 // Since each element is seen as 2 x i32, we get:
15449 // high_mask[i] = 2 x vector_index[i]
15450 // low_mask[i] = 2 x vector_index[i] + 1
15451 // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15452 // Size/2 - 1, Size/2 + Size/2 - 1}
15453 // where Size is the number of element of the final vector.
15454 SDValue Highs, Lows;
15455 if (VT == MVT::v8i32) {
15456 const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15457 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15458 const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15459 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15461 const int HighMask[] = {0, 4, 2, 6};
15462 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15463 const int LowMask[] = {1, 5, 3, 7};
15464 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15467 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15468 // unsigned multiply.
15469 if (IsSigned && !Subtarget->hasSSE41()) {
15471 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15472 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15473 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15474 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15475 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15477 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15478 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15481 // THe first result of MUL_LOHI is actually the high value, followed by the
15483 SDValue Ops[] = {Highs, Lows};
15484 return DAG.getMergeValues(Ops, dl);
15487 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15488 const X86Subtarget *Subtarget) {
15489 MVT VT = Op.getSimpleValueType();
15491 SDValue R = Op.getOperand(0);
15492 SDValue Amt = Op.getOperand(1);
15494 // Optimize shl/srl/sra with constant shift amount.
15495 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15496 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15497 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15499 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15500 (Subtarget->hasInt256() &&
15501 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15502 (Subtarget->hasAVX512() &&
15503 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15504 if (Op.getOpcode() == ISD::SHL)
15505 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15507 if (Op.getOpcode() == ISD::SRL)
15508 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15510 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15511 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15515 if (VT == MVT::v16i8) {
15516 if (Op.getOpcode() == ISD::SHL) {
15517 // Make a large shift.
15518 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15519 MVT::v8i16, R, ShiftAmt,
15521 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15522 // Zero out the rightmost bits.
15523 SmallVector<SDValue, 16> V(16,
15524 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15526 return DAG.getNode(ISD::AND, dl, VT, SHL,
15527 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15529 if (Op.getOpcode() == ISD::SRL) {
15530 // Make a large shift.
15531 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15532 MVT::v8i16, R, ShiftAmt,
15534 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15535 // Zero out the leftmost bits.
15536 SmallVector<SDValue, 16> V(16,
15537 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15539 return DAG.getNode(ISD::AND, dl, VT, SRL,
15540 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15542 if (Op.getOpcode() == ISD::SRA) {
15543 if (ShiftAmt == 7) {
15544 // R s>> 7 === R s< 0
15545 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15546 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15549 // R s>> a === ((R u>> a) ^ m) - m
15550 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15551 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15553 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15554 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15555 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15558 llvm_unreachable("Unknown shift opcode.");
15561 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15562 if (Op.getOpcode() == ISD::SHL) {
15563 // Make a large shift.
15564 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15565 MVT::v16i16, R, ShiftAmt,
15567 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15568 // Zero out the rightmost bits.
15569 SmallVector<SDValue, 32> V(32,
15570 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15572 return DAG.getNode(ISD::AND, dl, VT, SHL,
15573 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15575 if (Op.getOpcode() == ISD::SRL) {
15576 // Make a large shift.
15577 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15578 MVT::v16i16, R, ShiftAmt,
15580 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15581 // Zero out the leftmost bits.
15582 SmallVector<SDValue, 32> V(32,
15583 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15585 return DAG.getNode(ISD::AND, dl, VT, SRL,
15586 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15588 if (Op.getOpcode() == ISD::SRA) {
15589 if (ShiftAmt == 7) {
15590 // R s>> 7 === R s< 0
15591 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15592 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15595 // R s>> a === ((R u>> a) ^ m) - m
15596 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15597 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15599 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15600 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15601 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15604 llvm_unreachable("Unknown shift opcode.");
15609 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15610 if (!Subtarget->is64Bit() &&
15611 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15612 Amt.getOpcode() == ISD::BITCAST &&
15613 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15614 Amt = Amt.getOperand(0);
15615 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15616 VT.getVectorNumElements();
15617 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15618 uint64_t ShiftAmt = 0;
15619 for (unsigned i = 0; i != Ratio; ++i) {
15620 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15624 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15626 // Check remaining shift amounts.
15627 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15628 uint64_t ShAmt = 0;
15629 for (unsigned j = 0; j != Ratio; ++j) {
15630 ConstantSDNode *C =
15631 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15635 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15637 if (ShAmt != ShiftAmt)
15640 switch (Op.getOpcode()) {
15642 llvm_unreachable("Unknown shift opcode!");
15644 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15647 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15650 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15658 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15659 const X86Subtarget* Subtarget) {
15660 MVT VT = Op.getSimpleValueType();
15662 SDValue R = Op.getOperand(0);
15663 SDValue Amt = Op.getOperand(1);
15665 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15666 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15667 (Subtarget->hasInt256() &&
15668 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15669 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15670 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15672 EVT EltVT = VT.getVectorElementType();
15674 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15675 unsigned NumElts = VT.getVectorNumElements();
15677 for (i = 0; i != NumElts; ++i) {
15678 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15682 for (j = i; j != NumElts; ++j) {
15683 SDValue Arg = Amt.getOperand(j);
15684 if (Arg.getOpcode() == ISD::UNDEF) continue;
15685 if (Arg != Amt.getOperand(i))
15688 if (i != NumElts && j == NumElts)
15689 BaseShAmt = Amt.getOperand(i);
15691 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15692 Amt = Amt.getOperand(0);
15693 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15694 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15695 SDValue InVec = Amt.getOperand(0);
15696 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15697 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15699 for (; i != NumElts; ++i) {
15700 SDValue Arg = InVec.getOperand(i);
15701 if (Arg.getOpcode() == ISD::UNDEF) continue;
15705 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15706 if (ConstantSDNode *C =
15707 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15708 unsigned SplatIdx =
15709 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15710 if (C->getZExtValue() == SplatIdx)
15711 BaseShAmt = InVec.getOperand(1);
15714 if (!BaseShAmt.getNode())
15715 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15716 DAG.getIntPtrConstant(0));
15720 if (BaseShAmt.getNode()) {
15721 if (EltVT.bitsGT(MVT::i32))
15722 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15723 else if (EltVT.bitsLT(MVT::i32))
15724 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15726 switch (Op.getOpcode()) {
15728 llvm_unreachable("Unknown shift opcode!");
15730 switch (VT.SimpleTy) {
15731 default: return SDValue();
15740 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15743 switch (VT.SimpleTy) {
15744 default: return SDValue();
15751 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15754 switch (VT.SimpleTy) {
15755 default: return SDValue();
15764 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15770 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15771 if (!Subtarget->is64Bit() &&
15772 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15773 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15774 Amt.getOpcode() == ISD::BITCAST &&
15775 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15776 Amt = Amt.getOperand(0);
15777 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15778 VT.getVectorNumElements();
15779 std::vector<SDValue> Vals(Ratio);
15780 for (unsigned i = 0; i != Ratio; ++i)
15781 Vals[i] = Amt.getOperand(i);
15782 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15783 for (unsigned j = 0; j != Ratio; ++j)
15784 if (Vals[j] != Amt.getOperand(i + j))
15787 switch (Op.getOpcode()) {
15789 llvm_unreachable("Unknown shift opcode!");
15791 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15793 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15795 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15802 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15803 SelectionDAG &DAG) {
15804 MVT VT = Op.getSimpleValueType();
15806 SDValue R = Op.getOperand(0);
15807 SDValue Amt = Op.getOperand(1);
15810 assert(VT.isVector() && "Custom lowering only for vector shifts!");
15811 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15813 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15817 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15821 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15823 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15824 if (Subtarget->hasInt256()) {
15825 if (Op.getOpcode() == ISD::SRL &&
15826 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15827 VT == MVT::v4i64 || VT == MVT::v8i32))
15829 if (Op.getOpcode() == ISD::SHL &&
15830 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15831 VT == MVT::v4i64 || VT == MVT::v8i32))
15833 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15837 // If possible, lower this packed shift into a vector multiply instead of
15838 // expanding it into a sequence of scalar shifts.
15839 // Do this only if the vector shift count is a constant build_vector.
15840 if (Op.getOpcode() == ISD::SHL &&
15841 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15842 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15843 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15844 SmallVector<SDValue, 8> Elts;
15845 EVT SVT = VT.getScalarType();
15846 unsigned SVTBits = SVT.getSizeInBits();
15847 const APInt &One = APInt(SVTBits, 1);
15848 unsigned NumElems = VT.getVectorNumElements();
15850 for (unsigned i=0; i !=NumElems; ++i) {
15851 SDValue Op = Amt->getOperand(i);
15852 if (Op->getOpcode() == ISD::UNDEF) {
15853 Elts.push_back(Op);
15857 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15858 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15859 uint64_t ShAmt = C.getZExtValue();
15860 if (ShAmt >= SVTBits) {
15861 Elts.push_back(DAG.getUNDEF(SVT));
15864 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15866 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15867 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15870 // Lower SHL with variable shift amount.
15871 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15872 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15874 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15875 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15876 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15877 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15880 // If possible, lower this shift as a sequence of two shifts by
15881 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15883 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15885 // Could be rewritten as:
15886 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15888 // The advantage is that the two shifts from the example would be
15889 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15890 // the vector shift into four scalar shifts plus four pairs of vector
15892 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15893 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15894 unsigned TargetOpcode = X86ISD::MOVSS;
15895 bool CanBeSimplified;
15896 // The splat value for the first packed shift (the 'X' from the example).
15897 SDValue Amt1 = Amt->getOperand(0);
15898 // The splat value for the second packed shift (the 'Y' from the example).
15899 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15900 Amt->getOperand(2);
15902 // See if it is possible to replace this node with a sequence of
15903 // two shifts followed by a MOVSS/MOVSD
15904 if (VT == MVT::v4i32) {
15905 // Check if it is legal to use a MOVSS.
15906 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15907 Amt2 == Amt->getOperand(3);
15908 if (!CanBeSimplified) {
15909 // Otherwise, check if we can still simplify this node using a MOVSD.
15910 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15911 Amt->getOperand(2) == Amt->getOperand(3);
15912 TargetOpcode = X86ISD::MOVSD;
15913 Amt2 = Amt->getOperand(2);
15916 // Do similar checks for the case where the machine value type
15918 CanBeSimplified = Amt1 == Amt->getOperand(1);
15919 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15920 CanBeSimplified = Amt2 == Amt->getOperand(i);
15922 if (!CanBeSimplified) {
15923 TargetOpcode = X86ISD::MOVSD;
15924 CanBeSimplified = true;
15925 Amt2 = Amt->getOperand(4);
15926 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15927 CanBeSimplified = Amt1 == Amt->getOperand(i);
15928 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15929 CanBeSimplified = Amt2 == Amt->getOperand(j);
15933 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15934 isa<ConstantSDNode>(Amt2)) {
15935 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15936 EVT CastVT = MVT::v4i32;
15938 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15939 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15941 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15942 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15943 if (TargetOpcode == X86ISD::MOVSD)
15944 CastVT = MVT::v2i64;
15945 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15946 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15947 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15949 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15953 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15954 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15957 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15958 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15960 // Turn 'a' into a mask suitable for VSELECT
15961 SDValue VSelM = DAG.getConstant(0x80, VT);
15962 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15963 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15965 SDValue CM1 = DAG.getConstant(0x0f, VT);
15966 SDValue CM2 = DAG.getConstant(0x3f, VT);
15968 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15969 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15970 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15971 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15972 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15975 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15976 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15977 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15979 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15980 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15981 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15982 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15983 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15986 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15987 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15988 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15990 // return VSELECT(r, r+r, a);
15991 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15992 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15996 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15997 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15998 // solution better.
15999 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16000 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16002 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16003 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16004 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16005 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16006 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16009 // Decompose 256-bit shifts into smaller 128-bit shifts.
16010 if (VT.is256BitVector()) {
16011 unsigned NumElems = VT.getVectorNumElements();
16012 MVT EltVT = VT.getVectorElementType();
16013 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16015 // Extract the two vectors
16016 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16017 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16019 // Recreate the shift amount vectors
16020 SDValue Amt1, Amt2;
16021 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16022 // Constant shift amount
16023 SmallVector<SDValue, 4> Amt1Csts;
16024 SmallVector<SDValue, 4> Amt2Csts;
16025 for (unsigned i = 0; i != NumElems/2; ++i)
16026 Amt1Csts.push_back(Amt->getOperand(i));
16027 for (unsigned i = NumElems/2; i != NumElems; ++i)
16028 Amt2Csts.push_back(Amt->getOperand(i));
16030 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16031 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16033 // Variable shift amount
16034 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16035 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16038 // Issue new vector shifts for the smaller types
16039 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16040 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16042 // Concatenate the result back
16043 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16049 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16050 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16051 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16052 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16053 // has only one use.
16054 SDNode *N = Op.getNode();
16055 SDValue LHS = N->getOperand(0);
16056 SDValue RHS = N->getOperand(1);
16057 unsigned BaseOp = 0;
16060 switch (Op.getOpcode()) {
16061 default: llvm_unreachable("Unknown ovf instruction!");
16063 // A subtract of one will be selected as a INC. Note that INC doesn't
16064 // set CF, so we can't do this for UADDO.
16065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16067 BaseOp = X86ISD::INC;
16068 Cond = X86::COND_O;
16071 BaseOp = X86ISD::ADD;
16072 Cond = X86::COND_O;
16075 BaseOp = X86ISD::ADD;
16076 Cond = X86::COND_B;
16079 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16080 // set CF, so we can't do this for USUBO.
16081 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16083 BaseOp = X86ISD::DEC;
16084 Cond = X86::COND_O;
16087 BaseOp = X86ISD::SUB;
16088 Cond = X86::COND_O;
16091 BaseOp = X86ISD::SUB;
16092 Cond = X86::COND_B;
16095 BaseOp = X86ISD::SMUL;
16096 Cond = X86::COND_O;
16098 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16099 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16101 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16104 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16105 DAG.getConstant(X86::COND_O, MVT::i32),
16106 SDValue(Sum.getNode(), 2));
16108 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16112 // Also sets EFLAGS.
16113 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16114 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16117 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16118 DAG.getConstant(Cond, MVT::i32),
16119 SDValue(Sum.getNode(), 1));
16121 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16124 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16125 SelectionDAG &DAG) const {
16127 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16128 MVT VT = Op.getSimpleValueType();
16130 if (!Subtarget->hasSSE2() || !VT.isVector())
16133 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16134 ExtraVT.getScalarType().getSizeInBits();
16136 switch (VT.SimpleTy) {
16137 default: return SDValue();
16140 if (!Subtarget->hasFp256())
16142 if (!Subtarget->hasInt256()) {
16143 // needs to be split
16144 unsigned NumElems = VT.getVectorNumElements();
16146 // Extract the LHS vectors
16147 SDValue LHS = Op.getOperand(0);
16148 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16149 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16151 MVT EltVT = VT.getVectorElementType();
16152 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16154 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16155 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16156 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16158 SDValue Extra = DAG.getValueType(ExtraVT);
16160 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16161 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16163 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16168 SDValue Op0 = Op.getOperand(0);
16169 SDValue Op00 = Op0.getOperand(0);
16171 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16172 if (Op0.getOpcode() == ISD::BITCAST &&
16173 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16174 // (sext (vzext x)) -> (vsext x)
16175 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16176 if (Tmp1.getNode()) {
16177 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16178 // This folding is only valid when the in-reg type is a vector of i8,
16180 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16181 ExtraEltVT == MVT::i32) {
16182 SDValue Tmp1Op0 = Tmp1.getOperand(0);
16183 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16184 "This optimization is invalid without a VZEXT.");
16185 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16191 // If the above didn't work, then just use Shift-Left + Shift-Right.
16192 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16194 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16200 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16201 SelectionDAG &DAG) {
16203 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16204 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16205 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16206 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16208 // The only fence that needs an instruction is a sequentially-consistent
16209 // cross-thread fence.
16210 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16211 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16212 // no-sse2). There isn't any reason to disable it if the target processor
16214 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16215 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16217 SDValue Chain = Op.getOperand(0);
16218 SDValue Zero = DAG.getConstant(0, MVT::i32);
16220 DAG.getRegister(X86::ESP, MVT::i32), // Base
16221 DAG.getTargetConstant(1, MVT::i8), // Scale
16222 DAG.getRegister(0, MVT::i32), // Index
16223 DAG.getTargetConstant(0, MVT::i32), // Disp
16224 DAG.getRegister(0, MVT::i32), // Segment.
16228 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16229 return SDValue(Res, 0);
16232 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16233 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16236 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16237 SelectionDAG &DAG) {
16238 MVT T = Op.getSimpleValueType();
16242 switch(T.SimpleTy) {
16243 default: llvm_unreachable("Invalid value type!");
16244 case MVT::i8: Reg = X86::AL; size = 1; break;
16245 case MVT::i16: Reg = X86::AX; size = 2; break;
16246 case MVT::i32: Reg = X86::EAX; size = 4; break;
16248 assert(Subtarget->is64Bit() && "Node not type legal!");
16249 Reg = X86::RAX; size = 8;
16252 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16253 Op.getOperand(2), SDValue());
16254 SDValue Ops[] = { cpIn.getValue(0),
16257 DAG.getTargetConstant(size, MVT::i8),
16258 cpIn.getValue(1) };
16259 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16260 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16261 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16265 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16266 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16267 MVT::i32, cpOut.getValue(2));
16268 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16269 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16271 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16272 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16273 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16277 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16278 SelectionDAG &DAG) {
16279 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16280 MVT DstVT = Op.getSimpleValueType();
16282 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16283 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16284 if (DstVT != MVT::f64)
16285 // This conversion needs to be expanded.
16288 SDValue InVec = Op->getOperand(0);
16290 unsigned NumElts = SrcVT.getVectorNumElements();
16291 EVT SVT = SrcVT.getVectorElementType();
16293 // Widen the vector in input in the case of MVT::v2i32.
16294 // Example: from MVT::v2i32 to MVT::v4i32.
16295 SmallVector<SDValue, 16> Elts;
16296 for (unsigned i = 0, e = NumElts; i != e; ++i)
16297 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16298 DAG.getIntPtrConstant(i)));
16300 // Explicitly mark the extra elements as Undef.
16301 SDValue Undef = DAG.getUNDEF(SVT);
16302 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16303 Elts.push_back(Undef);
16305 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16306 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16307 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16308 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16309 DAG.getIntPtrConstant(0));
16312 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16313 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16314 assert((DstVT == MVT::i64 ||
16315 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16316 "Unexpected custom BITCAST");
16317 // i64 <=> MMX conversions are Legal.
16318 if (SrcVT==MVT::i64 && DstVT.isVector())
16320 if (DstVT==MVT::i64 && SrcVT.isVector())
16322 // MMX <=> MMX conversions are Legal.
16323 if (SrcVT.isVector() && DstVT.isVector())
16325 // All other conversions need to be expanded.
16329 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16330 SDNode *Node = Op.getNode();
16332 EVT T = Node->getValueType(0);
16333 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16334 DAG.getConstant(0, T), Node->getOperand(2));
16335 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16336 cast<AtomicSDNode>(Node)->getMemoryVT(),
16337 Node->getOperand(0),
16338 Node->getOperand(1), negOp,
16339 cast<AtomicSDNode>(Node)->getMemOperand(),
16340 cast<AtomicSDNode>(Node)->getOrdering(),
16341 cast<AtomicSDNode>(Node)->getSynchScope());
16344 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16345 SDNode *Node = Op.getNode();
16347 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16349 // Convert seq_cst store -> xchg
16350 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16351 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16352 // (The only way to get a 16-byte store is cmpxchg16b)
16353 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16354 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16355 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16356 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16357 cast<AtomicSDNode>(Node)->getMemoryVT(),
16358 Node->getOperand(0),
16359 Node->getOperand(1), Node->getOperand(2),
16360 cast<AtomicSDNode>(Node)->getMemOperand(),
16361 cast<AtomicSDNode>(Node)->getOrdering(),
16362 cast<AtomicSDNode>(Node)->getSynchScope());
16363 return Swap.getValue(1);
16365 // Other atomic stores have a simple pattern.
16369 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16370 EVT VT = Op.getNode()->getSimpleValueType(0);
16372 // Let legalize expand this if it isn't a legal type yet.
16373 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16376 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16379 bool ExtraOp = false;
16380 switch (Op.getOpcode()) {
16381 default: llvm_unreachable("Invalid code");
16382 case ISD::ADDC: Opc = X86ISD::ADD; break;
16383 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16384 case ISD::SUBC: Opc = X86ISD::SUB; break;
16385 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16389 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16391 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16392 Op.getOperand(1), Op.getOperand(2));
16395 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16396 SelectionDAG &DAG) {
16397 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16399 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16400 // which returns the values as { float, float } (in XMM0) or
16401 // { double, double } (which is returned in XMM0, XMM1).
16403 SDValue Arg = Op.getOperand(0);
16404 EVT ArgVT = Arg.getValueType();
16405 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16407 TargetLowering::ArgListTy Args;
16408 TargetLowering::ArgListEntry Entry;
16412 Entry.isSExt = false;
16413 Entry.isZExt = false;
16414 Args.push_back(Entry);
16416 bool isF64 = ArgVT == MVT::f64;
16417 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16418 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16419 // the results are returned via SRet in memory.
16420 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16422 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16424 Type *RetTy = isF64
16425 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16426 : (Type*)VectorType::get(ArgTy, 4);
16428 TargetLowering::CallLoweringInfo CLI(DAG);
16429 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16430 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16432 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16435 // Returned in xmm0 and xmm1.
16436 return CallResult.first;
16438 // Returned in bits 0:31 and 32:64 xmm0.
16439 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16440 CallResult.first, DAG.getIntPtrConstant(0));
16441 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16442 CallResult.first, DAG.getIntPtrConstant(1));
16443 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16444 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16447 /// LowerOperation - Provide custom lowering hooks for some operations.
16449 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16450 switch (Op.getOpcode()) {
16451 default: llvm_unreachable("Should not custom lower this!");
16452 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16453 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16454 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16455 return LowerCMP_SWAP(Op, Subtarget, DAG);
16456 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16457 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16458 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16459 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16460 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16461 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16462 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16463 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16464 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16465 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16466 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16467 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16468 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16469 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16470 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16471 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16472 case ISD::SHL_PARTS:
16473 case ISD::SRA_PARTS:
16474 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16475 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16476 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16477 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16478 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16479 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16480 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16481 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16482 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16483 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16484 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16485 case ISD::FABS: return LowerFABS(Op, DAG);
16486 case ISD::FNEG: return LowerFNEG(Op, DAG);
16487 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16488 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16489 case ISD::SETCC: return LowerSETCC(Op, DAG);
16490 case ISD::SELECT: return LowerSELECT(Op, DAG);
16491 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16492 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16493 case ISD::VASTART: return LowerVASTART(Op, DAG);
16494 case ISD::VAARG: return LowerVAARG(Op, DAG);
16495 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16496 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16497 case ISD::INTRINSIC_VOID:
16498 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16499 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16500 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16501 case ISD::FRAME_TO_ARGS_OFFSET:
16502 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16503 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16504 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16505 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16506 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16507 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16508 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16509 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16510 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16511 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16512 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16513 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16514 case ISD::UMUL_LOHI:
16515 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16518 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16524 case ISD::UMULO: return LowerXALUO(Op, DAG);
16525 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16526 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16530 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16531 case ISD::ADD: return LowerADD(Op, DAG);
16532 case ISD::SUB: return LowerSUB(Op, DAG);
16533 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16537 static void ReplaceATOMIC_LOAD(SDNode *Node,
16538 SmallVectorImpl<SDValue> &Results,
16539 SelectionDAG &DAG) {
16541 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16543 // Convert wide load -> cmpxchg8b/cmpxchg16b
16544 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16545 // (The only way to get a 16-byte load is cmpxchg16b)
16546 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16547 SDValue Zero = DAG.getConstant(0, VT);
16548 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16550 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16551 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16552 cast<AtomicSDNode>(Node)->getMemOperand(),
16553 cast<AtomicSDNode>(Node)->getOrdering(),
16554 cast<AtomicSDNode>(Node)->getOrdering(),
16555 cast<AtomicSDNode>(Node)->getSynchScope());
16556 Results.push_back(Swap.getValue(0));
16557 Results.push_back(Swap.getValue(2));
16560 /// ReplaceNodeResults - Replace a node with an illegal result type
16561 /// with a new node built out of custom code.
16562 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16563 SmallVectorImpl<SDValue>&Results,
16564 SelectionDAG &DAG) const {
16566 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16567 switch (N->getOpcode()) {
16569 llvm_unreachable("Do not know how to custom type legalize this operation!");
16570 case ISD::SIGN_EXTEND_INREG:
16575 // We don't want to expand or promote these.
16582 case ISD::UDIVREM: {
16583 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16584 Results.push_back(V);
16587 case ISD::FP_TO_SINT:
16588 case ISD::FP_TO_UINT: {
16589 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16591 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16594 std::pair<SDValue,SDValue> Vals =
16595 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16596 SDValue FIST = Vals.first, StackSlot = Vals.second;
16597 if (FIST.getNode()) {
16598 EVT VT = N->getValueType(0);
16599 // Return a load from the stack slot.
16600 if (StackSlot.getNode())
16601 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16602 MachinePointerInfo(),
16603 false, false, false, 0));
16605 Results.push_back(FIST);
16609 case ISD::UINT_TO_FP: {
16610 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16611 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16612 N->getValueType(0) != MVT::v2f32)
16614 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16616 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16618 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16619 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16620 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16621 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16622 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16623 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16626 case ISD::FP_ROUND: {
16627 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16629 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16630 Results.push_back(V);
16633 case ISD::INTRINSIC_W_CHAIN: {
16634 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16636 default : llvm_unreachable("Do not know how to custom type "
16637 "legalize this intrinsic operation!");
16638 case Intrinsic::x86_rdtsc:
16639 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16641 case Intrinsic::x86_rdtscp:
16642 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16644 case Intrinsic::x86_rdpmc:
16645 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16648 case ISD::READCYCLECOUNTER: {
16649 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16652 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16653 EVT T = N->getValueType(0);
16654 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16655 bool Regs64bit = T == MVT::i128;
16656 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16657 SDValue cpInL, cpInH;
16658 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16659 DAG.getConstant(0, HalfT));
16660 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16661 DAG.getConstant(1, HalfT));
16662 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16663 Regs64bit ? X86::RAX : X86::EAX,
16665 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16666 Regs64bit ? X86::RDX : X86::EDX,
16667 cpInH, cpInL.getValue(1));
16668 SDValue swapInL, swapInH;
16669 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16670 DAG.getConstant(0, HalfT));
16671 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16672 DAG.getConstant(1, HalfT));
16673 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16674 Regs64bit ? X86::RBX : X86::EBX,
16675 swapInL, cpInH.getValue(1));
16676 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16677 Regs64bit ? X86::RCX : X86::ECX,
16678 swapInH, swapInL.getValue(1));
16679 SDValue Ops[] = { swapInH.getValue(0),
16681 swapInH.getValue(1) };
16682 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16683 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16684 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16685 X86ISD::LCMPXCHG8_DAG;
16686 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16687 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16688 Regs64bit ? X86::RAX : X86::EAX,
16689 HalfT, Result.getValue(1));
16690 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16691 Regs64bit ? X86::RDX : X86::EDX,
16692 HalfT, cpOutL.getValue(2));
16693 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16695 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16696 MVT::i32, cpOutH.getValue(2));
16698 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16699 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16700 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16702 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16703 Results.push_back(Success);
16704 Results.push_back(EFLAGS.getValue(1));
16707 case ISD::ATOMIC_SWAP:
16708 case ISD::ATOMIC_LOAD_ADD:
16709 case ISD::ATOMIC_LOAD_SUB:
16710 case ISD::ATOMIC_LOAD_AND:
16711 case ISD::ATOMIC_LOAD_OR:
16712 case ISD::ATOMIC_LOAD_XOR:
16713 case ISD::ATOMIC_LOAD_NAND:
16714 case ISD::ATOMIC_LOAD_MIN:
16715 case ISD::ATOMIC_LOAD_MAX:
16716 case ISD::ATOMIC_LOAD_UMIN:
16717 case ISD::ATOMIC_LOAD_UMAX:
16718 // Delegate to generic TypeLegalization. Situations we can really handle
16719 // should have already been dealt with by X86AtomicExpand.cpp.
16721 case ISD::ATOMIC_LOAD: {
16722 ReplaceATOMIC_LOAD(N, Results, DAG);
16725 case ISD::BITCAST: {
16726 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16727 EVT DstVT = N->getValueType(0);
16728 EVT SrcVT = N->getOperand(0)->getValueType(0);
16730 if (SrcVT != MVT::f64 ||
16731 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16734 unsigned NumElts = DstVT.getVectorNumElements();
16735 EVT SVT = DstVT.getVectorElementType();
16736 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16737 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16738 MVT::v2f64, N->getOperand(0));
16739 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16741 if (ExperimentalVectorWideningLegalization) {
16742 // If we are legalizing vectors by widening, we already have the desired
16743 // legal vector type, just return it.
16744 Results.push_back(ToVecInt);
16748 SmallVector<SDValue, 8> Elts;
16749 for (unsigned i = 0, e = NumElts; i != e; ++i)
16750 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16751 ToVecInt, DAG.getIntPtrConstant(i)));
16753 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16758 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16760 default: return nullptr;
16761 case X86ISD::BSF: return "X86ISD::BSF";
16762 case X86ISD::BSR: return "X86ISD::BSR";
16763 case X86ISD::SHLD: return "X86ISD::SHLD";
16764 case X86ISD::SHRD: return "X86ISD::SHRD";
16765 case X86ISD::FAND: return "X86ISD::FAND";
16766 case X86ISD::FANDN: return "X86ISD::FANDN";
16767 case X86ISD::FOR: return "X86ISD::FOR";
16768 case X86ISD::FXOR: return "X86ISD::FXOR";
16769 case X86ISD::FSRL: return "X86ISD::FSRL";
16770 case X86ISD::FILD: return "X86ISD::FILD";
16771 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16772 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16773 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16774 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16775 case X86ISD::FLD: return "X86ISD::FLD";
16776 case X86ISD::FST: return "X86ISD::FST";
16777 case X86ISD::CALL: return "X86ISD::CALL";
16778 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16779 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16780 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16781 case X86ISD::BT: return "X86ISD::BT";
16782 case X86ISD::CMP: return "X86ISD::CMP";
16783 case X86ISD::COMI: return "X86ISD::COMI";
16784 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16785 case X86ISD::CMPM: return "X86ISD::CMPM";
16786 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16787 case X86ISD::SETCC: return "X86ISD::SETCC";
16788 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16789 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16790 case X86ISD::CMOV: return "X86ISD::CMOV";
16791 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16792 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16793 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16794 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16795 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16796 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16797 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16798 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16799 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16800 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16801 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16802 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16803 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16804 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16805 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16806 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16807 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16808 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16809 case X86ISD::HADD: return "X86ISD::HADD";
16810 case X86ISD::HSUB: return "X86ISD::HSUB";
16811 case X86ISD::FHADD: return "X86ISD::FHADD";
16812 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16813 case X86ISD::UMAX: return "X86ISD::UMAX";
16814 case X86ISD::UMIN: return "X86ISD::UMIN";
16815 case X86ISD::SMAX: return "X86ISD::SMAX";
16816 case X86ISD::SMIN: return "X86ISD::SMIN";
16817 case X86ISD::FMAX: return "X86ISD::FMAX";
16818 case X86ISD::FMIN: return "X86ISD::FMIN";
16819 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16820 case X86ISD::FMINC: return "X86ISD::FMINC";
16821 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16822 case X86ISD::FRCP: return "X86ISD::FRCP";
16823 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16824 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16825 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16826 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16827 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16828 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16829 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16830 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16831 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16832 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16833 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16834 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16835 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16836 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16837 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16838 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16839 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16840 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16841 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16842 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16843 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16844 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16845 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16846 case X86ISD::VSHL: return "X86ISD::VSHL";
16847 case X86ISD::VSRL: return "X86ISD::VSRL";
16848 case X86ISD::VSRA: return "X86ISD::VSRA";
16849 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16850 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16851 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16852 case X86ISD::CMPP: return "X86ISD::CMPP";
16853 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16854 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16855 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16856 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16857 case X86ISD::ADD: return "X86ISD::ADD";
16858 case X86ISD::SUB: return "X86ISD::SUB";
16859 case X86ISD::ADC: return "X86ISD::ADC";
16860 case X86ISD::SBB: return "X86ISD::SBB";
16861 case X86ISD::SMUL: return "X86ISD::SMUL";
16862 case X86ISD::UMUL: return "X86ISD::UMUL";
16863 case X86ISD::INC: return "X86ISD::INC";
16864 case X86ISD::DEC: return "X86ISD::DEC";
16865 case X86ISD::OR: return "X86ISD::OR";
16866 case X86ISD::XOR: return "X86ISD::XOR";
16867 case X86ISD::AND: return "X86ISD::AND";
16868 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16869 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16870 case X86ISD::PTEST: return "X86ISD::PTEST";
16871 case X86ISD::TESTP: return "X86ISD::TESTP";
16872 case X86ISD::TESTM: return "X86ISD::TESTM";
16873 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16874 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16875 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16876 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16877 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16878 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16879 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16880 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16881 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16882 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16883 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16884 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16885 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16886 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16887 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16888 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16889 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16890 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16891 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16892 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16893 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16894 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16895 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16896 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16897 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16898 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16899 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16900 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16901 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16902 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16903 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16904 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16905 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16906 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16907 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16908 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16909 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16910 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16911 case X86ISD::SAHF: return "X86ISD::SAHF";
16912 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16913 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16914 case X86ISD::FMADD: return "X86ISD::FMADD";
16915 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16916 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16917 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16918 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16919 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16920 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16921 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16922 case X86ISD::XTEST: return "X86ISD::XTEST";
16926 // isLegalAddressingMode - Return true if the addressing mode represented
16927 // by AM is legal for this target, for a load/store of the specified type.
16928 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16930 // X86 supports extremely general addressing modes.
16931 CodeModel::Model M = getTargetMachine().getCodeModel();
16932 Reloc::Model R = getTargetMachine().getRelocationModel();
16934 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16935 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16940 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16942 // If a reference to this global requires an extra load, we can't fold it.
16943 if (isGlobalStubReference(GVFlags))
16946 // If BaseGV requires a register for the PIC base, we cannot also have a
16947 // BaseReg specified.
16948 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16951 // If lower 4G is not available, then we must use rip-relative addressing.
16952 if ((M != CodeModel::Small || R != Reloc::Static) &&
16953 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16957 switch (AM.Scale) {
16963 // These scales always work.
16968 // These scales are formed with basereg+scalereg. Only accept if there is
16973 default: // Other stuff never works.
16980 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16981 unsigned Bits = Ty->getScalarSizeInBits();
16983 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16984 // particularly cheaper than those without.
16988 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16989 // variable shifts just as cheap as scalar ones.
16990 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16993 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16994 // fully general vector.
16998 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16999 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17001 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17002 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17003 return NumBits1 > NumBits2;
17006 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17007 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17010 if (!isTypeLegal(EVT::getEVT(Ty1)))
17013 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17015 // Assuming the caller doesn't have a zeroext or signext return parameter,
17016 // truncation all the way down to i1 is valid.
17020 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17021 return isInt<32>(Imm);
17024 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17025 // Can also use sub to handle negated immediates.
17026 return isInt<32>(Imm);
17029 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17030 if (!VT1.isInteger() || !VT2.isInteger())
17032 unsigned NumBits1 = VT1.getSizeInBits();
17033 unsigned NumBits2 = VT2.getSizeInBits();
17034 return NumBits1 > NumBits2;
17037 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17038 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17039 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17042 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17043 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17044 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17047 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17048 EVT VT1 = Val.getValueType();
17049 if (isZExtFree(VT1, VT2))
17052 if (Val.getOpcode() != ISD::LOAD)
17055 if (!VT1.isSimple() || !VT1.isInteger() ||
17056 !VT2.isSimple() || !VT2.isInteger())
17059 switch (VT1.getSimpleVT().SimpleTy) {
17064 // X86 has 8, 16, and 32-bit zero-extending loads.
17072 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17073 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17076 VT = VT.getScalarType();
17078 if (!VT.isSimple())
17081 switch (VT.getSimpleVT().SimpleTy) {
17092 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17093 // i16 instructions are longer (0x66 prefix) and potentially slower.
17094 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17097 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17098 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17099 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17100 /// are assumed to be legal.
17102 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17104 if (!VT.isSimple())
17107 MVT SVT = VT.getSimpleVT();
17109 // Very little shuffling can be done for 64-bit vectors right now.
17110 if (VT.getSizeInBits() == 64)
17113 // If this is a single-input shuffle with no 128 bit lane crossings we can
17114 // lower it into pshufb.
17115 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17116 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17117 bool isLegal = true;
17118 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17119 if (M[I] >= (int)SVT.getVectorNumElements() ||
17120 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17129 // FIXME: blends, shifts.
17130 return (SVT.getVectorNumElements() == 2 ||
17131 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17132 isMOVLMask(M, SVT) ||
17133 isMOVHLPSMask(M, SVT) ||
17134 isSHUFPMask(M, SVT) ||
17135 isPSHUFDMask(M, SVT) ||
17136 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17137 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17138 isPALIGNRMask(M, SVT, Subtarget) ||
17139 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17140 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17141 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17142 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17143 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17147 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17149 if (!VT.isSimple())
17152 MVT SVT = VT.getSimpleVT();
17153 unsigned NumElts = SVT.getVectorNumElements();
17154 // FIXME: This collection of masks seems suspect.
17157 if (NumElts == 4 && SVT.is128BitVector()) {
17158 return (isMOVLMask(Mask, SVT) ||
17159 isCommutedMOVLMask(Mask, SVT, true) ||
17160 isSHUFPMask(Mask, SVT) ||
17161 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17166 //===----------------------------------------------------------------------===//
17167 // X86 Scheduler Hooks
17168 //===----------------------------------------------------------------------===//
17170 /// Utility function to emit xbegin specifying the start of an RTM region.
17171 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17172 const TargetInstrInfo *TII) {
17173 DebugLoc DL = MI->getDebugLoc();
17175 const BasicBlock *BB = MBB->getBasicBlock();
17176 MachineFunction::iterator I = MBB;
17179 // For the v = xbegin(), we generate
17190 MachineBasicBlock *thisMBB = MBB;
17191 MachineFunction *MF = MBB->getParent();
17192 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17193 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17194 MF->insert(I, mainMBB);
17195 MF->insert(I, sinkMBB);
17197 // Transfer the remainder of BB and its successor edges to sinkMBB.
17198 sinkMBB->splice(sinkMBB->begin(), MBB,
17199 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17200 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17204 // # fallthrough to mainMBB
17205 // # abortion to sinkMBB
17206 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17207 thisMBB->addSuccessor(mainMBB);
17208 thisMBB->addSuccessor(sinkMBB);
17212 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17213 mainMBB->addSuccessor(sinkMBB);
17216 // EAX is live into the sinkMBB
17217 sinkMBB->addLiveIn(X86::EAX);
17218 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17219 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17222 MI->eraseFromParent();
17226 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17227 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17228 // in the .td file.
17229 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17230 const TargetInstrInfo *TII) {
17232 switch (MI->getOpcode()) {
17233 default: llvm_unreachable("illegal opcode!");
17234 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17235 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17236 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17237 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17238 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17239 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17240 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17241 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17244 DebugLoc dl = MI->getDebugLoc();
17245 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17247 unsigned NumArgs = MI->getNumOperands();
17248 for (unsigned i = 1; i < NumArgs; ++i) {
17249 MachineOperand &Op = MI->getOperand(i);
17250 if (!(Op.isReg() && Op.isImplicit()))
17251 MIB.addOperand(Op);
17253 if (MI->hasOneMemOperand())
17254 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17256 BuildMI(*BB, MI, dl,
17257 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17258 .addReg(X86::XMM0);
17260 MI->eraseFromParent();
17264 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17265 // defs in an instruction pattern
17266 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17267 const TargetInstrInfo *TII) {
17269 switch (MI->getOpcode()) {
17270 default: llvm_unreachable("illegal opcode!");
17271 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17272 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17273 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17274 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17275 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17276 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17277 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17278 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17281 DebugLoc dl = MI->getDebugLoc();
17282 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17284 unsigned NumArgs = MI->getNumOperands(); // remove the results
17285 for (unsigned i = 1; i < NumArgs; ++i) {
17286 MachineOperand &Op = MI->getOperand(i);
17287 if (!(Op.isReg() && Op.isImplicit()))
17288 MIB.addOperand(Op);
17290 if (MI->hasOneMemOperand())
17291 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17293 BuildMI(*BB, MI, dl,
17294 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17297 MI->eraseFromParent();
17301 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17302 const TargetInstrInfo *TII,
17303 const X86Subtarget* Subtarget) {
17304 DebugLoc dl = MI->getDebugLoc();
17306 // Address into RAX/EAX, other two args into ECX, EDX.
17307 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17308 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17309 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17310 for (int i = 0; i < X86::AddrNumOperands; ++i)
17311 MIB.addOperand(MI->getOperand(i));
17313 unsigned ValOps = X86::AddrNumOperands;
17314 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17315 .addReg(MI->getOperand(ValOps).getReg());
17316 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17317 .addReg(MI->getOperand(ValOps+1).getReg());
17319 // The instruction doesn't actually take any operands though.
17320 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17322 MI->eraseFromParent(); // The pseudo is gone now.
17326 MachineBasicBlock *
17327 X86TargetLowering::EmitVAARG64WithCustomInserter(
17329 MachineBasicBlock *MBB) const {
17330 // Emit va_arg instruction on X86-64.
17332 // Operands to this pseudo-instruction:
17333 // 0 ) Output : destination address (reg)
17334 // 1-5) Input : va_list address (addr, i64mem)
17335 // 6 ) ArgSize : Size (in bytes) of vararg type
17336 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17337 // 8 ) Align : Alignment of type
17338 // 9 ) EFLAGS (implicit-def)
17340 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17341 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17343 unsigned DestReg = MI->getOperand(0).getReg();
17344 MachineOperand &Base = MI->getOperand(1);
17345 MachineOperand &Scale = MI->getOperand(2);
17346 MachineOperand &Index = MI->getOperand(3);
17347 MachineOperand &Disp = MI->getOperand(4);
17348 MachineOperand &Segment = MI->getOperand(5);
17349 unsigned ArgSize = MI->getOperand(6).getImm();
17350 unsigned ArgMode = MI->getOperand(7).getImm();
17351 unsigned Align = MI->getOperand(8).getImm();
17353 // Memory Reference
17354 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17355 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17356 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17358 // Machine Information
17359 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17360 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17361 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17362 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17363 DebugLoc DL = MI->getDebugLoc();
17365 // struct va_list {
17368 // i64 overflow_area (address)
17369 // i64 reg_save_area (address)
17371 // sizeof(va_list) = 24
17372 // alignment(va_list) = 8
17374 unsigned TotalNumIntRegs = 6;
17375 unsigned TotalNumXMMRegs = 8;
17376 bool UseGPOffset = (ArgMode == 1);
17377 bool UseFPOffset = (ArgMode == 2);
17378 unsigned MaxOffset = TotalNumIntRegs * 8 +
17379 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17381 /* Align ArgSize to a multiple of 8 */
17382 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17383 bool NeedsAlign = (Align > 8);
17385 MachineBasicBlock *thisMBB = MBB;
17386 MachineBasicBlock *overflowMBB;
17387 MachineBasicBlock *offsetMBB;
17388 MachineBasicBlock *endMBB;
17390 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17391 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17392 unsigned OffsetReg = 0;
17394 if (!UseGPOffset && !UseFPOffset) {
17395 // If we only pull from the overflow region, we don't create a branch.
17396 // We don't need to alter control flow.
17397 OffsetDestReg = 0; // unused
17398 OverflowDestReg = DestReg;
17400 offsetMBB = nullptr;
17401 overflowMBB = thisMBB;
17404 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17405 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17406 // If not, pull from overflow_area. (branch to overflowMBB)
17411 // offsetMBB overflowMBB
17416 // Registers for the PHI in endMBB
17417 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17418 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17420 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17421 MachineFunction *MF = MBB->getParent();
17422 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17423 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17424 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17426 MachineFunction::iterator MBBIter = MBB;
17429 // Insert the new basic blocks
17430 MF->insert(MBBIter, offsetMBB);
17431 MF->insert(MBBIter, overflowMBB);
17432 MF->insert(MBBIter, endMBB);
17434 // Transfer the remainder of MBB and its successor edges to endMBB.
17435 endMBB->splice(endMBB->begin(), thisMBB,
17436 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17437 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17439 // Make offsetMBB and overflowMBB successors of thisMBB
17440 thisMBB->addSuccessor(offsetMBB);
17441 thisMBB->addSuccessor(overflowMBB);
17443 // endMBB is a successor of both offsetMBB and overflowMBB
17444 offsetMBB->addSuccessor(endMBB);
17445 overflowMBB->addSuccessor(endMBB);
17447 // Load the offset value into a register
17448 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17449 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17453 .addDisp(Disp, UseFPOffset ? 4 : 0)
17454 .addOperand(Segment)
17455 .setMemRefs(MMOBegin, MMOEnd);
17457 // Check if there is enough room left to pull this argument.
17458 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17460 .addImm(MaxOffset + 8 - ArgSizeA8);
17462 // Branch to "overflowMBB" if offset >= max
17463 // Fall through to "offsetMBB" otherwise
17464 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17465 .addMBB(overflowMBB);
17468 // In offsetMBB, emit code to use the reg_save_area.
17470 assert(OffsetReg != 0);
17472 // Read the reg_save_area address.
17473 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17474 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17479 .addOperand(Segment)
17480 .setMemRefs(MMOBegin, MMOEnd);
17482 // Zero-extend the offset
17483 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17484 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17487 .addImm(X86::sub_32bit);
17489 // Add the offset to the reg_save_area to get the final address.
17490 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17491 .addReg(OffsetReg64)
17492 .addReg(RegSaveReg);
17494 // Compute the offset for the next argument
17495 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17496 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17498 .addImm(UseFPOffset ? 16 : 8);
17500 // Store it back into the va_list.
17501 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17505 .addDisp(Disp, UseFPOffset ? 4 : 0)
17506 .addOperand(Segment)
17507 .addReg(NextOffsetReg)
17508 .setMemRefs(MMOBegin, MMOEnd);
17511 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17516 // Emit code to use overflow area
17519 // Load the overflow_area address into a register.
17520 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17521 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17526 .addOperand(Segment)
17527 .setMemRefs(MMOBegin, MMOEnd);
17529 // If we need to align it, do so. Otherwise, just copy the address
17530 // to OverflowDestReg.
17532 // Align the overflow address
17533 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17534 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17536 // aligned_addr = (addr + (align-1)) & ~(align-1)
17537 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17538 .addReg(OverflowAddrReg)
17541 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17543 .addImm(~(uint64_t)(Align-1));
17545 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17546 .addReg(OverflowAddrReg);
17549 // Compute the next overflow address after this argument.
17550 // (the overflow address should be kept 8-byte aligned)
17551 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17552 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17553 .addReg(OverflowDestReg)
17554 .addImm(ArgSizeA8);
17556 // Store the new overflow address.
17557 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17562 .addOperand(Segment)
17563 .addReg(NextAddrReg)
17564 .setMemRefs(MMOBegin, MMOEnd);
17566 // If we branched, emit the PHI to the front of endMBB.
17568 BuildMI(*endMBB, endMBB->begin(), DL,
17569 TII->get(X86::PHI), DestReg)
17570 .addReg(OffsetDestReg).addMBB(offsetMBB)
17571 .addReg(OverflowDestReg).addMBB(overflowMBB);
17574 // Erase the pseudo instruction
17575 MI->eraseFromParent();
17580 MachineBasicBlock *
17581 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17583 MachineBasicBlock *MBB) const {
17584 // Emit code to save XMM registers to the stack. The ABI says that the
17585 // number of registers to save is given in %al, so it's theoretically
17586 // possible to do an indirect jump trick to avoid saving all of them,
17587 // however this code takes a simpler approach and just executes all
17588 // of the stores if %al is non-zero. It's less code, and it's probably
17589 // easier on the hardware branch predictor, and stores aren't all that
17590 // expensive anyway.
17592 // Create the new basic blocks. One block contains all the XMM stores,
17593 // and one block is the final destination regardless of whether any
17594 // stores were performed.
17595 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17596 MachineFunction *F = MBB->getParent();
17597 MachineFunction::iterator MBBIter = MBB;
17599 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17600 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17601 F->insert(MBBIter, XMMSaveMBB);
17602 F->insert(MBBIter, EndMBB);
17604 // Transfer the remainder of MBB and its successor edges to EndMBB.
17605 EndMBB->splice(EndMBB->begin(), MBB,
17606 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17607 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17609 // The original block will now fall through to the XMM save block.
17610 MBB->addSuccessor(XMMSaveMBB);
17611 // The XMMSaveMBB will fall through to the end block.
17612 XMMSaveMBB->addSuccessor(EndMBB);
17614 // Now add the instructions.
17615 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17616 DebugLoc DL = MI->getDebugLoc();
17618 unsigned CountReg = MI->getOperand(0).getReg();
17619 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17620 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17622 if (!Subtarget->isTargetWin64()) {
17623 // If %al is 0, branch around the XMM save block.
17624 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17625 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17626 MBB->addSuccessor(EndMBB);
17629 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17630 // that was just emitted, but clearly shouldn't be "saved".
17631 assert((MI->getNumOperands() <= 3 ||
17632 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17633 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17634 && "Expected last argument to be EFLAGS");
17635 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17636 // In the XMM save block, save all the XMM argument registers.
17637 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17638 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17639 MachineMemOperand *MMO =
17640 F->getMachineMemOperand(
17641 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17642 MachineMemOperand::MOStore,
17643 /*Size=*/16, /*Align=*/16);
17644 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17645 .addFrameIndex(RegSaveFrameIndex)
17646 .addImm(/*Scale=*/1)
17647 .addReg(/*IndexReg=*/0)
17648 .addImm(/*Disp=*/Offset)
17649 .addReg(/*Segment=*/0)
17650 .addReg(MI->getOperand(i).getReg())
17651 .addMemOperand(MMO);
17654 MI->eraseFromParent(); // The pseudo instruction is gone now.
17659 // The EFLAGS operand of SelectItr might be missing a kill marker
17660 // because there were multiple uses of EFLAGS, and ISel didn't know
17661 // which to mark. Figure out whether SelectItr should have had a
17662 // kill marker, and set it if it should. Returns the correct kill
17664 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17665 MachineBasicBlock* BB,
17666 const TargetRegisterInfo* TRI) {
17667 // Scan forward through BB for a use/def of EFLAGS.
17668 MachineBasicBlock::iterator miI(std::next(SelectItr));
17669 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17670 const MachineInstr& mi = *miI;
17671 if (mi.readsRegister(X86::EFLAGS))
17673 if (mi.definesRegister(X86::EFLAGS))
17674 break; // Should have kill-flag - update below.
17677 // If we hit the end of the block, check whether EFLAGS is live into a
17679 if (miI == BB->end()) {
17680 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17681 sEnd = BB->succ_end();
17682 sItr != sEnd; ++sItr) {
17683 MachineBasicBlock* succ = *sItr;
17684 if (succ->isLiveIn(X86::EFLAGS))
17689 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17690 // out. SelectMI should have a kill flag on EFLAGS.
17691 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17695 MachineBasicBlock *
17696 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17697 MachineBasicBlock *BB) const {
17698 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17699 DebugLoc DL = MI->getDebugLoc();
17701 // To "insert" a SELECT_CC instruction, we actually have to insert the
17702 // diamond control-flow pattern. The incoming instruction knows the
17703 // destination vreg to set, the condition code register to branch on, the
17704 // true/false values to select between, and a branch opcode to use.
17705 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17706 MachineFunction::iterator It = BB;
17712 // cmpTY ccX, r1, r2
17714 // fallthrough --> copy0MBB
17715 MachineBasicBlock *thisMBB = BB;
17716 MachineFunction *F = BB->getParent();
17717 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17718 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17719 F->insert(It, copy0MBB);
17720 F->insert(It, sinkMBB);
17722 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17723 // live into the sink and copy blocks.
17724 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17725 if (!MI->killsRegister(X86::EFLAGS) &&
17726 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17727 copy0MBB->addLiveIn(X86::EFLAGS);
17728 sinkMBB->addLiveIn(X86::EFLAGS);
17731 // Transfer the remainder of BB and its successor edges to sinkMBB.
17732 sinkMBB->splice(sinkMBB->begin(), BB,
17733 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17734 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17736 // Add the true and fallthrough blocks as its successors.
17737 BB->addSuccessor(copy0MBB);
17738 BB->addSuccessor(sinkMBB);
17740 // Create the conditional branch instruction.
17742 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17743 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17746 // %FalseValue = ...
17747 // # fallthrough to sinkMBB
17748 copy0MBB->addSuccessor(sinkMBB);
17751 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17753 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17754 TII->get(X86::PHI), MI->getOperand(0).getReg())
17755 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17756 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17758 MI->eraseFromParent(); // The pseudo instruction is gone now.
17762 MachineBasicBlock *
17763 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17764 bool Is64Bit) const {
17765 MachineFunction *MF = BB->getParent();
17766 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17767 DebugLoc DL = MI->getDebugLoc();
17768 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17770 assert(MF->shouldSplitStack());
17772 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17773 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17776 // ... [Till the alloca]
17777 // If stacklet is not large enough, jump to mallocMBB
17780 // Allocate by subtracting from RSP
17781 // Jump to continueMBB
17784 // Allocate by call to runtime
17788 // [rest of original BB]
17791 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17792 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17793 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17795 MachineRegisterInfo &MRI = MF->getRegInfo();
17796 const TargetRegisterClass *AddrRegClass =
17797 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17799 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17800 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17801 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17802 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17803 sizeVReg = MI->getOperand(1).getReg(),
17804 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17806 MachineFunction::iterator MBBIter = BB;
17809 MF->insert(MBBIter, bumpMBB);
17810 MF->insert(MBBIter, mallocMBB);
17811 MF->insert(MBBIter, continueMBB);
17813 continueMBB->splice(continueMBB->begin(), BB,
17814 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17815 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17817 // Add code to the main basic block to check if the stack limit has been hit,
17818 // and if so, jump to mallocMBB otherwise to bumpMBB.
17819 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17820 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17821 .addReg(tmpSPVReg).addReg(sizeVReg);
17822 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17823 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17824 .addReg(SPLimitVReg);
17825 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17827 // bumpMBB simply decreases the stack pointer, since we know the current
17828 // stacklet has enough space.
17829 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17830 .addReg(SPLimitVReg);
17831 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17832 .addReg(SPLimitVReg);
17833 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17835 // Calls into a routine in libgcc to allocate more space from the heap.
17836 const uint32_t *RegMask =
17837 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17839 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17841 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17842 .addExternalSymbol("__morestack_allocate_stack_space")
17843 .addRegMask(RegMask)
17844 .addReg(X86::RDI, RegState::Implicit)
17845 .addReg(X86::RAX, RegState::ImplicitDefine);
17847 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17849 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17850 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17851 .addExternalSymbol("__morestack_allocate_stack_space")
17852 .addRegMask(RegMask)
17853 .addReg(X86::EAX, RegState::ImplicitDefine);
17857 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17860 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17861 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17862 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17864 // Set up the CFG correctly.
17865 BB->addSuccessor(bumpMBB);
17866 BB->addSuccessor(mallocMBB);
17867 mallocMBB->addSuccessor(continueMBB);
17868 bumpMBB->addSuccessor(continueMBB);
17870 // Take care of the PHI nodes.
17871 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17872 MI->getOperand(0).getReg())
17873 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17874 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17876 // Delete the original pseudo instruction.
17877 MI->eraseFromParent();
17880 return continueMBB;
17883 MachineBasicBlock *
17884 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17885 MachineBasicBlock *BB) const {
17886 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17887 DebugLoc DL = MI->getDebugLoc();
17889 assert(!Subtarget->isTargetMacho());
17891 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17892 // non-trivial part is impdef of ESP.
17894 if (Subtarget->isTargetWin64()) {
17895 if (Subtarget->isTargetCygMing()) {
17896 // ___chkstk(Mingw64):
17897 // Clobbers R10, R11, RAX and EFLAGS.
17899 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17900 .addExternalSymbol("___chkstk")
17901 .addReg(X86::RAX, RegState::Implicit)
17902 .addReg(X86::RSP, RegState::Implicit)
17903 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17904 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17905 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17907 // __chkstk(MSVCRT): does not update stack pointer.
17908 // Clobbers R10, R11 and EFLAGS.
17909 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17910 .addExternalSymbol("__chkstk")
17911 .addReg(X86::RAX, RegState::Implicit)
17912 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17913 // RAX has the offset to be subtracted from RSP.
17914 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17919 const char *StackProbeSymbol =
17920 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17922 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17923 .addExternalSymbol(StackProbeSymbol)
17924 .addReg(X86::EAX, RegState::Implicit)
17925 .addReg(X86::ESP, RegState::Implicit)
17926 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17927 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17928 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17931 MI->eraseFromParent(); // The pseudo instruction is gone now.
17935 MachineBasicBlock *
17936 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17937 MachineBasicBlock *BB) const {
17938 // This is pretty easy. We're taking the value that we received from
17939 // our load from the relocation, sticking it in either RDI (x86-64)
17940 // or EAX and doing an indirect call. The return value will then
17941 // be in the normal return register.
17942 MachineFunction *F = BB->getParent();
17943 const X86InstrInfo *TII
17944 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17945 DebugLoc DL = MI->getDebugLoc();
17947 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17948 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17950 // Get a register mask for the lowered call.
17951 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17952 // proper register mask.
17953 const uint32_t *RegMask =
17954 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17955 if (Subtarget->is64Bit()) {
17956 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17957 TII->get(X86::MOV64rm), X86::RDI)
17959 .addImm(0).addReg(0)
17960 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17961 MI->getOperand(3).getTargetFlags())
17963 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17964 addDirectMem(MIB, X86::RDI);
17965 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17966 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17967 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17968 TII->get(X86::MOV32rm), X86::EAX)
17970 .addImm(0).addReg(0)
17971 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17972 MI->getOperand(3).getTargetFlags())
17974 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17975 addDirectMem(MIB, X86::EAX);
17976 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17978 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17979 TII->get(X86::MOV32rm), X86::EAX)
17980 .addReg(TII->getGlobalBaseReg(F))
17981 .addImm(0).addReg(0)
17982 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17983 MI->getOperand(3).getTargetFlags())
17985 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17986 addDirectMem(MIB, X86::EAX);
17987 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17990 MI->eraseFromParent(); // The pseudo instruction is gone now.
17994 MachineBasicBlock *
17995 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17996 MachineBasicBlock *MBB) const {
17997 DebugLoc DL = MI->getDebugLoc();
17998 MachineFunction *MF = MBB->getParent();
17999 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18000 MachineRegisterInfo &MRI = MF->getRegInfo();
18002 const BasicBlock *BB = MBB->getBasicBlock();
18003 MachineFunction::iterator I = MBB;
18006 // Memory Reference
18007 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18008 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18011 unsigned MemOpndSlot = 0;
18013 unsigned CurOp = 0;
18015 DstReg = MI->getOperand(CurOp++).getReg();
18016 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18017 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18018 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18019 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18021 MemOpndSlot = CurOp;
18023 MVT PVT = getPointerTy();
18024 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18025 "Invalid Pointer Size!");
18027 // For v = setjmp(buf), we generate
18030 // buf[LabelOffset] = restoreMBB
18031 // SjLjSetup restoreMBB
18037 // v = phi(main, restore)
18042 MachineBasicBlock *thisMBB = MBB;
18043 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18044 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18045 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18046 MF->insert(I, mainMBB);
18047 MF->insert(I, sinkMBB);
18048 MF->push_back(restoreMBB);
18050 MachineInstrBuilder MIB;
18052 // Transfer the remainder of BB and its successor edges to sinkMBB.
18053 sinkMBB->splice(sinkMBB->begin(), MBB,
18054 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18055 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18058 unsigned PtrStoreOpc = 0;
18059 unsigned LabelReg = 0;
18060 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18061 Reloc::Model RM = MF->getTarget().getRelocationModel();
18062 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18063 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18065 // Prepare IP either in reg or imm.
18066 if (!UseImmLabel) {
18067 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18068 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18069 LabelReg = MRI.createVirtualRegister(PtrRC);
18070 if (Subtarget->is64Bit()) {
18071 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18075 .addMBB(restoreMBB)
18078 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18079 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18080 .addReg(XII->getGlobalBaseReg(MF))
18083 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18087 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18089 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18090 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18091 if (i == X86::AddrDisp)
18092 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18094 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18097 MIB.addReg(LabelReg);
18099 MIB.addMBB(restoreMBB);
18100 MIB.setMemRefs(MMOBegin, MMOEnd);
18102 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18103 .addMBB(restoreMBB);
18105 const X86RegisterInfo *RegInfo =
18106 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18107 MIB.addRegMask(RegInfo->getNoPreservedMask());
18108 thisMBB->addSuccessor(mainMBB);
18109 thisMBB->addSuccessor(restoreMBB);
18113 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18114 mainMBB->addSuccessor(sinkMBB);
18117 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18118 TII->get(X86::PHI), DstReg)
18119 .addReg(mainDstReg).addMBB(mainMBB)
18120 .addReg(restoreDstReg).addMBB(restoreMBB);
18123 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18124 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18125 restoreMBB->addSuccessor(sinkMBB);
18127 MI->eraseFromParent();
18131 MachineBasicBlock *
18132 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18133 MachineBasicBlock *MBB) const {
18134 DebugLoc DL = MI->getDebugLoc();
18135 MachineFunction *MF = MBB->getParent();
18136 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18137 MachineRegisterInfo &MRI = MF->getRegInfo();
18139 // Memory Reference
18140 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18141 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18143 MVT PVT = getPointerTy();
18144 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18145 "Invalid Pointer Size!");
18147 const TargetRegisterClass *RC =
18148 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18149 unsigned Tmp = MRI.createVirtualRegister(RC);
18150 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18151 const X86RegisterInfo *RegInfo =
18152 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18153 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18154 unsigned SP = RegInfo->getStackRegister();
18156 MachineInstrBuilder MIB;
18158 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18159 const int64_t SPOffset = 2 * PVT.getStoreSize();
18161 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18162 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18165 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18166 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18167 MIB.addOperand(MI->getOperand(i));
18168 MIB.setMemRefs(MMOBegin, MMOEnd);
18170 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18171 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18172 if (i == X86::AddrDisp)
18173 MIB.addDisp(MI->getOperand(i), LabelOffset);
18175 MIB.addOperand(MI->getOperand(i));
18177 MIB.setMemRefs(MMOBegin, MMOEnd);
18179 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18180 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18181 if (i == X86::AddrDisp)
18182 MIB.addDisp(MI->getOperand(i), SPOffset);
18184 MIB.addOperand(MI->getOperand(i));
18186 MIB.setMemRefs(MMOBegin, MMOEnd);
18188 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18190 MI->eraseFromParent();
18194 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18195 // accumulator loops. Writing back to the accumulator allows the coalescer
18196 // to remove extra copies in the loop.
18197 MachineBasicBlock *
18198 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18199 MachineBasicBlock *MBB) const {
18200 MachineOperand &AddendOp = MI->getOperand(3);
18202 // Bail out early if the addend isn't a register - we can't switch these.
18203 if (!AddendOp.isReg())
18206 MachineFunction &MF = *MBB->getParent();
18207 MachineRegisterInfo &MRI = MF.getRegInfo();
18209 // Check whether the addend is defined by a PHI:
18210 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18211 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18212 if (!AddendDef.isPHI())
18215 // Look for the following pattern:
18217 // %addend = phi [%entry, 0], [%loop, %result]
18219 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18223 // %addend = phi [%entry, 0], [%loop, %result]
18225 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18227 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18228 assert(AddendDef.getOperand(i).isReg());
18229 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18230 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18231 if (&PHISrcInst == MI) {
18232 // Found a matching instruction.
18233 unsigned NewFMAOpc = 0;
18234 switch (MI->getOpcode()) {
18235 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18236 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18237 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18238 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18239 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18240 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18241 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18242 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18243 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18244 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18245 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18246 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18247 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18248 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18249 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18250 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18251 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18252 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18253 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18254 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18255 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18256 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18257 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18258 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18259 default: llvm_unreachable("Unrecognized FMA variant.");
18262 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18263 MachineInstrBuilder MIB =
18264 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18265 .addOperand(MI->getOperand(0))
18266 .addOperand(MI->getOperand(3))
18267 .addOperand(MI->getOperand(2))
18268 .addOperand(MI->getOperand(1));
18269 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18270 MI->eraseFromParent();
18277 MachineBasicBlock *
18278 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18279 MachineBasicBlock *BB) const {
18280 switch (MI->getOpcode()) {
18281 default: llvm_unreachable("Unexpected instr type to insert");
18282 case X86::TAILJMPd64:
18283 case X86::TAILJMPr64:
18284 case X86::TAILJMPm64:
18285 llvm_unreachable("TAILJMP64 would not be touched here.");
18286 case X86::TCRETURNdi64:
18287 case X86::TCRETURNri64:
18288 case X86::TCRETURNmi64:
18290 case X86::WIN_ALLOCA:
18291 return EmitLoweredWinAlloca(MI, BB);
18292 case X86::SEG_ALLOCA_32:
18293 return EmitLoweredSegAlloca(MI, BB, false);
18294 case X86::SEG_ALLOCA_64:
18295 return EmitLoweredSegAlloca(MI, BB, true);
18296 case X86::TLSCall_32:
18297 case X86::TLSCall_64:
18298 return EmitLoweredTLSCall(MI, BB);
18299 case X86::CMOV_GR8:
18300 case X86::CMOV_FR32:
18301 case X86::CMOV_FR64:
18302 case X86::CMOV_V4F32:
18303 case X86::CMOV_V2F64:
18304 case X86::CMOV_V2I64:
18305 case X86::CMOV_V8F32:
18306 case X86::CMOV_V4F64:
18307 case X86::CMOV_V4I64:
18308 case X86::CMOV_V16F32:
18309 case X86::CMOV_V8F64:
18310 case X86::CMOV_V8I64:
18311 case X86::CMOV_GR16:
18312 case X86::CMOV_GR32:
18313 case X86::CMOV_RFP32:
18314 case X86::CMOV_RFP64:
18315 case X86::CMOV_RFP80:
18316 return EmitLoweredSelect(MI, BB);
18318 case X86::FP32_TO_INT16_IN_MEM:
18319 case X86::FP32_TO_INT32_IN_MEM:
18320 case X86::FP32_TO_INT64_IN_MEM:
18321 case X86::FP64_TO_INT16_IN_MEM:
18322 case X86::FP64_TO_INT32_IN_MEM:
18323 case X86::FP64_TO_INT64_IN_MEM:
18324 case X86::FP80_TO_INT16_IN_MEM:
18325 case X86::FP80_TO_INT32_IN_MEM:
18326 case X86::FP80_TO_INT64_IN_MEM: {
18327 MachineFunction *F = BB->getParent();
18328 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18329 DebugLoc DL = MI->getDebugLoc();
18331 // Change the floating point control register to use "round towards zero"
18332 // mode when truncating to an integer value.
18333 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18334 addFrameReference(BuildMI(*BB, MI, DL,
18335 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18337 // Load the old value of the high byte of the control word...
18339 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18340 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18343 // Set the high part to be round to zero...
18344 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18347 // Reload the modified control word now...
18348 addFrameReference(BuildMI(*BB, MI, DL,
18349 TII->get(X86::FLDCW16m)), CWFrameIdx);
18351 // Restore the memory image of control word to original value
18352 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18355 // Get the X86 opcode to use.
18357 switch (MI->getOpcode()) {
18358 default: llvm_unreachable("illegal opcode!");
18359 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18360 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18361 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18362 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18363 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18364 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18365 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18366 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18367 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18371 MachineOperand &Op = MI->getOperand(0);
18373 AM.BaseType = X86AddressMode::RegBase;
18374 AM.Base.Reg = Op.getReg();
18376 AM.BaseType = X86AddressMode::FrameIndexBase;
18377 AM.Base.FrameIndex = Op.getIndex();
18379 Op = MI->getOperand(1);
18381 AM.Scale = Op.getImm();
18382 Op = MI->getOperand(2);
18384 AM.IndexReg = Op.getImm();
18385 Op = MI->getOperand(3);
18386 if (Op.isGlobal()) {
18387 AM.GV = Op.getGlobal();
18389 AM.Disp = Op.getImm();
18391 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18392 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18394 // Reload the original control word now.
18395 addFrameReference(BuildMI(*BB, MI, DL,
18396 TII->get(X86::FLDCW16m)), CWFrameIdx);
18398 MI->eraseFromParent(); // The pseudo instruction is gone now.
18401 // String/text processing lowering.
18402 case X86::PCMPISTRM128REG:
18403 case X86::VPCMPISTRM128REG:
18404 case X86::PCMPISTRM128MEM:
18405 case X86::VPCMPISTRM128MEM:
18406 case X86::PCMPESTRM128REG:
18407 case X86::VPCMPESTRM128REG:
18408 case X86::PCMPESTRM128MEM:
18409 case X86::VPCMPESTRM128MEM:
18410 assert(Subtarget->hasSSE42() &&
18411 "Target must have SSE4.2 or AVX features enabled");
18412 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18414 // String/text processing lowering.
18415 case X86::PCMPISTRIREG:
18416 case X86::VPCMPISTRIREG:
18417 case X86::PCMPISTRIMEM:
18418 case X86::VPCMPISTRIMEM:
18419 case X86::PCMPESTRIREG:
18420 case X86::VPCMPESTRIREG:
18421 case X86::PCMPESTRIMEM:
18422 case X86::VPCMPESTRIMEM:
18423 assert(Subtarget->hasSSE42() &&
18424 "Target must have SSE4.2 or AVX features enabled");
18425 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18427 // Thread synchronization.
18429 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18433 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18435 case X86::VASTART_SAVE_XMM_REGS:
18436 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18438 case X86::VAARG_64:
18439 return EmitVAARG64WithCustomInserter(MI, BB);
18441 case X86::EH_SjLj_SetJmp32:
18442 case X86::EH_SjLj_SetJmp64:
18443 return emitEHSjLjSetJmp(MI, BB);
18445 case X86::EH_SjLj_LongJmp32:
18446 case X86::EH_SjLj_LongJmp64:
18447 return emitEHSjLjLongJmp(MI, BB);
18449 case TargetOpcode::STACKMAP:
18450 case TargetOpcode::PATCHPOINT:
18451 return emitPatchPoint(MI, BB);
18453 case X86::VFMADDPDr213r:
18454 case X86::VFMADDPSr213r:
18455 case X86::VFMADDSDr213r:
18456 case X86::VFMADDSSr213r:
18457 case X86::VFMSUBPDr213r:
18458 case X86::VFMSUBPSr213r:
18459 case X86::VFMSUBSDr213r:
18460 case X86::VFMSUBSSr213r:
18461 case X86::VFNMADDPDr213r:
18462 case X86::VFNMADDPSr213r:
18463 case X86::VFNMADDSDr213r:
18464 case X86::VFNMADDSSr213r:
18465 case X86::VFNMSUBPDr213r:
18466 case X86::VFNMSUBPSr213r:
18467 case X86::VFNMSUBSDr213r:
18468 case X86::VFNMSUBSSr213r:
18469 case X86::VFMADDPDr213rY:
18470 case X86::VFMADDPSr213rY:
18471 case X86::VFMSUBPDr213rY:
18472 case X86::VFMSUBPSr213rY:
18473 case X86::VFNMADDPDr213rY:
18474 case X86::VFNMADDPSr213rY:
18475 case X86::VFNMSUBPDr213rY:
18476 case X86::VFNMSUBPSr213rY:
18477 return emitFMA3Instr(MI, BB);
18481 //===----------------------------------------------------------------------===//
18482 // X86 Optimization Hooks
18483 //===----------------------------------------------------------------------===//
18485 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18488 const SelectionDAG &DAG,
18489 unsigned Depth) const {
18490 unsigned BitWidth = KnownZero.getBitWidth();
18491 unsigned Opc = Op.getOpcode();
18492 assert((Opc >= ISD::BUILTIN_OP_END ||
18493 Opc == ISD::INTRINSIC_WO_CHAIN ||
18494 Opc == ISD::INTRINSIC_W_CHAIN ||
18495 Opc == ISD::INTRINSIC_VOID) &&
18496 "Should use MaskedValueIsZero if you don't know whether Op"
18497 " is a target node!");
18499 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18513 // These nodes' second result is a boolean.
18514 if (Op.getResNo() == 0)
18517 case X86ISD::SETCC:
18518 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18520 case ISD::INTRINSIC_WO_CHAIN: {
18521 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18522 unsigned NumLoBits = 0;
18525 case Intrinsic::x86_sse_movmsk_ps:
18526 case Intrinsic::x86_avx_movmsk_ps_256:
18527 case Intrinsic::x86_sse2_movmsk_pd:
18528 case Intrinsic::x86_avx_movmsk_pd_256:
18529 case Intrinsic::x86_mmx_pmovmskb:
18530 case Intrinsic::x86_sse2_pmovmskb_128:
18531 case Intrinsic::x86_avx2_pmovmskb: {
18532 // High bits of movmskp{s|d}, pmovmskb are known zero.
18534 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18535 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18536 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18537 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18538 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18539 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18540 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18541 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18543 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18552 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18554 const SelectionDAG &,
18555 unsigned Depth) const {
18556 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18557 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18558 return Op.getValueType().getScalarType().getSizeInBits();
18564 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18565 /// node is a GlobalAddress + offset.
18566 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18567 const GlobalValue* &GA,
18568 int64_t &Offset) const {
18569 if (N->getOpcode() == X86ISD::Wrapper) {
18570 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18571 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18572 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18576 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18579 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18580 /// same as extracting the high 128-bit part of 256-bit vector and then
18581 /// inserting the result into the low part of a new 256-bit vector
18582 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18583 EVT VT = SVOp->getValueType(0);
18584 unsigned NumElems = VT.getVectorNumElements();
18586 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18587 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18588 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18589 SVOp->getMaskElt(j) >= 0)
18595 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18596 /// same as extracting the low 128-bit part of 256-bit vector and then
18597 /// inserting the result into the high part of a new 256-bit vector
18598 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18599 EVT VT = SVOp->getValueType(0);
18600 unsigned NumElems = VT.getVectorNumElements();
18602 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18603 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18604 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18605 SVOp->getMaskElt(j) >= 0)
18611 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18612 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18613 TargetLowering::DAGCombinerInfo &DCI,
18614 const X86Subtarget* Subtarget) {
18616 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18617 SDValue V1 = SVOp->getOperand(0);
18618 SDValue V2 = SVOp->getOperand(1);
18619 EVT VT = SVOp->getValueType(0);
18620 unsigned NumElems = VT.getVectorNumElements();
18622 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18623 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18627 // V UNDEF BUILD_VECTOR UNDEF
18629 // CONCAT_VECTOR CONCAT_VECTOR
18632 // RESULT: V + zero extended
18634 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18635 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18636 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18639 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18642 // To match the shuffle mask, the first half of the mask should
18643 // be exactly the first vector, and all the rest a splat with the
18644 // first element of the second one.
18645 for (unsigned i = 0; i != NumElems/2; ++i)
18646 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18647 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18650 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18651 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18652 if (Ld->hasNUsesOfValue(1, 0)) {
18653 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18654 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18656 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18658 Ld->getPointerInfo(),
18659 Ld->getAlignment(),
18660 false/*isVolatile*/, true/*ReadMem*/,
18661 false/*WriteMem*/);
18663 // Make sure the newly-created LOAD is in the same position as Ld in
18664 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18665 // and update uses of Ld's output chain to use the TokenFactor.
18666 if (Ld->hasAnyUseOfValue(1)) {
18667 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18668 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18669 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18670 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18671 SDValue(ResNode.getNode(), 1));
18674 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18678 // Emit a zeroed vector and insert the desired subvector on its
18680 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18681 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18682 return DCI.CombineTo(N, InsV);
18685 //===--------------------------------------------------------------------===//
18686 // Combine some shuffles into subvector extracts and inserts:
18689 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18690 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18691 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18692 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18693 return DCI.CombineTo(N, InsV);
18696 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18697 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18698 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18699 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18700 return DCI.CombineTo(N, InsV);
18706 /// \brief Get the PSHUF-style mask from PSHUF node.
18708 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18709 /// PSHUF-style masks that can be reused with such instructions.
18710 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18711 SmallVector<int, 4> Mask;
18713 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18717 switch (N.getOpcode()) {
18718 case X86ISD::PSHUFD:
18720 case X86ISD::PSHUFLW:
18723 case X86ISD::PSHUFHW:
18724 Mask.erase(Mask.begin(), Mask.begin() + 4);
18725 for (int &M : Mask)
18729 llvm_unreachable("No valid shuffle instruction found!");
18733 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18735 /// We walk up the chain and look for a combinable shuffle, skipping over
18736 /// shuffles that we could hoist this shuffle's transformation past without
18737 /// altering anything.
18738 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18740 TargetLowering::DAGCombinerInfo &DCI) {
18741 assert(N.getOpcode() == X86ISD::PSHUFD &&
18742 "Called with something other than an x86 128-bit half shuffle!");
18745 // Walk up a single-use chain looking for a combinable shuffle.
18746 SDValue V = N.getOperand(0);
18747 for (; V.hasOneUse(); V = V.getOperand(0)) {
18748 switch (V.getOpcode()) {
18750 return false; // Nothing combined!
18753 // Skip bitcasts as we always know the type for the target specific
18757 case X86ISD::PSHUFD:
18758 // Found another dword shuffle.
18761 case X86ISD::PSHUFLW:
18762 // Check that the low words (being shuffled) are the identity in the
18763 // dword shuffle, and the high words are self-contained.
18764 if (Mask[0] != 0 || Mask[1] != 1 ||
18765 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18770 case X86ISD::PSHUFHW:
18771 // Check that the high words (being shuffled) are the identity in the
18772 // dword shuffle, and the low words are self-contained.
18773 if (Mask[2] != 2 || Mask[3] != 3 ||
18774 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18779 case X86ISD::UNPCKL:
18780 case X86ISD::UNPCKH:
18781 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18782 // shuffle into a preceding word shuffle.
18783 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18786 // Search for a half-shuffle which we can combine with.
18787 unsigned CombineOp =
18788 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18789 if (V.getOperand(0) != V.getOperand(1) ||
18790 !V->isOnlyUserOf(V.getOperand(0).getNode()))
18792 V = V.getOperand(0);
18794 switch (V.getOpcode()) {
18796 return false; // Nothing to combine.
18798 case X86ISD::PSHUFLW:
18799 case X86ISD::PSHUFHW:
18800 if (V.getOpcode() == CombineOp)
18805 V = V.getOperand(0);
18809 } while (V.hasOneUse());
18812 // Break out of the loop if we break out of the switch.
18816 if (!V.hasOneUse())
18817 // We fell out of the loop without finding a viable combining instruction.
18820 // Record the old value to use in RAUW-ing.
18823 // Merge this node's mask and our incoming mask.
18824 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18825 for (int &M : Mask)
18827 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18828 getV4X86ShuffleImm8ForMask(Mask, DAG));
18830 // It is possible that one of the combinable shuffles was completely absorbed
18831 // by the other, just replace it and revisit all users in that case.
18832 if (Old.getNode() == V.getNode()) {
18833 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18837 // Replace N with its operand as we're going to combine that shuffle away.
18838 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18840 // Replace the combinable shuffle with the combined one, updating all users
18841 // so that we re-evaluate the chain here.
18842 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18846 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18848 /// We walk up the chain, skipping shuffles of the other half and looking
18849 /// through shuffles which switch halves trying to find a shuffle of the same
18850 /// pair of dwords.
18851 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18853 TargetLowering::DAGCombinerInfo &DCI) {
18855 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18856 "Called with something other than an x86 128-bit half shuffle!");
18858 unsigned CombineOpcode = N.getOpcode();
18860 // Walk up a single-use chain looking for a combinable shuffle.
18861 SDValue V = N.getOperand(0);
18862 for (; V.hasOneUse(); V = V.getOperand(0)) {
18863 switch (V.getOpcode()) {
18865 return false; // Nothing combined!
18868 // Skip bitcasts as we always know the type for the target specific
18872 case X86ISD::PSHUFLW:
18873 case X86ISD::PSHUFHW:
18874 if (V.getOpcode() == CombineOpcode)
18877 // Other-half shuffles are no-ops.
18880 case X86ISD::PSHUFD: {
18881 // We can only handle pshufd if the half we are combining either stays in
18882 // its half, or switches to the other half. Bail if one of these isn't
18884 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18885 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18886 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18887 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18890 // Map the mask through the pshufd and keep walking up the chain.
18891 for (int i = 0; i < 4; ++i)
18892 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18894 // Switch halves if the pshufd does.
18896 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18900 // Break out of the loop if we break out of the switch.
18904 if (!V.hasOneUse())
18905 // We fell out of the loop without finding a viable combining instruction.
18908 // Record the old value to use in RAUW-ing.
18911 // Merge this node's mask and our incoming mask (adjusted to account for all
18912 // the pshufd instructions encountered).
18913 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18914 for (int &M : Mask)
18916 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18917 getV4X86ShuffleImm8ForMask(Mask, DAG));
18919 // Replace N with its operand as we're going to combine that shuffle away.
18920 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18922 // Replace the combinable shuffle with the combined one, updating all users
18923 // so that we re-evaluate the chain here.
18924 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18928 /// \brief Try to combine x86 target specific shuffles.
18929 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18930 TargetLowering::DAGCombinerInfo &DCI,
18931 const X86Subtarget *Subtarget) {
18933 MVT VT = N.getSimpleValueType();
18934 SmallVector<int, 4> Mask;
18936 switch (N.getOpcode()) {
18937 case X86ISD::PSHUFD:
18938 case X86ISD::PSHUFLW:
18939 case X86ISD::PSHUFHW:
18940 Mask = getPSHUFShuffleMask(N);
18941 assert(Mask.size() == 4);
18947 // Nuke no-op shuffles that show up after combining.
18948 if (isNoopShuffleMask(Mask))
18949 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18951 // Look for simplifications involving one or two shuffle instructions.
18952 SDValue V = N.getOperand(0);
18953 switch (N.getOpcode()) {
18956 case X86ISD::PSHUFLW:
18957 case X86ISD::PSHUFHW:
18958 assert(VT == MVT::v8i16);
18961 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18962 return SDValue(); // We combined away this shuffle, so we're done.
18964 // See if this reduces to a PSHUFD which is no more expensive and can
18965 // combine with more operations.
18966 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18967 areAdjacentMasksSequential(Mask)) {
18968 int DMask[] = {-1, -1, -1, -1};
18969 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18970 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18971 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18972 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18973 DCI.AddToWorklist(V.getNode());
18974 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18975 getV4X86ShuffleImm8ForMask(DMask, DAG));
18976 DCI.AddToWorklist(V.getNode());
18977 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18980 // Look for shuffle patterns which can be implemented as a single unpack.
18981 // FIXME: This doesn't handle the location of the PSHUFD generically, and
18982 // only works when we have a PSHUFD followed by two half-shuffles.
18983 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18984 (V.getOpcode() == X86ISD::PSHUFLW ||
18985 V.getOpcode() == X86ISD::PSHUFHW) &&
18986 V.getOpcode() != N.getOpcode() &&
18988 SDValue D = V.getOperand(0);
18989 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18990 D = D.getOperand(0);
18991 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
18992 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18993 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
18994 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18995 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18997 for (int i = 0; i < 4; ++i) {
18998 WordMask[i + NOffset] = Mask[i] + NOffset;
18999 WordMask[i + VOffset] = VMask[i] + VOffset;
19001 // Map the word mask through the DWord mask.
19003 for (int i = 0; i < 8; ++i)
19004 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19005 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19006 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19007 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19008 std::begin(UnpackLoMask)) ||
19009 std::equal(std::begin(MappedMask), std::end(MappedMask),
19010 std::begin(UnpackHiMask))) {
19011 // We can replace all three shuffles with an unpack.
19012 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19013 DCI.AddToWorklist(V.getNode());
19014 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19016 DL, MVT::v8i16, V, V);
19023 case X86ISD::PSHUFD:
19024 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19025 return SDValue(); // We combined away this shuffle.
19033 /// PerformShuffleCombine - Performs several different shuffle combines.
19034 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19035 TargetLowering::DAGCombinerInfo &DCI,
19036 const X86Subtarget *Subtarget) {
19038 SDValue N0 = N->getOperand(0);
19039 SDValue N1 = N->getOperand(1);
19040 EVT VT = N->getValueType(0);
19042 // Don't create instructions with illegal types after legalize types has run.
19043 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19044 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19047 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19048 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19049 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19050 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19052 // During Type Legalization, when promoting illegal vector types,
19053 // the backend might introduce new shuffle dag nodes and bitcasts.
19055 // This code performs the following transformation:
19056 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19057 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19059 // We do this only if both the bitcast and the BINOP dag nodes have
19060 // one use. Also, perform this transformation only if the new binary
19061 // operation is legal. This is to avoid introducing dag nodes that
19062 // potentially need to be further expanded (or custom lowered) into a
19063 // less optimal sequence of dag nodes.
19064 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19065 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19066 N0.getOpcode() == ISD::BITCAST) {
19067 SDValue BC0 = N0.getOperand(0);
19068 EVT SVT = BC0.getValueType();
19069 unsigned Opcode = BC0.getOpcode();
19070 unsigned NumElts = VT.getVectorNumElements();
19072 if (BC0.hasOneUse() && SVT.isVector() &&
19073 SVT.getVectorNumElements() * 2 == NumElts &&
19074 TLI.isOperationLegal(Opcode, VT)) {
19075 bool CanFold = false;
19087 unsigned SVTNumElts = SVT.getVectorNumElements();
19088 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19089 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19090 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19091 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19092 CanFold = SVOp->getMaskElt(i) < 0;
19095 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19096 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19097 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19098 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19103 // Only handle 128 wide vector from here on.
19104 if (!VT.is128BitVector())
19107 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19108 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19109 // consecutive, non-overlapping, and in the right order.
19110 SmallVector<SDValue, 16> Elts;
19111 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19112 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19114 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19118 if (isTargetShuffle(N->getOpcode())) {
19120 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19121 if (Shuffle.getNode())
19128 /// PerformTruncateCombine - Converts truncate operation to
19129 /// a sequence of vector shuffle operations.
19130 /// It is possible when we truncate 256-bit vector to 128-bit vector
19131 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19132 TargetLowering::DAGCombinerInfo &DCI,
19133 const X86Subtarget *Subtarget) {
19137 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19138 /// specific shuffle of a load can be folded into a single element load.
19139 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19140 /// shuffles have been customed lowered so we need to handle those here.
19141 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19142 TargetLowering::DAGCombinerInfo &DCI) {
19143 if (DCI.isBeforeLegalizeOps())
19146 SDValue InVec = N->getOperand(0);
19147 SDValue EltNo = N->getOperand(1);
19149 if (!isa<ConstantSDNode>(EltNo))
19152 EVT VT = InVec.getValueType();
19154 bool HasShuffleIntoBitcast = false;
19155 if (InVec.getOpcode() == ISD::BITCAST) {
19156 // Don't duplicate a load with other uses.
19157 if (!InVec.hasOneUse())
19159 EVT BCVT = InVec.getOperand(0).getValueType();
19160 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19162 InVec = InVec.getOperand(0);
19163 HasShuffleIntoBitcast = true;
19166 if (!isTargetShuffle(InVec.getOpcode()))
19169 // Don't duplicate a load with other uses.
19170 if (!InVec.hasOneUse())
19173 SmallVector<int, 16> ShuffleMask;
19175 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19179 // Select the input vector, guarding against out of range extract vector.
19180 unsigned NumElems = VT.getVectorNumElements();
19181 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19182 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19183 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19184 : InVec.getOperand(1);
19186 // If inputs to shuffle are the same for both ops, then allow 2 uses
19187 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19189 if (LdNode.getOpcode() == ISD::BITCAST) {
19190 // Don't duplicate a load with other uses.
19191 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19194 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19195 LdNode = LdNode.getOperand(0);
19198 if (!ISD::isNormalLoad(LdNode.getNode()))
19201 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19203 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19206 if (HasShuffleIntoBitcast) {
19207 // If there's a bitcast before the shuffle, check if the load type and
19208 // alignment is valid.
19209 unsigned Align = LN0->getAlignment();
19210 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19211 unsigned NewAlign = TLI.getDataLayout()->
19212 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19214 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19218 // All checks match so transform back to vector_shuffle so that DAG combiner
19219 // can finish the job
19222 // Create shuffle node taking into account the case that its a unary shuffle
19223 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19224 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19225 InVec.getOperand(0), Shuffle,
19227 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19228 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19232 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19233 /// generation and convert it from being a bunch of shuffles and extracts
19234 /// to a simple store and scalar loads to extract the elements.
19235 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19236 TargetLowering::DAGCombinerInfo &DCI) {
19237 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19238 if (NewOp.getNode())
19241 SDValue InputVector = N->getOperand(0);
19243 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19244 // from mmx to v2i32 has a single usage.
19245 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19246 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19247 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19248 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19249 N->getValueType(0),
19250 InputVector.getNode()->getOperand(0));
19252 // Only operate on vectors of 4 elements, where the alternative shuffling
19253 // gets to be more expensive.
19254 if (InputVector.getValueType() != MVT::v4i32)
19257 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19258 // single use which is a sign-extend or zero-extend, and all elements are
19260 SmallVector<SDNode *, 4> Uses;
19261 unsigned ExtractedElements = 0;
19262 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19263 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19264 if (UI.getUse().getResNo() != InputVector.getResNo())
19267 SDNode *Extract = *UI;
19268 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19271 if (Extract->getValueType(0) != MVT::i32)
19273 if (!Extract->hasOneUse())
19275 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19276 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19278 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19281 // Record which element was extracted.
19282 ExtractedElements |=
19283 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19285 Uses.push_back(Extract);
19288 // If not all the elements were used, this may not be worthwhile.
19289 if (ExtractedElements != 15)
19292 // Ok, we've now decided to do the transformation.
19293 SDLoc dl(InputVector);
19295 // Store the value to a temporary stack slot.
19296 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19297 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19298 MachinePointerInfo(), false, false, 0);
19300 // Replace each use (extract) with a load of the appropriate element.
19301 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19302 UE = Uses.end(); UI != UE; ++UI) {
19303 SDNode *Extract = *UI;
19305 // cOMpute the element's address.
19306 SDValue Idx = Extract->getOperand(1);
19308 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19309 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19310 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19311 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19313 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19314 StackPtr, OffsetVal);
19316 // Load the scalar.
19317 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19318 ScalarAddr, MachinePointerInfo(),
19319 false, false, false, 0);
19321 // Replace the exact with the load.
19322 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19325 // The replacement was made in place; don't return anything.
19329 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19330 static std::pair<unsigned, bool>
19331 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19332 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19333 if (!VT.isVector())
19334 return std::make_pair(0, false);
19336 bool NeedSplit = false;
19337 switch (VT.getSimpleVT().SimpleTy) {
19338 default: return std::make_pair(0, false);
19342 if (!Subtarget->hasAVX2())
19344 if (!Subtarget->hasAVX())
19345 return std::make_pair(0, false);
19350 if (!Subtarget->hasSSE2())
19351 return std::make_pair(0, false);
19354 // SSE2 has only a small subset of the operations.
19355 bool hasUnsigned = Subtarget->hasSSE41() ||
19356 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19357 bool hasSigned = Subtarget->hasSSE41() ||
19358 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19360 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19363 // Check for x CC y ? x : y.
19364 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19365 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19370 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19373 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19376 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19379 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19381 // Check for x CC y ? y : x -- a min/max with reversed arms.
19382 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19383 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19388 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19391 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19394 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19397 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19401 return std::make_pair(Opc, NeedSplit);
19405 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19406 const X86Subtarget *Subtarget) {
19408 SDValue Cond = N->getOperand(0);
19409 SDValue LHS = N->getOperand(1);
19410 SDValue RHS = N->getOperand(2);
19412 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19413 SDValue CondSrc = Cond->getOperand(0);
19414 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19415 Cond = CondSrc->getOperand(0);
19418 MVT VT = N->getSimpleValueType(0);
19419 MVT EltVT = VT.getVectorElementType();
19420 unsigned NumElems = VT.getVectorNumElements();
19421 // There is no blend with immediate in AVX-512.
19422 if (VT.is512BitVector())
19425 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19427 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19430 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19433 unsigned MaskValue = 0;
19434 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19437 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19438 for (unsigned i = 0; i < NumElems; ++i) {
19439 // Be sure we emit undef where we can.
19440 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19441 ShuffleMask[i] = -1;
19443 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19446 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19449 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19451 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19452 TargetLowering::DAGCombinerInfo &DCI,
19453 const X86Subtarget *Subtarget) {
19455 SDValue Cond = N->getOperand(0);
19456 // Get the LHS/RHS of the select.
19457 SDValue LHS = N->getOperand(1);
19458 SDValue RHS = N->getOperand(2);
19459 EVT VT = LHS.getValueType();
19460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19462 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19463 // instructions match the semantics of the common C idiom x<y?x:y but not
19464 // x<=y?x:y, because of how they handle negative zero (which can be
19465 // ignored in unsafe-math mode).
19466 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19467 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19468 (Subtarget->hasSSE2() ||
19469 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19470 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19472 unsigned Opcode = 0;
19473 // Check for x CC y ? x : y.
19474 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19475 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19479 // Converting this to a min would handle NaNs incorrectly, and swapping
19480 // the operands would cause it to handle comparisons between positive
19481 // and negative zero incorrectly.
19482 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19483 if (!DAG.getTarget().Options.UnsafeFPMath &&
19484 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19486 std::swap(LHS, RHS);
19488 Opcode = X86ISD::FMIN;
19491 // Converting this to a min would handle comparisons between positive
19492 // and negative zero incorrectly.
19493 if (!DAG.getTarget().Options.UnsafeFPMath &&
19494 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19496 Opcode = X86ISD::FMIN;
19499 // Converting this to a min would handle both negative zeros and NaNs
19500 // incorrectly, but we can swap the operands to fix both.
19501 std::swap(LHS, RHS);
19505 Opcode = X86ISD::FMIN;
19509 // Converting this to a max would handle comparisons between positive
19510 // and negative zero incorrectly.
19511 if (!DAG.getTarget().Options.UnsafeFPMath &&
19512 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19514 Opcode = X86ISD::FMAX;
19517 // Converting this to a max would handle NaNs incorrectly, and swapping
19518 // the operands would cause it to handle comparisons between positive
19519 // and negative zero incorrectly.
19520 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19521 if (!DAG.getTarget().Options.UnsafeFPMath &&
19522 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19524 std::swap(LHS, RHS);
19526 Opcode = X86ISD::FMAX;
19529 // Converting this to a max would handle both negative zeros and NaNs
19530 // incorrectly, but we can swap the operands to fix both.
19531 std::swap(LHS, RHS);
19535 Opcode = X86ISD::FMAX;
19538 // Check for x CC y ? y : x -- a min/max with reversed arms.
19539 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19540 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19544 // Converting this to a min would handle comparisons between positive
19545 // and negative zero incorrectly, and swapping the operands would
19546 // cause it to handle NaNs incorrectly.
19547 if (!DAG.getTarget().Options.UnsafeFPMath &&
19548 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19549 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19551 std::swap(LHS, RHS);
19553 Opcode = X86ISD::FMIN;
19556 // Converting this to a min would handle NaNs incorrectly.
19557 if (!DAG.getTarget().Options.UnsafeFPMath &&
19558 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19560 Opcode = X86ISD::FMIN;
19563 // Converting this to a min would handle both negative zeros and NaNs
19564 // incorrectly, but we can swap the operands to fix both.
19565 std::swap(LHS, RHS);
19569 Opcode = X86ISD::FMIN;
19573 // Converting this to a max would handle NaNs incorrectly.
19574 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19576 Opcode = X86ISD::FMAX;
19579 // Converting this to a max would handle comparisons between positive
19580 // and negative zero incorrectly, and swapping the operands would
19581 // cause it to handle NaNs incorrectly.
19582 if (!DAG.getTarget().Options.UnsafeFPMath &&
19583 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19584 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19586 std::swap(LHS, RHS);
19588 Opcode = X86ISD::FMAX;
19591 // Converting this to a max would handle both negative zeros and NaNs
19592 // incorrectly, but we can swap the operands to fix both.
19593 std::swap(LHS, RHS);
19597 Opcode = X86ISD::FMAX;
19603 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19606 EVT CondVT = Cond.getValueType();
19607 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19608 CondVT.getVectorElementType() == MVT::i1) {
19609 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19610 // lowering on AVX-512. In this case we convert it to
19611 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19612 // The same situation for all 128 and 256-bit vectors of i8 and i16
19613 EVT OpVT = LHS.getValueType();
19614 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19615 (OpVT.getVectorElementType() == MVT::i8 ||
19616 OpVT.getVectorElementType() == MVT::i16)) {
19617 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19618 DCI.AddToWorklist(Cond.getNode());
19619 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19622 // If this is a select between two integer constants, try to do some
19624 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19625 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19626 // Don't do this for crazy integer types.
19627 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19628 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19629 // so that TrueC (the true value) is larger than FalseC.
19630 bool NeedsCondInvert = false;
19632 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19633 // Efficiently invertible.
19634 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19635 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19636 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19637 NeedsCondInvert = true;
19638 std::swap(TrueC, FalseC);
19641 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19642 if (FalseC->getAPIntValue() == 0 &&
19643 TrueC->getAPIntValue().isPowerOf2()) {
19644 if (NeedsCondInvert) // Invert the condition if needed.
19645 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19646 DAG.getConstant(1, Cond.getValueType()));
19648 // Zero extend the condition if needed.
19649 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19651 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19652 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19653 DAG.getConstant(ShAmt, MVT::i8));
19656 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19657 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19658 if (NeedsCondInvert) // Invert the condition if needed.
19659 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19660 DAG.getConstant(1, Cond.getValueType()));
19662 // Zero extend the condition if needed.
19663 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19664 FalseC->getValueType(0), Cond);
19665 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19666 SDValue(FalseC, 0));
19669 // Optimize cases that will turn into an LEA instruction. This requires
19670 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19671 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19672 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19673 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19675 bool isFastMultiplier = false;
19677 switch ((unsigned char)Diff) {
19679 case 1: // result = add base, cond
19680 case 2: // result = lea base( , cond*2)
19681 case 3: // result = lea base(cond, cond*2)
19682 case 4: // result = lea base( , cond*4)
19683 case 5: // result = lea base(cond, cond*4)
19684 case 8: // result = lea base( , cond*8)
19685 case 9: // result = lea base(cond, cond*8)
19686 isFastMultiplier = true;
19691 if (isFastMultiplier) {
19692 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19693 if (NeedsCondInvert) // Invert the condition if needed.
19694 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19695 DAG.getConstant(1, Cond.getValueType()));
19697 // Zero extend the condition if needed.
19698 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19700 // Scale the condition by the difference.
19702 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19703 DAG.getConstant(Diff, Cond.getValueType()));
19705 // Add the base if non-zero.
19706 if (FalseC->getAPIntValue() != 0)
19707 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19708 SDValue(FalseC, 0));
19715 // Canonicalize max and min:
19716 // (x > y) ? x : y -> (x >= y) ? x : y
19717 // (x < y) ? x : y -> (x <= y) ? x : y
19718 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19719 // the need for an extra compare
19720 // against zero. e.g.
19721 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19723 // testl %edi, %edi
19725 // cmovgl %edi, %eax
19729 // cmovsl %eax, %edi
19730 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19731 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19732 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19733 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19738 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19739 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19740 Cond.getOperand(0), Cond.getOperand(1), NewCC);
19741 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19746 // Early exit check
19747 if (!TLI.isTypeLegal(VT))
19750 // Match VSELECTs into subs with unsigned saturation.
19751 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19752 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19753 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19754 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19755 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19757 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19758 // left side invert the predicate to simplify logic below.
19760 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19762 CC = ISD::getSetCCInverse(CC, true);
19763 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19767 if (Other.getNode() && Other->getNumOperands() == 2 &&
19768 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19769 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19770 SDValue CondRHS = Cond->getOperand(1);
19772 // Look for a general sub with unsigned saturation first.
19773 // x >= y ? x-y : 0 --> subus x, y
19774 // x > y ? x-y : 0 --> subus x, y
19775 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19776 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19777 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19779 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19780 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19781 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19782 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19783 // If the RHS is a constant we have to reverse the const
19784 // canonicalization.
19785 // x > C-1 ? x+-C : 0 --> subus x, C
19786 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19787 CondRHSConst->getAPIntValue() ==
19788 (-OpRHSConst->getAPIntValue() - 1))
19789 return DAG.getNode(
19790 X86ISD::SUBUS, DL, VT, OpLHS,
19791 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19793 // Another special case: If C was a sign bit, the sub has been
19794 // canonicalized into a xor.
19795 // FIXME: Would it be better to use computeKnownBits to determine
19796 // whether it's safe to decanonicalize the xor?
19797 // x s< 0 ? x^C : 0 --> subus x, C
19798 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19799 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19800 OpRHSConst->getAPIntValue().isSignBit())
19801 // Note that we have to rebuild the RHS constant here to ensure we
19802 // don't rely on particular values of undef lanes.
19803 return DAG.getNode(
19804 X86ISD::SUBUS, DL, VT, OpLHS,
19805 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19810 // Try to match a min/max vector operation.
19811 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19812 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19813 unsigned Opc = ret.first;
19814 bool NeedSplit = ret.second;
19816 if (Opc && NeedSplit) {
19817 unsigned NumElems = VT.getVectorNumElements();
19818 // Extract the LHS vectors
19819 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19820 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19822 // Extract the RHS vectors
19823 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19824 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19826 // Create min/max for each subvector
19827 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19828 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19830 // Merge the result
19831 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19833 return DAG.getNode(Opc, DL, VT, LHS, RHS);
19836 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19837 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19838 // Check if SETCC has already been promoted
19839 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19840 // Check that condition value type matches vselect operand type
19843 assert(Cond.getValueType().isVector() &&
19844 "vector select expects a vector selector!");
19846 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19847 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19849 if (!TValIsAllOnes && !FValIsAllZeros) {
19850 // Try invert the condition if true value is not all 1s and false value
19852 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19853 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19855 if (TValIsAllZeros || FValIsAllOnes) {
19856 SDValue CC = Cond.getOperand(2);
19857 ISD::CondCode NewCC =
19858 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19859 Cond.getOperand(0).getValueType().isInteger());
19860 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19861 std::swap(LHS, RHS);
19862 TValIsAllOnes = FValIsAllOnes;
19863 FValIsAllZeros = TValIsAllZeros;
19867 if (TValIsAllOnes || FValIsAllZeros) {
19870 if (TValIsAllOnes && FValIsAllZeros)
19872 else if (TValIsAllOnes)
19873 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19874 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19875 else if (FValIsAllZeros)
19876 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19877 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19879 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19883 // Try to fold this VSELECT into a MOVSS/MOVSD
19884 if (N->getOpcode() == ISD::VSELECT &&
19885 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19886 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19887 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19888 bool CanFold = false;
19889 unsigned NumElems = Cond.getNumOperands();
19893 if (isZero(Cond.getOperand(0))) {
19896 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19897 // fold (vselect <0,-1> -> (movsd A, B)
19898 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19899 CanFold = isAllOnes(Cond.getOperand(i));
19900 } else if (isAllOnes(Cond.getOperand(0))) {
19904 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19905 // fold (vselect <-1,0> -> (movsd B, A)
19906 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19907 CanFold = isZero(Cond.getOperand(i));
19911 if (VT == MVT::v4i32 || VT == MVT::v4f32)
19912 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19913 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19916 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19917 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19918 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19919 // (v2i64 (bitcast B)))))
19921 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19922 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19923 // (v2f64 (bitcast B)))))
19925 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19926 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19927 // (v2i64 (bitcast A)))))
19929 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19930 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19931 // (v2f64 (bitcast A)))))
19933 CanFold = (isZero(Cond.getOperand(0)) &&
19934 isZero(Cond.getOperand(1)) &&
19935 isAllOnes(Cond.getOperand(2)) &&
19936 isAllOnes(Cond.getOperand(3)));
19938 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19939 isAllOnes(Cond.getOperand(1)) &&
19940 isZero(Cond.getOperand(2)) &&
19941 isZero(Cond.getOperand(3))) {
19943 std::swap(LHS, RHS);
19947 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19948 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19949 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19950 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19952 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19958 // If we know that this node is legal then we know that it is going to be
19959 // matched by one of the SSE/AVX BLEND instructions. These instructions only
19960 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19961 // to simplify previous instructions.
19962 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19963 !DCI.isBeforeLegalize() &&
19964 // We explicitly check against v8i16 and v16i16 because, although
19965 // they're marked as Custom, they might only be legal when Cond is a
19966 // build_vector of constants. This will be taken care in a later
19968 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19969 VT != MVT::v8i16)) {
19970 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19972 // Don't optimize vector selects that map to mask-registers.
19976 // Check all uses of that condition operand to check whether it will be
19977 // consumed by non-BLEND instructions, which may depend on all bits are set
19979 for (SDNode::use_iterator I = Cond->use_begin(),
19980 E = Cond->use_end(); I != E; ++I)
19981 if (I->getOpcode() != ISD::VSELECT)
19982 // TODO: Add other opcodes eventually lowered into BLEND.
19985 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19986 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19988 APInt KnownZero, KnownOne;
19989 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19990 DCI.isBeforeLegalizeOps());
19991 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19992 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19993 DCI.CommitTargetLoweringOpt(TLO);
19996 // We should generate an X86ISD::BLENDI from a vselect if its argument
19997 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19998 // constants. This specific pattern gets generated when we split a
19999 // selector for a 512 bit vector in a machine without AVX512 (but with
20000 // 256-bit vectors), during legalization:
20002 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20004 // Iff we find this pattern and the build_vectors are built from
20005 // constants, we translate the vselect into a shuffle_vector that we
20006 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20007 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20008 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20009 if (Shuffle.getNode())
20016 // Check whether a boolean test is testing a boolean value generated by
20017 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20020 // Simplify the following patterns:
20021 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20022 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20023 // to (Op EFLAGS Cond)
20025 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20026 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20027 // to (Op EFLAGS !Cond)
20029 // where Op could be BRCOND or CMOV.
20031 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20032 // Quit if not CMP and SUB with its value result used.
20033 if (Cmp.getOpcode() != X86ISD::CMP &&
20034 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20037 // Quit if not used as a boolean value.
20038 if (CC != X86::COND_E && CC != X86::COND_NE)
20041 // Check CMP operands. One of them should be 0 or 1 and the other should be
20042 // an SetCC or extended from it.
20043 SDValue Op1 = Cmp.getOperand(0);
20044 SDValue Op2 = Cmp.getOperand(1);
20047 const ConstantSDNode* C = nullptr;
20048 bool needOppositeCond = (CC == X86::COND_E);
20049 bool checkAgainstTrue = false; // Is it a comparison against 1?
20051 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20053 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20055 else // Quit if all operands are not constants.
20058 if (C->getZExtValue() == 1) {
20059 needOppositeCond = !needOppositeCond;
20060 checkAgainstTrue = true;
20061 } else if (C->getZExtValue() != 0)
20062 // Quit if the constant is neither 0 or 1.
20065 bool truncatedToBoolWithAnd = false;
20066 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20067 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20068 SetCC.getOpcode() == ISD::TRUNCATE ||
20069 SetCC.getOpcode() == ISD::AND) {
20070 if (SetCC.getOpcode() == ISD::AND) {
20072 ConstantSDNode *CS;
20073 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20074 CS->getZExtValue() == 1)
20076 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20077 CS->getZExtValue() == 1)
20081 SetCC = SetCC.getOperand(OpIdx);
20082 truncatedToBoolWithAnd = true;
20084 SetCC = SetCC.getOperand(0);
20087 switch (SetCC.getOpcode()) {
20088 case X86ISD::SETCC_CARRY:
20089 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20090 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20091 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20092 // truncated to i1 using 'and'.
20093 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20095 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20096 "Invalid use of SETCC_CARRY!");
20098 case X86ISD::SETCC:
20099 // Set the condition code or opposite one if necessary.
20100 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20101 if (needOppositeCond)
20102 CC = X86::GetOppositeBranchCondition(CC);
20103 return SetCC.getOperand(1);
20104 case X86ISD::CMOV: {
20105 // Check whether false/true value has canonical one, i.e. 0 or 1.
20106 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20107 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20108 // Quit if true value is not a constant.
20111 // Quit if false value is not a constant.
20113 SDValue Op = SetCC.getOperand(0);
20114 // Skip 'zext' or 'trunc' node.
20115 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20116 Op.getOpcode() == ISD::TRUNCATE)
20117 Op = Op.getOperand(0);
20118 // A special case for rdrand/rdseed, where 0 is set if false cond is
20120 if ((Op.getOpcode() != X86ISD::RDRAND &&
20121 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20124 // Quit if false value is not the constant 0 or 1.
20125 bool FValIsFalse = true;
20126 if (FVal && FVal->getZExtValue() != 0) {
20127 if (FVal->getZExtValue() != 1)
20129 // If FVal is 1, opposite cond is needed.
20130 needOppositeCond = !needOppositeCond;
20131 FValIsFalse = false;
20133 // Quit if TVal is not the constant opposite of FVal.
20134 if (FValIsFalse && TVal->getZExtValue() != 1)
20136 if (!FValIsFalse && TVal->getZExtValue() != 0)
20138 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20139 if (needOppositeCond)
20140 CC = X86::GetOppositeBranchCondition(CC);
20141 return SetCC.getOperand(3);
20148 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20149 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20150 TargetLowering::DAGCombinerInfo &DCI,
20151 const X86Subtarget *Subtarget) {
20154 // If the flag operand isn't dead, don't touch this CMOV.
20155 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20158 SDValue FalseOp = N->getOperand(0);
20159 SDValue TrueOp = N->getOperand(1);
20160 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20161 SDValue Cond = N->getOperand(3);
20163 if (CC == X86::COND_E || CC == X86::COND_NE) {
20164 switch (Cond.getOpcode()) {
20168 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20169 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20170 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20176 Flags = checkBoolTestSetCCCombine(Cond, CC);
20177 if (Flags.getNode() &&
20178 // Extra check as FCMOV only supports a subset of X86 cond.
20179 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20180 SDValue Ops[] = { FalseOp, TrueOp,
20181 DAG.getConstant(CC, MVT::i8), Flags };
20182 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20185 // If this is a select between two integer constants, try to do some
20186 // optimizations. Note that the operands are ordered the opposite of SELECT
20188 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20189 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20190 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20191 // larger than FalseC (the false value).
20192 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20193 CC = X86::GetOppositeBranchCondition(CC);
20194 std::swap(TrueC, FalseC);
20195 std::swap(TrueOp, FalseOp);
20198 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20199 // This is efficient for any integer data type (including i8/i16) and
20201 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20202 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20203 DAG.getConstant(CC, MVT::i8), Cond);
20205 // Zero extend the condition if needed.
20206 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20208 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20209 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20210 DAG.getConstant(ShAmt, MVT::i8));
20211 if (N->getNumValues() == 2) // Dead flag value?
20212 return DCI.CombineTo(N, Cond, SDValue());
20216 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20217 // for any integer data type, including i8/i16.
20218 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20219 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20220 DAG.getConstant(CC, MVT::i8), Cond);
20222 // Zero extend the condition if needed.
20223 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20224 FalseC->getValueType(0), Cond);
20225 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20226 SDValue(FalseC, 0));
20228 if (N->getNumValues() == 2) // Dead flag value?
20229 return DCI.CombineTo(N, Cond, SDValue());
20233 // Optimize cases that will turn into an LEA instruction. This requires
20234 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20235 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20236 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20237 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20239 bool isFastMultiplier = false;
20241 switch ((unsigned char)Diff) {
20243 case 1: // result = add base, cond
20244 case 2: // result = lea base( , cond*2)
20245 case 3: // result = lea base(cond, cond*2)
20246 case 4: // result = lea base( , cond*4)
20247 case 5: // result = lea base(cond, cond*4)
20248 case 8: // result = lea base( , cond*8)
20249 case 9: // result = lea base(cond, cond*8)
20250 isFastMultiplier = true;
20255 if (isFastMultiplier) {
20256 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20257 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20258 DAG.getConstant(CC, MVT::i8), Cond);
20259 // Zero extend the condition if needed.
20260 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20262 // Scale the condition by the difference.
20264 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20265 DAG.getConstant(Diff, Cond.getValueType()));
20267 // Add the base if non-zero.
20268 if (FalseC->getAPIntValue() != 0)
20269 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20270 SDValue(FalseC, 0));
20271 if (N->getNumValues() == 2) // Dead flag value?
20272 return DCI.CombineTo(N, Cond, SDValue());
20279 // Handle these cases:
20280 // (select (x != c), e, c) -> select (x != c), e, x),
20281 // (select (x == c), c, e) -> select (x == c), x, e)
20282 // where the c is an integer constant, and the "select" is the combination
20283 // of CMOV and CMP.
20285 // The rationale for this change is that the conditional-move from a constant
20286 // needs two instructions, however, conditional-move from a register needs
20287 // only one instruction.
20289 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20290 // some instruction-combining opportunities. This opt needs to be
20291 // postponed as late as possible.
20293 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20294 // the DCI.xxxx conditions are provided to postpone the optimization as
20295 // late as possible.
20297 ConstantSDNode *CmpAgainst = nullptr;
20298 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20299 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20300 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20302 if (CC == X86::COND_NE &&
20303 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20304 CC = X86::GetOppositeBranchCondition(CC);
20305 std::swap(TrueOp, FalseOp);
20308 if (CC == X86::COND_E &&
20309 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20310 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20311 DAG.getConstant(CC, MVT::i8), Cond };
20312 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20320 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20321 const X86Subtarget *Subtarget) {
20322 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20324 default: return SDValue();
20325 // SSE/AVX/AVX2 blend intrinsics.
20326 case Intrinsic::x86_avx2_pblendvb:
20327 case Intrinsic::x86_avx2_pblendw:
20328 case Intrinsic::x86_avx2_pblendd_128:
20329 case Intrinsic::x86_avx2_pblendd_256:
20330 // Don't try to simplify this intrinsic if we don't have AVX2.
20331 if (!Subtarget->hasAVX2())
20334 case Intrinsic::x86_avx_blend_pd_256:
20335 case Intrinsic::x86_avx_blend_ps_256:
20336 case Intrinsic::x86_avx_blendv_pd_256:
20337 case Intrinsic::x86_avx_blendv_ps_256:
20338 // Don't try to simplify this intrinsic if we don't have AVX.
20339 if (!Subtarget->hasAVX())
20342 case Intrinsic::x86_sse41_pblendw:
20343 case Intrinsic::x86_sse41_blendpd:
20344 case Intrinsic::x86_sse41_blendps:
20345 case Intrinsic::x86_sse41_blendvps:
20346 case Intrinsic::x86_sse41_blendvpd:
20347 case Intrinsic::x86_sse41_pblendvb: {
20348 SDValue Op0 = N->getOperand(1);
20349 SDValue Op1 = N->getOperand(2);
20350 SDValue Mask = N->getOperand(3);
20352 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20353 if (!Subtarget->hasSSE41())
20356 // fold (blend A, A, Mask) -> A
20359 // fold (blend A, B, allZeros) -> A
20360 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20362 // fold (blend A, B, allOnes) -> B
20363 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20366 // Simplify the case where the mask is a constant i32 value.
20367 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20368 if (C->isNullValue())
20370 if (C->isAllOnesValue())
20377 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20378 case Intrinsic::x86_sse2_psrai_w:
20379 case Intrinsic::x86_sse2_psrai_d:
20380 case Intrinsic::x86_avx2_psrai_w:
20381 case Intrinsic::x86_avx2_psrai_d:
20382 case Intrinsic::x86_sse2_psra_w:
20383 case Intrinsic::x86_sse2_psra_d:
20384 case Intrinsic::x86_avx2_psra_w:
20385 case Intrinsic::x86_avx2_psra_d: {
20386 SDValue Op0 = N->getOperand(1);
20387 SDValue Op1 = N->getOperand(2);
20388 EVT VT = Op0.getValueType();
20389 assert(VT.isVector() && "Expected a vector type!");
20391 if (isa<BuildVectorSDNode>(Op1))
20392 Op1 = Op1.getOperand(0);
20394 if (!isa<ConstantSDNode>(Op1))
20397 EVT SVT = VT.getVectorElementType();
20398 unsigned SVTBits = SVT.getSizeInBits();
20400 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20401 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20402 uint64_t ShAmt = C.getZExtValue();
20404 // Don't try to convert this shift into a ISD::SRA if the shift
20405 // count is bigger than or equal to the element size.
20406 if (ShAmt >= SVTBits)
20409 // Trivial case: if the shift count is zero, then fold this
20410 // into the first operand.
20414 // Replace this packed shift intrinsic with a target independent
20416 SDValue Splat = DAG.getConstant(C, VT);
20417 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20422 /// PerformMulCombine - Optimize a single multiply with constant into two
20423 /// in order to implement it with two cheaper instructions, e.g.
20424 /// LEA + SHL, LEA + LEA.
20425 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20426 TargetLowering::DAGCombinerInfo &DCI) {
20427 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20430 EVT VT = N->getValueType(0);
20431 if (VT != MVT::i64)
20434 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20437 uint64_t MulAmt = C->getZExtValue();
20438 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20441 uint64_t MulAmt1 = 0;
20442 uint64_t MulAmt2 = 0;
20443 if ((MulAmt % 9) == 0) {
20445 MulAmt2 = MulAmt / 9;
20446 } else if ((MulAmt % 5) == 0) {
20448 MulAmt2 = MulAmt / 5;
20449 } else if ((MulAmt % 3) == 0) {
20451 MulAmt2 = MulAmt / 3;
20454 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20457 if (isPowerOf2_64(MulAmt2) &&
20458 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20459 // If second multiplifer is pow2, issue it first. We want the multiply by
20460 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20462 std::swap(MulAmt1, MulAmt2);
20465 if (isPowerOf2_64(MulAmt1))
20466 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20467 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20469 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20470 DAG.getConstant(MulAmt1, VT));
20472 if (isPowerOf2_64(MulAmt2))
20473 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20474 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20476 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20477 DAG.getConstant(MulAmt2, VT));
20479 // Do not add new nodes to DAG combiner worklist.
20480 DCI.CombineTo(N, NewMul, false);
20485 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20486 SDValue N0 = N->getOperand(0);
20487 SDValue N1 = N->getOperand(1);
20488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20489 EVT VT = N0.getValueType();
20491 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20492 // since the result of setcc_c is all zero's or all ones.
20493 if (VT.isInteger() && !VT.isVector() &&
20494 N1C && N0.getOpcode() == ISD::AND &&
20495 N0.getOperand(1).getOpcode() == ISD::Constant) {
20496 SDValue N00 = N0.getOperand(0);
20497 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20498 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20499 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20500 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20501 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20502 APInt ShAmt = N1C->getAPIntValue();
20503 Mask = Mask.shl(ShAmt);
20505 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20506 N00, DAG.getConstant(Mask, VT));
20510 // Hardware support for vector shifts is sparse which makes us scalarize the
20511 // vector operations in many cases. Also, on sandybridge ADD is faster than
20513 // (shl V, 1) -> add V,V
20514 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20515 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20516 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20517 // We shift all of the values by one. In many cases we do not have
20518 // hardware support for this operation. This is better expressed as an ADD
20520 if (N1SplatC->getZExtValue() == 1)
20521 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20527 /// \brief Returns a vector of 0s if the node in input is a vector logical
20528 /// shift by a constant amount which is known to be bigger than or equal
20529 /// to the vector element size in bits.
20530 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20531 const X86Subtarget *Subtarget) {
20532 EVT VT = N->getValueType(0);
20534 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20535 (!Subtarget->hasInt256() ||
20536 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20539 SDValue Amt = N->getOperand(1);
20541 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20542 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20543 APInt ShiftAmt = AmtSplat->getAPIntValue();
20544 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20546 // SSE2/AVX2 logical shifts always return a vector of 0s
20547 // if the shift amount is bigger than or equal to
20548 // the element size. The constant shift amount will be
20549 // encoded as a 8-bit immediate.
20550 if (ShiftAmt.trunc(8).uge(MaxAmount))
20551 return getZeroVector(VT, Subtarget, DAG, DL);
20557 /// PerformShiftCombine - Combine shifts.
20558 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20559 TargetLowering::DAGCombinerInfo &DCI,
20560 const X86Subtarget *Subtarget) {
20561 if (N->getOpcode() == ISD::SHL) {
20562 SDValue V = PerformSHLCombine(N, DAG);
20563 if (V.getNode()) return V;
20566 if (N->getOpcode() != ISD::SRA) {
20567 // Try to fold this logical shift into a zero vector.
20568 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20569 if (V.getNode()) return V;
20575 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20576 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20577 // and friends. Likewise for OR -> CMPNEQSS.
20578 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20579 TargetLowering::DAGCombinerInfo &DCI,
20580 const X86Subtarget *Subtarget) {
20583 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20584 // we're requiring SSE2 for both.
20585 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20586 SDValue N0 = N->getOperand(0);
20587 SDValue N1 = N->getOperand(1);
20588 SDValue CMP0 = N0->getOperand(1);
20589 SDValue CMP1 = N1->getOperand(1);
20592 // The SETCCs should both refer to the same CMP.
20593 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20596 SDValue CMP00 = CMP0->getOperand(0);
20597 SDValue CMP01 = CMP0->getOperand(1);
20598 EVT VT = CMP00.getValueType();
20600 if (VT == MVT::f32 || VT == MVT::f64) {
20601 bool ExpectingFlags = false;
20602 // Check for any users that want flags:
20603 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20604 !ExpectingFlags && UI != UE; ++UI)
20605 switch (UI->getOpcode()) {
20610 ExpectingFlags = true;
20612 case ISD::CopyToReg:
20613 case ISD::SIGN_EXTEND:
20614 case ISD::ZERO_EXTEND:
20615 case ISD::ANY_EXTEND:
20619 if (!ExpectingFlags) {
20620 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20621 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20623 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20624 X86::CondCode tmp = cc0;
20629 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20630 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20631 // FIXME: need symbolic constants for these magic numbers.
20632 // See X86ATTInstPrinter.cpp:printSSECC().
20633 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20634 if (Subtarget->hasAVX512()) {
20635 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20636 CMP01, DAG.getConstant(x86cc, MVT::i8));
20637 if (N->getValueType(0) != MVT::i1)
20638 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20642 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20643 CMP00.getValueType(), CMP00, CMP01,
20644 DAG.getConstant(x86cc, MVT::i8));
20646 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20647 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20649 if (is64BitFP && !Subtarget->is64Bit()) {
20650 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20651 // 64-bit integer, since that's not a legal type. Since
20652 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20653 // bits, but can do this little dance to extract the lowest 32 bits
20654 // and work with those going forward.
20655 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20657 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20659 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20660 Vector32, DAG.getIntPtrConstant(0));
20664 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20665 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20666 DAG.getConstant(1, IntVT));
20667 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20668 return OneBitOfTruth;
20676 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20677 /// so it can be folded inside ANDNP.
20678 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20679 EVT VT = N->getValueType(0);
20681 // Match direct AllOnes for 128 and 256-bit vectors
20682 if (ISD::isBuildVectorAllOnes(N))
20685 // Look through a bit convert.
20686 if (N->getOpcode() == ISD::BITCAST)
20687 N = N->getOperand(0).getNode();
20689 // Sometimes the operand may come from a insert_subvector building a 256-bit
20691 if (VT.is256BitVector() &&
20692 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20693 SDValue V1 = N->getOperand(0);
20694 SDValue V2 = N->getOperand(1);
20696 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20697 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20698 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20699 ISD::isBuildVectorAllOnes(V2.getNode()))
20706 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20707 // register. In most cases we actually compare or select YMM-sized registers
20708 // and mixing the two types creates horrible code. This method optimizes
20709 // some of the transition sequences.
20710 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20711 TargetLowering::DAGCombinerInfo &DCI,
20712 const X86Subtarget *Subtarget) {
20713 EVT VT = N->getValueType(0);
20714 if (!VT.is256BitVector())
20717 assert((N->getOpcode() == ISD::ANY_EXTEND ||
20718 N->getOpcode() == ISD::ZERO_EXTEND ||
20719 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20721 SDValue Narrow = N->getOperand(0);
20722 EVT NarrowVT = Narrow->getValueType(0);
20723 if (!NarrowVT.is128BitVector())
20726 if (Narrow->getOpcode() != ISD::XOR &&
20727 Narrow->getOpcode() != ISD::AND &&
20728 Narrow->getOpcode() != ISD::OR)
20731 SDValue N0 = Narrow->getOperand(0);
20732 SDValue N1 = Narrow->getOperand(1);
20735 // The Left side has to be a trunc.
20736 if (N0.getOpcode() != ISD::TRUNCATE)
20739 // The type of the truncated inputs.
20740 EVT WideVT = N0->getOperand(0)->getValueType(0);
20744 // The right side has to be a 'trunc' or a constant vector.
20745 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20746 ConstantSDNode *RHSConstSplat = nullptr;
20747 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20748 RHSConstSplat = RHSBV->getConstantSplatNode();
20749 if (!RHSTrunc && !RHSConstSplat)
20752 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20754 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20757 // Set N0 and N1 to hold the inputs to the new wide operation.
20758 N0 = N0->getOperand(0);
20759 if (RHSConstSplat) {
20760 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20761 SDValue(RHSConstSplat, 0));
20762 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20763 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20764 } else if (RHSTrunc) {
20765 N1 = N1->getOperand(0);
20768 // Generate the wide operation.
20769 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20770 unsigned Opcode = N->getOpcode();
20772 case ISD::ANY_EXTEND:
20774 case ISD::ZERO_EXTEND: {
20775 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20776 APInt Mask = APInt::getAllOnesValue(InBits);
20777 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20778 return DAG.getNode(ISD::AND, DL, VT,
20779 Op, DAG.getConstant(Mask, VT));
20781 case ISD::SIGN_EXTEND:
20782 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20783 Op, DAG.getValueType(NarrowVT));
20785 llvm_unreachable("Unexpected opcode");
20789 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20790 TargetLowering::DAGCombinerInfo &DCI,
20791 const X86Subtarget *Subtarget) {
20792 EVT VT = N->getValueType(0);
20793 if (DCI.isBeforeLegalizeOps())
20796 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20800 // Create BEXTR instructions
20801 // BEXTR is ((X >> imm) & (2**size-1))
20802 if (VT == MVT::i32 || VT == MVT::i64) {
20803 SDValue N0 = N->getOperand(0);
20804 SDValue N1 = N->getOperand(1);
20807 // Check for BEXTR.
20808 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20809 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20810 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20811 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20812 if (MaskNode && ShiftNode) {
20813 uint64_t Mask = MaskNode->getZExtValue();
20814 uint64_t Shift = ShiftNode->getZExtValue();
20815 if (isMask_64(Mask)) {
20816 uint64_t MaskSize = CountPopulation_64(Mask);
20817 if (Shift + MaskSize <= VT.getSizeInBits())
20818 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20819 DAG.getConstant(Shift | (MaskSize << 8), VT));
20827 // Want to form ANDNP nodes:
20828 // 1) In the hopes of then easily combining them with OR and AND nodes
20829 // to form PBLEND/PSIGN.
20830 // 2) To match ANDN packed intrinsics
20831 if (VT != MVT::v2i64 && VT != MVT::v4i64)
20834 SDValue N0 = N->getOperand(0);
20835 SDValue N1 = N->getOperand(1);
20838 // Check LHS for vnot
20839 if (N0.getOpcode() == ISD::XOR &&
20840 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20841 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20842 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20844 // Check RHS for vnot
20845 if (N1.getOpcode() == ISD::XOR &&
20846 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20847 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20848 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20853 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20854 TargetLowering::DAGCombinerInfo &DCI,
20855 const X86Subtarget *Subtarget) {
20856 if (DCI.isBeforeLegalizeOps())
20859 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20863 SDValue N0 = N->getOperand(0);
20864 SDValue N1 = N->getOperand(1);
20865 EVT VT = N->getValueType(0);
20867 // look for psign/blend
20868 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20869 if (!Subtarget->hasSSSE3() ||
20870 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20873 // Canonicalize pandn to RHS
20874 if (N0.getOpcode() == X86ISD::ANDNP)
20876 // or (and (m, y), (pandn m, x))
20877 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20878 SDValue Mask = N1.getOperand(0);
20879 SDValue X = N1.getOperand(1);
20881 if (N0.getOperand(0) == Mask)
20882 Y = N0.getOperand(1);
20883 if (N0.getOperand(1) == Mask)
20884 Y = N0.getOperand(0);
20886 // Check to see if the mask appeared in both the AND and ANDNP and
20890 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20891 // Look through mask bitcast.
20892 if (Mask.getOpcode() == ISD::BITCAST)
20893 Mask = Mask.getOperand(0);
20894 if (X.getOpcode() == ISD::BITCAST)
20895 X = X.getOperand(0);
20896 if (Y.getOpcode() == ISD::BITCAST)
20897 Y = Y.getOperand(0);
20899 EVT MaskVT = Mask.getValueType();
20901 // Validate that the Mask operand is a vector sra node.
20902 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20903 // there is no psrai.b
20904 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20905 unsigned SraAmt = ~0;
20906 if (Mask.getOpcode() == ISD::SRA) {
20907 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20908 if (auto *AmtConst = AmtBV->getConstantSplatNode())
20909 SraAmt = AmtConst->getZExtValue();
20910 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20911 SDValue SraC = Mask.getOperand(1);
20912 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
20914 if ((SraAmt + 1) != EltBits)
20919 // Now we know we at least have a plendvb with the mask val. See if
20920 // we can form a psignb/w/d.
20921 // psign = x.type == y.type == mask.type && y = sub(0, x);
20922 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20923 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20924 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20925 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20926 "Unsupported VT for PSIGN");
20927 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20928 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20930 // PBLENDVB only available on SSE 4.1
20931 if (!Subtarget->hasSSE41())
20934 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20936 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20937 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20938 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20939 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20940 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20944 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20947 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20948 MachineFunction &MF = DAG.getMachineFunction();
20949 bool OptForSize = MF.getFunction()->getAttributes().
20950 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20952 // SHLD/SHRD instructions have lower register pressure, but on some
20953 // platforms they have higher latency than the equivalent
20954 // series of shifts/or that would otherwise be generated.
20955 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20956 // have higher latencies and we are not optimizing for size.
20957 if (!OptForSize && Subtarget->isSHLDSlow())
20960 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20962 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20964 if (!N0.hasOneUse() || !N1.hasOneUse())
20967 SDValue ShAmt0 = N0.getOperand(1);
20968 if (ShAmt0.getValueType() != MVT::i8)
20970 SDValue ShAmt1 = N1.getOperand(1);
20971 if (ShAmt1.getValueType() != MVT::i8)
20973 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20974 ShAmt0 = ShAmt0.getOperand(0);
20975 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20976 ShAmt1 = ShAmt1.getOperand(0);
20979 unsigned Opc = X86ISD::SHLD;
20980 SDValue Op0 = N0.getOperand(0);
20981 SDValue Op1 = N1.getOperand(0);
20982 if (ShAmt0.getOpcode() == ISD::SUB) {
20983 Opc = X86ISD::SHRD;
20984 std::swap(Op0, Op1);
20985 std::swap(ShAmt0, ShAmt1);
20988 unsigned Bits = VT.getSizeInBits();
20989 if (ShAmt1.getOpcode() == ISD::SUB) {
20990 SDValue Sum = ShAmt1.getOperand(0);
20991 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20992 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20993 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20994 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20995 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20996 return DAG.getNode(Opc, DL, VT,
20998 DAG.getNode(ISD::TRUNCATE, DL,
21001 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21002 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21004 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21005 return DAG.getNode(Opc, DL, VT,
21006 N0.getOperand(0), N1.getOperand(0),
21007 DAG.getNode(ISD::TRUNCATE, DL,
21014 // Generate NEG and CMOV for integer abs.
21015 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21016 EVT VT = N->getValueType(0);
21018 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21019 // 8-bit integer abs to NEG and CMOV.
21020 if (VT.isInteger() && VT.getSizeInBits() == 8)
21023 SDValue N0 = N->getOperand(0);
21024 SDValue N1 = N->getOperand(1);
21027 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21028 // and change it to SUB and CMOV.
21029 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21030 N0.getOpcode() == ISD::ADD &&
21031 N0.getOperand(1) == N1 &&
21032 N1.getOpcode() == ISD::SRA &&
21033 N1.getOperand(0) == N0.getOperand(0))
21034 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21035 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21036 // Generate SUB & CMOV.
21037 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21038 DAG.getConstant(0, VT), N0.getOperand(0));
21040 SDValue Ops[] = { N0.getOperand(0), Neg,
21041 DAG.getConstant(X86::COND_GE, MVT::i8),
21042 SDValue(Neg.getNode(), 1) };
21043 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21048 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21049 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21050 TargetLowering::DAGCombinerInfo &DCI,
21051 const X86Subtarget *Subtarget) {
21052 if (DCI.isBeforeLegalizeOps())
21055 if (Subtarget->hasCMov()) {
21056 SDValue RV = performIntegerAbsCombine(N, DAG);
21064 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21065 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21066 TargetLowering::DAGCombinerInfo &DCI,
21067 const X86Subtarget *Subtarget) {
21068 LoadSDNode *Ld = cast<LoadSDNode>(N);
21069 EVT RegVT = Ld->getValueType(0);
21070 EVT MemVT = Ld->getMemoryVT();
21072 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21074 // On Sandybridge unaligned 256bit loads are inefficient.
21075 ISD::LoadExtType Ext = Ld->getExtensionType();
21076 unsigned Alignment = Ld->getAlignment();
21077 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21078 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21079 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21080 unsigned NumElems = RegVT.getVectorNumElements();
21084 SDValue Ptr = Ld->getBasePtr();
21085 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21087 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21089 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21090 Ld->getPointerInfo(), Ld->isVolatile(),
21091 Ld->isNonTemporal(), Ld->isInvariant(),
21093 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21094 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21095 Ld->getPointerInfo(), Ld->isVolatile(),
21096 Ld->isNonTemporal(), Ld->isInvariant(),
21097 std::min(16U, Alignment));
21098 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21100 Load2.getValue(1));
21102 SDValue NewVec = DAG.getUNDEF(RegVT);
21103 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21104 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21105 return DCI.CombineTo(N, NewVec, TF, true);
21111 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21112 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21113 const X86Subtarget *Subtarget) {
21114 StoreSDNode *St = cast<StoreSDNode>(N);
21115 EVT VT = St->getValue().getValueType();
21116 EVT StVT = St->getMemoryVT();
21118 SDValue StoredVal = St->getOperand(1);
21119 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21121 // If we are saving a concatenation of two XMM registers, perform two stores.
21122 // On Sandy Bridge, 256-bit memory operations are executed by two
21123 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21124 // memory operation.
21125 unsigned Alignment = St->getAlignment();
21126 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21127 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21128 StVT == VT && !IsAligned) {
21129 unsigned NumElems = VT.getVectorNumElements();
21133 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21134 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21136 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21137 SDValue Ptr0 = St->getBasePtr();
21138 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21140 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21141 St->getPointerInfo(), St->isVolatile(),
21142 St->isNonTemporal(), Alignment);
21143 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21144 St->getPointerInfo(), St->isVolatile(),
21145 St->isNonTemporal(),
21146 std::min(16U, Alignment));
21147 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21150 // Optimize trunc store (of multiple scalars) to shuffle and store.
21151 // First, pack all of the elements in one place. Next, store to memory
21152 // in fewer chunks.
21153 if (St->isTruncatingStore() && VT.isVector()) {
21154 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21155 unsigned NumElems = VT.getVectorNumElements();
21156 assert(StVT != VT && "Cannot truncate to the same type");
21157 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21158 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21160 // From, To sizes and ElemCount must be pow of two
21161 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21162 // We are going to use the original vector elt for storing.
21163 // Accumulated smaller vector elements must be a multiple of the store size.
21164 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21166 unsigned SizeRatio = FromSz / ToSz;
21168 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21170 // Create a type on which we perform the shuffle
21171 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21172 StVT.getScalarType(), NumElems*SizeRatio);
21174 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21176 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21177 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21178 for (unsigned i = 0; i != NumElems; ++i)
21179 ShuffleVec[i] = i * SizeRatio;
21181 // Can't shuffle using an illegal type.
21182 if (!TLI.isTypeLegal(WideVecVT))
21185 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21186 DAG.getUNDEF(WideVecVT),
21188 // At this point all of the data is stored at the bottom of the
21189 // register. We now need to save it to mem.
21191 // Find the largest store unit
21192 MVT StoreType = MVT::i8;
21193 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21194 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21195 MVT Tp = (MVT::SimpleValueType)tp;
21196 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21200 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21201 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21202 (64 <= NumElems * ToSz))
21203 StoreType = MVT::f64;
21205 // Bitcast the original vector into a vector of store-size units
21206 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21207 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21208 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21209 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21210 SmallVector<SDValue, 8> Chains;
21211 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21212 TLI.getPointerTy());
21213 SDValue Ptr = St->getBasePtr();
21215 // Perform one or more big stores into memory.
21216 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21217 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21218 StoreType, ShuffWide,
21219 DAG.getIntPtrConstant(i));
21220 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21221 St->getPointerInfo(), St->isVolatile(),
21222 St->isNonTemporal(), St->getAlignment());
21223 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21224 Chains.push_back(Ch);
21227 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21230 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21231 // the FP state in cases where an emms may be missing.
21232 // A preferable solution to the general problem is to figure out the right
21233 // places to insert EMMS. This qualifies as a quick hack.
21235 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21236 if (VT.getSizeInBits() != 64)
21239 const Function *F = DAG.getMachineFunction().getFunction();
21240 bool NoImplicitFloatOps = F->getAttributes().
21241 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21242 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21243 && Subtarget->hasSSE2();
21244 if ((VT.isVector() ||
21245 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21246 isa<LoadSDNode>(St->getValue()) &&
21247 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21248 St->getChain().hasOneUse() && !St->isVolatile()) {
21249 SDNode* LdVal = St->getValue().getNode();
21250 LoadSDNode *Ld = nullptr;
21251 int TokenFactorIndex = -1;
21252 SmallVector<SDValue, 8> Ops;
21253 SDNode* ChainVal = St->getChain().getNode();
21254 // Must be a store of a load. We currently handle two cases: the load
21255 // is a direct child, and it's under an intervening TokenFactor. It is
21256 // possible to dig deeper under nested TokenFactors.
21257 if (ChainVal == LdVal)
21258 Ld = cast<LoadSDNode>(St->getChain());
21259 else if (St->getValue().hasOneUse() &&
21260 ChainVal->getOpcode() == ISD::TokenFactor) {
21261 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21262 if (ChainVal->getOperand(i).getNode() == LdVal) {
21263 TokenFactorIndex = i;
21264 Ld = cast<LoadSDNode>(St->getValue());
21266 Ops.push_back(ChainVal->getOperand(i));
21270 if (!Ld || !ISD::isNormalLoad(Ld))
21273 // If this is not the MMX case, i.e. we are just turning i64 load/store
21274 // into f64 load/store, avoid the transformation if there are multiple
21275 // uses of the loaded value.
21276 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21281 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21282 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21284 if (Subtarget->is64Bit() || F64IsLegal) {
21285 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21286 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21287 Ld->getPointerInfo(), Ld->isVolatile(),
21288 Ld->isNonTemporal(), Ld->isInvariant(),
21289 Ld->getAlignment());
21290 SDValue NewChain = NewLd.getValue(1);
21291 if (TokenFactorIndex != -1) {
21292 Ops.push_back(NewChain);
21293 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21295 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21296 St->getPointerInfo(),
21297 St->isVolatile(), St->isNonTemporal(),
21298 St->getAlignment());
21301 // Otherwise, lower to two pairs of 32-bit loads / stores.
21302 SDValue LoAddr = Ld->getBasePtr();
21303 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21304 DAG.getConstant(4, MVT::i32));
21306 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21307 Ld->getPointerInfo(),
21308 Ld->isVolatile(), Ld->isNonTemporal(),
21309 Ld->isInvariant(), Ld->getAlignment());
21310 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21311 Ld->getPointerInfo().getWithOffset(4),
21312 Ld->isVolatile(), Ld->isNonTemporal(),
21314 MinAlign(Ld->getAlignment(), 4));
21316 SDValue NewChain = LoLd.getValue(1);
21317 if (TokenFactorIndex != -1) {
21318 Ops.push_back(LoLd);
21319 Ops.push_back(HiLd);
21320 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21323 LoAddr = St->getBasePtr();
21324 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21325 DAG.getConstant(4, MVT::i32));
21327 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21328 St->getPointerInfo(),
21329 St->isVolatile(), St->isNonTemporal(),
21330 St->getAlignment());
21331 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21332 St->getPointerInfo().getWithOffset(4),
21334 St->isNonTemporal(),
21335 MinAlign(St->getAlignment(), 4));
21336 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21341 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21342 /// and return the operands for the horizontal operation in LHS and RHS. A
21343 /// horizontal operation performs the binary operation on successive elements
21344 /// of its first operand, then on successive elements of its second operand,
21345 /// returning the resulting values in a vector. For example, if
21346 /// A = < float a0, float a1, float a2, float a3 >
21348 /// B = < float b0, float b1, float b2, float b3 >
21349 /// then the result of doing a horizontal operation on A and B is
21350 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21351 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21352 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21353 /// set to A, RHS to B, and the routine returns 'true'.
21354 /// Note that the binary operation should have the property that if one of the
21355 /// operands is UNDEF then the result is UNDEF.
21356 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21357 // Look for the following pattern: if
21358 // A = < float a0, float a1, float a2, float a3 >
21359 // B = < float b0, float b1, float b2, float b3 >
21361 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21362 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21363 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21364 // which is A horizontal-op B.
21366 // At least one of the operands should be a vector shuffle.
21367 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21368 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21371 MVT VT = LHS.getSimpleValueType();
21373 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21374 "Unsupported vector type for horizontal add/sub");
21376 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21377 // operate independently on 128-bit lanes.
21378 unsigned NumElts = VT.getVectorNumElements();
21379 unsigned NumLanes = VT.getSizeInBits()/128;
21380 unsigned NumLaneElts = NumElts / NumLanes;
21381 assert((NumLaneElts % 2 == 0) &&
21382 "Vector type should have an even number of elements in each lane");
21383 unsigned HalfLaneElts = NumLaneElts/2;
21385 // View LHS in the form
21386 // LHS = VECTOR_SHUFFLE A, B, LMask
21387 // If LHS is not a shuffle then pretend it is the shuffle
21388 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21389 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21392 SmallVector<int, 16> LMask(NumElts);
21393 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21394 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21395 A = LHS.getOperand(0);
21396 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21397 B = LHS.getOperand(1);
21398 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21399 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21401 if (LHS.getOpcode() != ISD::UNDEF)
21403 for (unsigned i = 0; i != NumElts; ++i)
21407 // Likewise, view RHS in the form
21408 // RHS = VECTOR_SHUFFLE C, D, RMask
21410 SmallVector<int, 16> RMask(NumElts);
21411 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21412 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21413 C = RHS.getOperand(0);
21414 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21415 D = RHS.getOperand(1);
21416 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21417 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21419 if (RHS.getOpcode() != ISD::UNDEF)
21421 for (unsigned i = 0; i != NumElts; ++i)
21425 // Check that the shuffles are both shuffling the same vectors.
21426 if (!(A == C && B == D) && !(A == D && B == C))
21429 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21430 if (!A.getNode() && !B.getNode())
21433 // If A and B occur in reverse order in RHS, then "swap" them (which means
21434 // rewriting the mask).
21436 CommuteVectorShuffleMask(RMask, NumElts);
21438 // At this point LHS and RHS are equivalent to
21439 // LHS = VECTOR_SHUFFLE A, B, LMask
21440 // RHS = VECTOR_SHUFFLE A, B, RMask
21441 // Check that the masks correspond to performing a horizontal operation.
21442 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21443 for (unsigned i = 0; i != NumLaneElts; ++i) {
21444 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21446 // Ignore any UNDEF components.
21447 if (LIdx < 0 || RIdx < 0 ||
21448 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21449 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21452 // Check that successive elements are being operated on. If not, this is
21453 // not a horizontal operation.
21454 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21455 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21456 if (!(LIdx == Index && RIdx == Index + 1) &&
21457 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21462 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21463 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21467 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21468 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21469 const X86Subtarget *Subtarget) {
21470 EVT VT = N->getValueType(0);
21471 SDValue LHS = N->getOperand(0);
21472 SDValue RHS = N->getOperand(1);
21474 // Try to synthesize horizontal adds from adds of shuffles.
21475 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21476 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21477 isHorizontalBinOp(LHS, RHS, true))
21478 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21482 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21483 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21484 const X86Subtarget *Subtarget) {
21485 EVT VT = N->getValueType(0);
21486 SDValue LHS = N->getOperand(0);
21487 SDValue RHS = N->getOperand(1);
21489 // Try to synthesize horizontal subs from subs of shuffles.
21490 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21491 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21492 isHorizontalBinOp(LHS, RHS, false))
21493 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21497 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21498 /// X86ISD::FXOR nodes.
21499 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21500 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21501 // F[X]OR(0.0, x) -> x
21502 // F[X]OR(x, 0.0) -> x
21503 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21504 if (C->getValueAPF().isPosZero())
21505 return N->getOperand(1);
21506 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21507 if (C->getValueAPF().isPosZero())
21508 return N->getOperand(0);
21512 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21513 /// X86ISD::FMAX nodes.
21514 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21515 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21517 // Only perform optimizations if UnsafeMath is used.
21518 if (!DAG.getTarget().Options.UnsafeFPMath)
21521 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21522 // into FMINC and FMAXC, which are Commutative operations.
21523 unsigned NewOp = 0;
21524 switch (N->getOpcode()) {
21525 default: llvm_unreachable("unknown opcode");
21526 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21527 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21530 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21531 N->getOperand(0), N->getOperand(1));
21534 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21535 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21536 // FAND(0.0, x) -> 0.0
21537 // FAND(x, 0.0) -> 0.0
21538 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21539 if (C->getValueAPF().isPosZero())
21540 return N->getOperand(0);
21541 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21542 if (C->getValueAPF().isPosZero())
21543 return N->getOperand(1);
21547 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21548 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21549 // FANDN(x, 0.0) -> 0.0
21550 // FANDN(0.0, x) -> x
21551 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21552 if (C->getValueAPF().isPosZero())
21553 return N->getOperand(1);
21554 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21555 if (C->getValueAPF().isPosZero())
21556 return N->getOperand(1);
21560 static SDValue PerformBTCombine(SDNode *N,
21562 TargetLowering::DAGCombinerInfo &DCI) {
21563 // BT ignores high bits in the bit index operand.
21564 SDValue Op1 = N->getOperand(1);
21565 if (Op1.hasOneUse()) {
21566 unsigned BitWidth = Op1.getValueSizeInBits();
21567 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21568 APInt KnownZero, KnownOne;
21569 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21570 !DCI.isBeforeLegalizeOps());
21571 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21572 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21573 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21574 DCI.CommitTargetLoweringOpt(TLO);
21579 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21580 SDValue Op = N->getOperand(0);
21581 if (Op.getOpcode() == ISD::BITCAST)
21582 Op = Op.getOperand(0);
21583 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21584 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21585 VT.getVectorElementType().getSizeInBits() ==
21586 OpVT.getVectorElementType().getSizeInBits()) {
21587 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21592 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21593 const X86Subtarget *Subtarget) {
21594 EVT VT = N->getValueType(0);
21595 if (!VT.isVector())
21598 SDValue N0 = N->getOperand(0);
21599 SDValue N1 = N->getOperand(1);
21600 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21603 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21604 // both SSE and AVX2 since there is no sign-extended shift right
21605 // operation on a vector with 64-bit elements.
21606 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21607 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21608 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21609 N0.getOpcode() == ISD::SIGN_EXTEND)) {
21610 SDValue N00 = N0.getOperand(0);
21612 // EXTLOAD has a better solution on AVX2,
21613 // it may be replaced with X86ISD::VSEXT node.
21614 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21615 if (!ISD::isNormalLoad(N00.getNode()))
21618 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21619 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21621 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21627 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21628 TargetLowering::DAGCombinerInfo &DCI,
21629 const X86Subtarget *Subtarget) {
21630 if (!DCI.isBeforeLegalizeOps())
21633 if (!Subtarget->hasFp256())
21636 EVT VT = N->getValueType(0);
21637 if (VT.isVector() && VT.getSizeInBits() == 256) {
21638 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21646 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21647 const X86Subtarget* Subtarget) {
21649 EVT VT = N->getValueType(0);
21651 // Let legalize expand this if it isn't a legal type yet.
21652 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21655 EVT ScalarVT = VT.getScalarType();
21656 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21657 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21660 SDValue A = N->getOperand(0);
21661 SDValue B = N->getOperand(1);
21662 SDValue C = N->getOperand(2);
21664 bool NegA = (A.getOpcode() == ISD::FNEG);
21665 bool NegB = (B.getOpcode() == ISD::FNEG);
21666 bool NegC = (C.getOpcode() == ISD::FNEG);
21668 // Negative multiplication when NegA xor NegB
21669 bool NegMul = (NegA != NegB);
21671 A = A.getOperand(0);
21673 B = B.getOperand(0);
21675 C = C.getOperand(0);
21679 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21681 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21683 return DAG.getNode(Opcode, dl, VT, A, B, C);
21686 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21687 TargetLowering::DAGCombinerInfo &DCI,
21688 const X86Subtarget *Subtarget) {
21689 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
21690 // (and (i32 x86isd::setcc_carry), 1)
21691 // This eliminates the zext. This transformation is necessary because
21692 // ISD::SETCC is always legalized to i8.
21694 SDValue N0 = N->getOperand(0);
21695 EVT VT = N->getValueType(0);
21697 if (N0.getOpcode() == ISD::AND &&
21699 N0.getOperand(0).hasOneUse()) {
21700 SDValue N00 = N0.getOperand(0);
21701 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21702 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21703 if (!C || C->getZExtValue() != 1)
21705 return DAG.getNode(ISD::AND, dl, VT,
21706 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21707 N00.getOperand(0), N00.getOperand(1)),
21708 DAG.getConstant(1, VT));
21712 if (N0.getOpcode() == ISD::TRUNCATE &&
21714 N0.getOperand(0).hasOneUse()) {
21715 SDValue N00 = N0.getOperand(0);
21716 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21717 return DAG.getNode(ISD::AND, dl, VT,
21718 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21719 N00.getOperand(0), N00.getOperand(1)),
21720 DAG.getConstant(1, VT));
21723 if (VT.is256BitVector()) {
21724 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21732 // Optimize x == -y --> x+y == 0
21733 // x != -y --> x+y != 0
21734 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21735 const X86Subtarget* Subtarget) {
21736 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21737 SDValue LHS = N->getOperand(0);
21738 SDValue RHS = N->getOperand(1);
21739 EVT VT = N->getValueType(0);
21742 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21743 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21744 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21745 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21746 LHS.getValueType(), RHS, LHS.getOperand(1));
21747 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21748 addV, DAG.getConstant(0, addV.getValueType()), CC);
21750 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21751 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21752 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21753 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21754 RHS.getValueType(), LHS, RHS.getOperand(1));
21755 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21756 addV, DAG.getConstant(0, addV.getValueType()), CC);
21759 if (VT.getScalarType() == MVT::i1) {
21760 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21761 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21762 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21763 if (!IsSEXT0 && !IsVZero0)
21765 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21766 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21767 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21769 if (!IsSEXT1 && !IsVZero1)
21772 if (IsSEXT0 && IsVZero1) {
21773 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21774 if (CC == ISD::SETEQ)
21775 return DAG.getNOT(DL, LHS.getOperand(0), VT);
21776 return LHS.getOperand(0);
21778 if (IsSEXT1 && IsVZero0) {
21779 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21780 if (CC == ISD::SETEQ)
21781 return DAG.getNOT(DL, RHS.getOperand(0), VT);
21782 return RHS.getOperand(0);
21789 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21790 const X86Subtarget *Subtarget) {
21792 MVT VT = N->getOperand(1)->getSimpleValueType(0);
21793 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21794 "X86insertps is only defined for v4x32");
21796 SDValue Ld = N->getOperand(1);
21797 if (MayFoldLoad(Ld)) {
21798 // Extract the countS bits from the immediate so we can get the proper
21799 // address when narrowing the vector load to a specific element.
21800 // When the second source op is a memory address, interps doesn't use
21801 // countS and just gets an f32 from that address.
21802 unsigned DestIndex =
21803 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21804 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21808 // Create this as a scalar to vector to match the instruction pattern.
21809 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21810 // countS bits are ignored when loading from memory on insertps, which
21811 // means we don't need to explicitly set them to 0.
21812 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21813 LoadScalarToVector, N->getOperand(2));
21816 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21817 // as "sbb reg,reg", since it can be extended without zext and produces
21818 // an all-ones bit which is more useful than 0/1 in some cases.
21819 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21822 return DAG.getNode(ISD::AND, DL, VT,
21823 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21824 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21825 DAG.getConstant(1, VT));
21826 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21827 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21828 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21829 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21832 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21833 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21834 TargetLowering::DAGCombinerInfo &DCI,
21835 const X86Subtarget *Subtarget) {
21837 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21838 SDValue EFLAGS = N->getOperand(1);
21840 if (CC == X86::COND_A) {
21841 // Try to convert COND_A into COND_B in an attempt to facilitate
21842 // materializing "setb reg".
21844 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21845 // cannot take an immediate as its first operand.
21847 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21848 EFLAGS.getValueType().isInteger() &&
21849 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21850 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21851 EFLAGS.getNode()->getVTList(),
21852 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21853 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21854 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21858 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21859 // a zext and produces an all-ones bit which is more useful than 0/1 in some
21861 if (CC == X86::COND_B)
21862 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21866 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21867 if (Flags.getNode()) {
21868 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21869 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21875 // Optimize branch condition evaluation.
21877 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21878 TargetLowering::DAGCombinerInfo &DCI,
21879 const X86Subtarget *Subtarget) {
21881 SDValue Chain = N->getOperand(0);
21882 SDValue Dest = N->getOperand(1);
21883 SDValue EFLAGS = N->getOperand(3);
21884 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21888 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21889 if (Flags.getNode()) {
21890 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21891 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21898 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
21899 SelectionDAG &DAG) {
21900 // Take advantage of vector comparisons producing 0 or -1 in each lane to
21901 // optimize away operation when it's from a constant.
21903 // The general transformation is:
21904 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
21905 // AND(VECTOR_CMP(x,y), constant2)
21906 // constant2 = UNARYOP(constant)
21908 // Early exit if this isn't a vector operation, the operand of the
21909 // unary operation isn't a bitwise AND, or if the sizes of the operations
21910 // aren't the same.
21911 EVT VT = N->getValueType(0);
21912 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
21913 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
21914 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
21917 // Now check that the other operand of the AND is a constant. We could
21918 // make the transformation for non-constant splats as well, but it's unclear
21919 // that would be a benefit as it would not eliminate any operations, just
21920 // perform one more step in scalar code before moving to the vector unit.
21921 if (BuildVectorSDNode *BV =
21922 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
21923 // Bail out if the vector isn't a constant.
21924 if (!BV->isConstant())
21927 // Everything checks out. Build up the new and improved node.
21929 EVT IntVT = BV->getValueType(0);
21930 // Create a new constant of the appropriate type for the transformed
21932 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
21933 // The AND node needs bitcasts to/from an integer vector type around it.
21934 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
21935 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
21936 N->getOperand(0)->getOperand(0), MaskConst);
21937 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
21944 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21945 const X86TargetLowering *XTLI) {
21946 // First try to optimize away the conversion entirely when it's
21947 // conditionally from a constant. Vectors only.
21948 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
21949 if (Res != SDValue())
21952 // Now move on to more general possibilities.
21953 SDValue Op0 = N->getOperand(0);
21954 EVT InVT = Op0->getValueType(0);
21956 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21957 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21959 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21960 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21961 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21964 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21965 // a 32-bit target where SSE doesn't support i64->FP operations.
21966 if (Op0.getOpcode() == ISD::LOAD) {
21967 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21968 EVT VT = Ld->getValueType(0);
21969 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21970 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21971 !XTLI->getSubtarget()->is64Bit() &&
21973 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21974 Ld->getChain(), Op0, DAG);
21975 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21982 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21983 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21984 X86TargetLowering::DAGCombinerInfo &DCI) {
21985 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21986 // the result is either zero or one (depending on the input carry bit).
21987 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21988 if (X86::isZeroNode(N->getOperand(0)) &&
21989 X86::isZeroNode(N->getOperand(1)) &&
21990 // We don't have a good way to replace an EFLAGS use, so only do this when
21992 SDValue(N, 1).use_empty()) {
21994 EVT VT = N->getValueType(0);
21995 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21996 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21997 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21998 DAG.getConstant(X86::COND_B,MVT::i8),
22000 DAG.getConstant(1, VT));
22001 return DCI.CombineTo(N, Res1, CarryOut);
22007 // fold (add Y, (sete X, 0)) -> adc 0, Y
22008 // (add Y, (setne X, 0)) -> sbb -1, Y
22009 // (sub (sete X, 0), Y) -> sbb 0, Y
22010 // (sub (setne X, 0), Y) -> adc -1, Y
22011 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22014 // Look through ZExts.
22015 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22016 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22019 SDValue SetCC = Ext.getOperand(0);
22020 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22023 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22024 if (CC != X86::COND_E && CC != X86::COND_NE)
22027 SDValue Cmp = SetCC.getOperand(1);
22028 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22029 !X86::isZeroNode(Cmp.getOperand(1)) ||
22030 !Cmp.getOperand(0).getValueType().isInteger())
22033 SDValue CmpOp0 = Cmp.getOperand(0);
22034 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22035 DAG.getConstant(1, CmpOp0.getValueType()));
22037 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22038 if (CC == X86::COND_NE)
22039 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22040 DL, OtherVal.getValueType(), OtherVal,
22041 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22042 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22043 DL, OtherVal.getValueType(), OtherVal,
22044 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22047 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22048 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22049 const X86Subtarget *Subtarget) {
22050 EVT VT = N->getValueType(0);
22051 SDValue Op0 = N->getOperand(0);
22052 SDValue Op1 = N->getOperand(1);
22054 // Try to synthesize horizontal adds from adds of shuffles.
22055 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22056 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22057 isHorizontalBinOp(Op0, Op1, true))
22058 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22060 return OptimizeConditionalInDecrement(N, DAG);
22063 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22064 const X86Subtarget *Subtarget) {
22065 SDValue Op0 = N->getOperand(0);
22066 SDValue Op1 = N->getOperand(1);
22068 // X86 can't encode an immediate LHS of a sub. See if we can push the
22069 // negation into a preceding instruction.
22070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22071 // If the RHS of the sub is a XOR with one use and a constant, invert the
22072 // immediate. Then add one to the LHS of the sub so we can turn
22073 // X-Y -> X+~Y+1, saving one register.
22074 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22075 isa<ConstantSDNode>(Op1.getOperand(1))) {
22076 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22077 EVT VT = Op0.getValueType();
22078 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22080 DAG.getConstant(~XorC, VT));
22081 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22082 DAG.getConstant(C->getAPIntValue()+1, VT));
22086 // Try to synthesize horizontal adds from adds of shuffles.
22087 EVT VT = N->getValueType(0);
22088 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22089 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22090 isHorizontalBinOp(Op0, Op1, true))
22091 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22093 return OptimizeConditionalInDecrement(N, DAG);
22096 /// performVZEXTCombine - Performs build vector combines
22097 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22098 TargetLowering::DAGCombinerInfo &DCI,
22099 const X86Subtarget *Subtarget) {
22100 // (vzext (bitcast (vzext (x)) -> (vzext x)
22101 SDValue In = N->getOperand(0);
22102 while (In.getOpcode() == ISD::BITCAST)
22103 In = In.getOperand(0);
22105 if (In.getOpcode() != X86ISD::VZEXT)
22108 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22112 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22113 DAGCombinerInfo &DCI) const {
22114 SelectionDAG &DAG = DCI.DAG;
22115 switch (N->getOpcode()) {
22117 case ISD::EXTRACT_VECTOR_ELT:
22118 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22120 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22121 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22122 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22123 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22124 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22125 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22128 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22129 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22130 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22131 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22132 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22133 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22134 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22135 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22136 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22138 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22140 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22141 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22142 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22143 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22144 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22145 case ISD::ANY_EXTEND:
22146 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22147 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22148 case ISD::SIGN_EXTEND_INREG:
22149 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22150 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22151 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22152 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22153 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22154 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22155 case X86ISD::SHUFP: // Handle all target specific shuffles
22156 case X86ISD::PALIGNR:
22157 case X86ISD::UNPCKH:
22158 case X86ISD::UNPCKL:
22159 case X86ISD::MOVHLPS:
22160 case X86ISD::MOVLHPS:
22161 case X86ISD::PSHUFD:
22162 case X86ISD::PSHUFHW:
22163 case X86ISD::PSHUFLW:
22164 case X86ISD::MOVSS:
22165 case X86ISD::MOVSD:
22166 case X86ISD::VPERMILP:
22167 case X86ISD::VPERM2X128:
22168 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22169 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22170 case ISD::INTRINSIC_WO_CHAIN:
22171 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22172 case X86ISD::INSERTPS:
22173 return PerformINSERTPSCombine(N, DAG, Subtarget);
22174 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22180 /// isTypeDesirableForOp - Return true if the target has native support for
22181 /// the specified value type and it is 'desirable' to use the type for the
22182 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22183 /// instruction encodings are longer and some i16 instructions are slow.
22184 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22185 if (!isTypeLegal(VT))
22187 if (VT != MVT::i16)
22194 case ISD::SIGN_EXTEND:
22195 case ISD::ZERO_EXTEND:
22196 case ISD::ANY_EXTEND:
22209 /// IsDesirableToPromoteOp - This method query the target whether it is
22210 /// beneficial for dag combiner to promote the specified node. If true, it
22211 /// should return the desired promotion type by reference.
22212 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22213 EVT VT = Op.getValueType();
22214 if (VT != MVT::i16)
22217 bool Promote = false;
22218 bool Commute = false;
22219 switch (Op.getOpcode()) {
22222 LoadSDNode *LD = cast<LoadSDNode>(Op);
22223 // If the non-extending load has a single use and it's not live out, then it
22224 // might be folded.
22225 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22226 Op.hasOneUse()*/) {
22227 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22228 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22229 // The only case where we'd want to promote LOAD (rather then it being
22230 // promoted as an operand is when it's only use is liveout.
22231 if (UI->getOpcode() != ISD::CopyToReg)
22238 case ISD::SIGN_EXTEND:
22239 case ISD::ZERO_EXTEND:
22240 case ISD::ANY_EXTEND:
22245 SDValue N0 = Op.getOperand(0);
22246 // Look out for (store (shl (load), x)).
22247 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22260 SDValue N0 = Op.getOperand(0);
22261 SDValue N1 = Op.getOperand(1);
22262 if (!Commute && MayFoldLoad(N1))
22264 // Avoid disabling potential load folding opportunities.
22265 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22267 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22277 //===----------------------------------------------------------------------===//
22278 // X86 Inline Assembly Support
22279 //===----------------------------------------------------------------------===//
22282 // Helper to match a string separated by whitespace.
22283 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22284 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22286 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22287 StringRef piece(*args[i]);
22288 if (!s.startswith(piece)) // Check if the piece matches.
22291 s = s.substr(piece.size());
22292 StringRef::size_type pos = s.find_first_not_of(" \t");
22293 if (pos == 0) // We matched a prefix.
22301 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22304 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22306 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22307 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22308 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22309 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22311 if (AsmPieces.size() == 3)
22313 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22320 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22321 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22323 std::string AsmStr = IA->getAsmString();
22325 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22326 if (!Ty || Ty->getBitWidth() % 16 != 0)
22329 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22330 SmallVector<StringRef, 4> AsmPieces;
22331 SplitString(AsmStr, AsmPieces, ";\n");
22333 switch (AsmPieces.size()) {
22334 default: return false;
22336 // FIXME: this should verify that we are targeting a 486 or better. If not,
22337 // we will turn this bswap into something that will be lowered to logical
22338 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22339 // lower so don't worry about this.
22341 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22342 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22343 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22344 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22345 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22346 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22347 // No need to check constraints, nothing other than the equivalent of
22348 // "=r,0" would be valid here.
22349 return IntrinsicLowering::LowerToByteSwap(CI);
22352 // rorw $$8, ${0:w} --> llvm.bswap.i16
22353 if (CI->getType()->isIntegerTy(16) &&
22354 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22355 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22356 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22358 const std::string &ConstraintsStr = IA->getConstraintString();
22359 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22360 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22361 if (clobbersFlagRegisters(AsmPieces))
22362 return IntrinsicLowering::LowerToByteSwap(CI);
22366 if (CI->getType()->isIntegerTy(32) &&
22367 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22368 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22369 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22370 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22372 const std::string &ConstraintsStr = IA->getConstraintString();
22373 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22374 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22375 if (clobbersFlagRegisters(AsmPieces))
22376 return IntrinsicLowering::LowerToByteSwap(CI);
22379 if (CI->getType()->isIntegerTy(64)) {
22380 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22381 if (Constraints.size() >= 2 &&
22382 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22383 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22384 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22385 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22386 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22387 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22388 return IntrinsicLowering::LowerToByteSwap(CI);
22396 /// getConstraintType - Given a constraint letter, return the type of
22397 /// constraint it is for this target.
22398 X86TargetLowering::ConstraintType
22399 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22400 if (Constraint.size() == 1) {
22401 switch (Constraint[0]) {
22412 return C_RegisterClass;
22436 return TargetLowering::getConstraintType(Constraint);
22439 /// Examine constraint type and operand type and determine a weight value.
22440 /// This object must already have been set up with the operand type
22441 /// and the current alternative constraint selected.
22442 TargetLowering::ConstraintWeight
22443 X86TargetLowering::getSingleConstraintMatchWeight(
22444 AsmOperandInfo &info, const char *constraint) const {
22445 ConstraintWeight weight = CW_Invalid;
22446 Value *CallOperandVal = info.CallOperandVal;
22447 // If we don't have a value, we can't do a match,
22448 // but allow it at the lowest weight.
22449 if (!CallOperandVal)
22451 Type *type = CallOperandVal->getType();
22452 // Look at the constraint type.
22453 switch (*constraint) {
22455 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22466 if (CallOperandVal->getType()->isIntegerTy())
22467 weight = CW_SpecificReg;
22472 if (type->isFloatingPointTy())
22473 weight = CW_SpecificReg;
22476 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22477 weight = CW_SpecificReg;
22481 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22482 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22483 weight = CW_Register;
22486 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22487 if (C->getZExtValue() <= 31)
22488 weight = CW_Constant;
22492 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22493 if (C->getZExtValue() <= 63)
22494 weight = CW_Constant;
22498 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22499 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22500 weight = CW_Constant;
22504 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22505 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22506 weight = CW_Constant;
22510 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22511 if (C->getZExtValue() <= 3)
22512 weight = CW_Constant;
22516 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22517 if (C->getZExtValue() <= 0xff)
22518 weight = CW_Constant;
22523 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22524 weight = CW_Constant;
22528 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22529 if ((C->getSExtValue() >= -0x80000000LL) &&
22530 (C->getSExtValue() <= 0x7fffffffLL))
22531 weight = CW_Constant;
22535 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22536 if (C->getZExtValue() <= 0xffffffff)
22537 weight = CW_Constant;
22544 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22545 /// with another that has more specific requirements based on the type of the
22546 /// corresponding operand.
22547 const char *X86TargetLowering::
22548 LowerXConstraint(EVT ConstraintVT) const {
22549 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22550 // 'f' like normal targets.
22551 if (ConstraintVT.isFloatingPoint()) {
22552 if (Subtarget->hasSSE2())
22554 if (Subtarget->hasSSE1())
22558 return TargetLowering::LowerXConstraint(ConstraintVT);
22561 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22562 /// vector. If it is invalid, don't add anything to Ops.
22563 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22564 std::string &Constraint,
22565 std::vector<SDValue>&Ops,
22566 SelectionDAG &DAG) const {
22569 // Only support length 1 constraints for now.
22570 if (Constraint.length() > 1) return;
22572 char ConstraintLetter = Constraint[0];
22573 switch (ConstraintLetter) {
22576 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22577 if (C->getZExtValue() <= 31) {
22578 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22584 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22585 if (C->getZExtValue() <= 63) {
22586 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22592 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22593 if (isInt<8>(C->getSExtValue())) {
22594 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22601 if (C->getZExtValue() <= 255) {
22602 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22608 // 32-bit signed value
22609 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22610 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22611 C->getSExtValue())) {
22612 // Widen to 64 bits here to get it sign extended.
22613 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22616 // FIXME gcc accepts some relocatable values here too, but only in certain
22617 // memory models; it's complicated.
22622 // 32-bit unsigned value
22623 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22624 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22625 C->getZExtValue())) {
22626 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22630 // FIXME gcc accepts some relocatable values here too, but only in certain
22631 // memory models; it's complicated.
22635 // Literal immediates are always ok.
22636 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22637 // Widen to 64 bits here to get it sign extended.
22638 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22642 // In any sort of PIC mode addresses need to be computed at runtime by
22643 // adding in a register or some sort of table lookup. These can't
22644 // be used as immediates.
22645 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22648 // If we are in non-pic codegen mode, we allow the address of a global (with
22649 // an optional displacement) to be used with 'i'.
22650 GlobalAddressSDNode *GA = nullptr;
22651 int64_t Offset = 0;
22653 // Match either (GA), (GA+C), (GA+C1+C2), etc.
22655 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22656 Offset += GA->getOffset();
22658 } else if (Op.getOpcode() == ISD::ADD) {
22659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22660 Offset += C->getZExtValue();
22661 Op = Op.getOperand(0);
22664 } else if (Op.getOpcode() == ISD::SUB) {
22665 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22666 Offset += -C->getZExtValue();
22667 Op = Op.getOperand(0);
22672 // Otherwise, this isn't something we can handle, reject it.
22676 const GlobalValue *GV = GA->getGlobal();
22677 // If we require an extra load to get this address, as in PIC mode, we
22678 // can't accept it.
22679 if (isGlobalStubReference(
22680 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22683 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22684 GA->getValueType(0), Offset);
22689 if (Result.getNode()) {
22690 Ops.push_back(Result);
22693 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22696 std::pair<unsigned, const TargetRegisterClass*>
22697 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22699 // First, see if this is a constraint that directly corresponds to an LLVM
22701 if (Constraint.size() == 1) {
22702 // GCC Constraint Letters
22703 switch (Constraint[0]) {
22705 // TODO: Slight differences here in allocation order and leaving
22706 // RIP in the class. Do they matter any more here than they do
22707 // in the normal allocation?
22708 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22709 if (Subtarget->is64Bit()) {
22710 if (VT == MVT::i32 || VT == MVT::f32)
22711 return std::make_pair(0U, &X86::GR32RegClass);
22712 if (VT == MVT::i16)
22713 return std::make_pair(0U, &X86::GR16RegClass);
22714 if (VT == MVT::i8 || VT == MVT::i1)
22715 return std::make_pair(0U, &X86::GR8RegClass);
22716 if (VT == MVT::i64 || VT == MVT::f64)
22717 return std::make_pair(0U, &X86::GR64RegClass);
22720 // 32-bit fallthrough
22721 case 'Q': // Q_REGS
22722 if (VT == MVT::i32 || VT == MVT::f32)
22723 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22724 if (VT == MVT::i16)
22725 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22726 if (VT == MVT::i8 || VT == MVT::i1)
22727 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22728 if (VT == MVT::i64)
22729 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22731 case 'r': // GENERAL_REGS
22732 case 'l': // INDEX_REGS
22733 if (VT == MVT::i8 || VT == MVT::i1)
22734 return std::make_pair(0U, &X86::GR8RegClass);
22735 if (VT == MVT::i16)
22736 return std::make_pair(0U, &X86::GR16RegClass);
22737 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22738 return std::make_pair(0U, &X86::GR32RegClass);
22739 return std::make_pair(0U, &X86::GR64RegClass);
22740 case 'R': // LEGACY_REGS
22741 if (VT == MVT::i8 || VT == MVT::i1)
22742 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22743 if (VT == MVT::i16)
22744 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22745 if (VT == MVT::i32 || !Subtarget->is64Bit())
22746 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22747 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22748 case 'f': // FP Stack registers.
22749 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22750 // value to the correct fpstack register class.
22751 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22752 return std::make_pair(0U, &X86::RFP32RegClass);
22753 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22754 return std::make_pair(0U, &X86::RFP64RegClass);
22755 return std::make_pair(0U, &X86::RFP80RegClass);
22756 case 'y': // MMX_REGS if MMX allowed.
22757 if (!Subtarget->hasMMX()) break;
22758 return std::make_pair(0U, &X86::VR64RegClass);
22759 case 'Y': // SSE_REGS if SSE2 allowed
22760 if (!Subtarget->hasSSE2()) break;
22762 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22763 if (!Subtarget->hasSSE1()) break;
22765 switch (VT.SimpleTy) {
22767 // Scalar SSE types.
22770 return std::make_pair(0U, &X86::FR32RegClass);
22773 return std::make_pair(0U, &X86::FR64RegClass);
22781 return std::make_pair(0U, &X86::VR128RegClass);
22789 return std::make_pair(0U, &X86::VR256RegClass);
22794 return std::make_pair(0U, &X86::VR512RegClass);
22800 // Use the default implementation in TargetLowering to convert the register
22801 // constraint into a member of a register class.
22802 std::pair<unsigned, const TargetRegisterClass*> Res;
22803 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22805 // Not found as a standard register?
22807 // Map st(0) -> st(7) -> ST0
22808 if (Constraint.size() == 7 && Constraint[0] == '{' &&
22809 tolower(Constraint[1]) == 's' &&
22810 tolower(Constraint[2]) == 't' &&
22811 Constraint[3] == '(' &&
22812 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22813 Constraint[5] == ')' &&
22814 Constraint[6] == '}') {
22816 Res.first = X86::ST0+Constraint[4]-'0';
22817 Res.second = &X86::RFP80RegClass;
22821 // GCC allows "st(0)" to be called just plain "st".
22822 if (StringRef("{st}").equals_lower(Constraint)) {
22823 Res.first = X86::ST0;
22824 Res.second = &X86::RFP80RegClass;
22829 if (StringRef("{flags}").equals_lower(Constraint)) {
22830 Res.first = X86::EFLAGS;
22831 Res.second = &X86::CCRRegClass;
22835 // 'A' means EAX + EDX.
22836 if (Constraint == "A") {
22837 Res.first = X86::EAX;
22838 Res.second = &X86::GR32_ADRegClass;
22844 // Otherwise, check to see if this is a register class of the wrong value
22845 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22846 // turn into {ax},{dx}.
22847 if (Res.second->hasType(VT))
22848 return Res; // Correct type already, nothing to do.
22850 // All of the single-register GCC register classes map their values onto
22851 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
22852 // really want an 8-bit or 32-bit register, map to the appropriate register
22853 // class and return the appropriate register.
22854 if (Res.second == &X86::GR16RegClass) {
22855 if (VT == MVT::i8 || VT == MVT::i1) {
22856 unsigned DestReg = 0;
22857 switch (Res.first) {
22859 case X86::AX: DestReg = X86::AL; break;
22860 case X86::DX: DestReg = X86::DL; break;
22861 case X86::CX: DestReg = X86::CL; break;
22862 case X86::BX: DestReg = X86::BL; break;
22865 Res.first = DestReg;
22866 Res.second = &X86::GR8RegClass;
22868 } else if (VT == MVT::i32 || VT == MVT::f32) {
22869 unsigned DestReg = 0;
22870 switch (Res.first) {
22872 case X86::AX: DestReg = X86::EAX; break;
22873 case X86::DX: DestReg = X86::EDX; break;
22874 case X86::CX: DestReg = X86::ECX; break;
22875 case X86::BX: DestReg = X86::EBX; break;
22876 case X86::SI: DestReg = X86::ESI; break;
22877 case X86::DI: DestReg = X86::EDI; break;
22878 case X86::BP: DestReg = X86::EBP; break;
22879 case X86::SP: DestReg = X86::ESP; break;
22882 Res.first = DestReg;
22883 Res.second = &X86::GR32RegClass;
22885 } else if (VT == MVT::i64 || VT == MVT::f64) {
22886 unsigned DestReg = 0;
22887 switch (Res.first) {
22889 case X86::AX: DestReg = X86::RAX; break;
22890 case X86::DX: DestReg = X86::RDX; break;
22891 case X86::CX: DestReg = X86::RCX; break;
22892 case X86::BX: DestReg = X86::RBX; break;
22893 case X86::SI: DestReg = X86::RSI; break;
22894 case X86::DI: DestReg = X86::RDI; break;
22895 case X86::BP: DestReg = X86::RBP; break;
22896 case X86::SP: DestReg = X86::RSP; break;
22899 Res.first = DestReg;
22900 Res.second = &X86::GR64RegClass;
22903 } else if (Res.second == &X86::FR32RegClass ||
22904 Res.second == &X86::FR64RegClass ||
22905 Res.second == &X86::VR128RegClass ||
22906 Res.second == &X86::VR256RegClass ||
22907 Res.second == &X86::FR32XRegClass ||
22908 Res.second == &X86::FR64XRegClass ||
22909 Res.second == &X86::VR128XRegClass ||
22910 Res.second == &X86::VR256XRegClass ||
22911 Res.second == &X86::VR512RegClass) {
22912 // Handle references to XMM physical registers that got mapped into the
22913 // wrong class. This can happen with constraints like {xmm0} where the
22914 // target independent register mapper will just pick the first match it can
22915 // find, ignoring the required type.
22917 if (VT == MVT::f32 || VT == MVT::i32)
22918 Res.second = &X86::FR32RegClass;
22919 else if (VT == MVT::f64 || VT == MVT::i64)
22920 Res.second = &X86::FR64RegClass;
22921 else if (X86::VR128RegClass.hasType(VT))
22922 Res.second = &X86::VR128RegClass;
22923 else if (X86::VR256RegClass.hasType(VT))
22924 Res.second = &X86::VR256RegClass;
22925 else if (X86::VR512RegClass.hasType(VT))
22926 Res.second = &X86::VR512RegClass;
22932 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22934 // Scaling factors are not free at all.
22935 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22936 // will take 2 allocations in the out of order engine instead of 1
22937 // for plain addressing mode, i.e. inst (reg1).
22939 // vaddps (%rsi,%drx), %ymm0, %ymm1
22940 // Requires two allocations (one for the load, one for the computation)
22942 // vaddps (%rsi), %ymm0, %ymm1
22943 // Requires just 1 allocation, i.e., freeing allocations for other operations
22944 // and having less micro operations to execute.
22946 // For some X86 architectures, this is even worse because for instance for
22947 // stores, the complex addressing mode forces the instruction to use the
22948 // "load" ports instead of the dedicated "store" port.
22949 // E.g., on Haswell:
22950 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22951 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
22952 if (isLegalAddressingMode(AM, Ty))
22953 // Scale represents reg2 * scale, thus account for 1
22954 // as soon as we use a second register.
22955 return AM.Scale != 0;
22959 bool X86TargetLowering::isTargetFTOL() const {
22960 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();