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 TM.getSubtarget<X86Subtarget>().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 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651 Subtarget->is64Bit();
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656 if (ExperimentalVectorWideningLegalization &&
1657 VT.getVectorNumElements() != 1 &&
1658 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659 return TypeWidenVector;
1661 return TargetLoweringBase::getPreferredVectorAction(VT);
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1666 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1668 if (Subtarget->hasAVX512())
1669 switch(VT.getVectorNumElements()) {
1670 case 8: return MVT::v8i1;
1671 case 16: return MVT::v16i1;
1674 return VT.changeVectorElementTypeToInteger();
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1682 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683 if (VTy->getBitWidth() == 128)
1685 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686 unsigned EltAlign = 0;
1687 getMaxByValAlign(ATy->getElementType(), EltAlign);
1688 if (EltAlign > MaxAlign)
1689 MaxAlign = EltAlign;
1690 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692 unsigned EltAlign = 0;
1693 getMaxByValAlign(STy->getElementType(i), EltAlign);
1694 if (EltAlign > MaxAlign)
1695 MaxAlign = EltAlign;
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707 if (Subtarget->is64Bit()) {
1708 // Max of 8 and alignment of type.
1709 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1716 if (Subtarget->hasSSE1())
1717 getMaxByValAlign(Ty, Align);
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734 unsigned DstAlign, unsigned SrcAlign,
1735 bool IsMemset, bool ZeroMemset,
1737 MachineFunction &MF) const {
1738 const Function *F = MF.getFunction();
1739 if ((!IsMemset || ZeroMemset) &&
1740 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741 Attribute::NoImplicitFloat)) {
1743 (Subtarget->isUnalignedMemAccessFast() ||
1744 ((DstAlign == 0 || DstAlign >= 16) &&
1745 (SrcAlign == 0 || SrcAlign >= 16)))) {
1747 if (Subtarget->hasInt256())
1749 if (Subtarget->hasFp256())
1752 if (Subtarget->hasSSE2())
1754 if (Subtarget->hasSSE1())
1756 } else if (!MemcpyStrSrc && Size >= 8 &&
1757 !Subtarget->is64Bit() &&
1758 Subtarget->hasSSE2()) {
1759 // Do not use f64 to lower memcpy if source is string constant. It's
1760 // better to use i32 to avoid the loads.
1764 if (Subtarget->is64Bit() && Size >= 8)
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1771 return X86ScalarSSEf32;
1772 else if (VT == MVT::f64)
1773 return X86ScalarSSEf64;
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1783 *Fast = Subtarget->isUnalignedMemAccessFast();
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function. The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1793 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794 Subtarget->isPICStyleGOT())
1795 return MachineJumpTableInfo::EK_Custom32;
1797 // Otherwise, use the normal jump table encoding heuristics.
1798 return TargetLowering::getJumpTableEncoding();
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803 const MachineBasicBlock *MBB,
1804 unsigned uid,MCContext &Ctx) const{
1805 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806 Subtarget->isPICStyleGOT());
1807 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1809 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816 SelectionDAG &DAG) const {
1817 if (!Subtarget->is64Bit())
1818 // This doesn't have SDLoc associated with it, but is not really the
1819 // same as a Register.
1820 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829 MCContext &Ctx) const {
1830 // X86-64 uses RIP relative addressing based on the jump table label.
1831 if (Subtarget->isPICStyleRIPRel())
1832 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1834 // Otherwise, the reference is relative to the PIC base.
1835 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841 const TargetRegisterClass *RRC = nullptr;
1843 switch (VT.SimpleTy) {
1845 return TargetLowering::findRepresentativeClass(VT);
1846 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847 RRC = Subtarget->is64Bit() ?
1848 (const TargetRegisterClass*)&X86::GR64RegClass :
1849 (const TargetRegisterClass*)&X86::GR32RegClass;
1852 RRC = &X86::VR64RegClass;
1854 case MVT::f32: case MVT::f64:
1855 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856 case MVT::v4f32: case MVT::v2f64:
1857 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1859 RRC = &X86::VR128RegClass;
1862 return std::make_pair(RRC, Cost);
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866 unsigned &Offset) const {
1867 if (!Subtarget->isTargetLinux())
1870 if (Subtarget->is64Bit()) {
1871 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1873 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886 unsigned DestAS) const {
1887 assert(SrcAS != DestAS && "Expected different address spaces!");
1889 return SrcAS < 256 && DestAS < 256;
1892 //===----------------------------------------------------------------------===//
1893 // Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1896 #include "X86GenCallingConv.inc"
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900 MachineFunction &MF, bool isVarArg,
1901 const SmallVectorImpl<ISD::OutputArg> &Outs,
1902 LLVMContext &Context) const {
1903 SmallVector<CCValAssign, 16> RVLocs;
1904 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1906 return CCInfo.CheckReturn(Outs, RetCC_X86);
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916 CallingConv::ID CallConv, bool isVarArg,
1917 const SmallVectorImpl<ISD::OutputArg> &Outs,
1918 const SmallVectorImpl<SDValue> &OutVals,
1919 SDLoc dl, SelectionDAG &DAG) const {
1920 MachineFunction &MF = DAG.getMachineFunction();
1921 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1923 SmallVector<CCValAssign, 16> RVLocs;
1924 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925 RVLocs, *DAG.getContext());
1926 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1929 SmallVector<SDValue, 6> RetOps;
1930 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931 // Operand #1 = Bytes To Pop
1932 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1935 // Copy the result values into the output registers.
1936 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937 CCValAssign &VA = RVLocs[i];
1938 assert(VA.isRegLoc() && "Can only return in registers!");
1939 SDValue ValToCopy = OutVals[i];
1940 EVT ValVT = ValToCopy.getValueType();
1942 // Promote values to the appropriate types
1943 if (VA.getLocInfo() == CCValAssign::SExt)
1944 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945 else if (VA.getLocInfo() == CCValAssign::ZExt)
1946 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947 else if (VA.getLocInfo() == CCValAssign::AExt)
1948 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949 else if (VA.getLocInfo() == CCValAssign::BCvt)
1950 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1952 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953 "Unexpected FP-extend for return value.");
1955 // If this is x86-64, and we disabled SSE, we can't return FP values,
1956 // or SSE or MMX vectors.
1957 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960 report_fatal_error("SSE register return with SSE disabled");
1962 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1963 // llvm-gcc has never done it right and no one has noticed, so this
1964 // should be OK for now.
1965 if (ValVT == MVT::f64 &&
1966 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967 report_fatal_error("SSE2 register return with SSE2 disabled");
1969 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970 // the RET instruction and handled by the FP Stackifier.
1971 if (VA.getLocReg() == X86::FP0 ||
1972 VA.getLocReg() == X86::FP1) {
1973 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974 // change the value to the FP stack register class.
1975 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977 RetOps.push_back(ValToCopy);
1978 // Don't emit a copytoreg.
1982 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983 // which is returned in RAX / RDX.
1984 if (Subtarget->is64Bit()) {
1985 if (ValVT == MVT::x86mmx) {
1986 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1990 // If we don't have SSE2 available, convert to v4f32 so the generated
1991 // register is legal.
1992 if (!Subtarget->hasSSE2())
1993 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1998 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999 Flag = Chain.getValue(1);
2000 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2003 // The x86-64 ABIs require that for returning structs by value we copy
2004 // the sret argument into %rax/%eax (depending on ABI) for the return.
2005 // Win32 requires us to put the sret argument to %eax as well.
2006 // We saved the argument into a virtual register in the entry block,
2007 // so now we copy the value out and into %rax/%eax.
2008 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010 MachineFunction &MF = DAG.getMachineFunction();
2011 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012 unsigned Reg = FuncInfo->getSRetReturnReg();
2014 "SRetReturnReg should have been set in LowerFormalArguments().");
2015 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2018 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019 X86::RAX : X86::EAX;
2020 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021 Flag = Chain.getValue(1);
2023 // RAX/EAX now acts like a return value.
2024 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2027 RetOps[0] = Chain; // Update chain.
2029 // Add the flag if we have it.
2031 RetOps.push_back(Flag);
2033 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037 if (N->getNumValues() != 1)
2039 if (!N->hasNUsesOfValue(1, 0))
2042 SDValue TCChain = Chain;
2043 SDNode *Copy = *N->use_begin();
2044 if (Copy->getOpcode() == ISD::CopyToReg) {
2045 // If the copy has a glue operand, we conservatively assume it isn't safe to
2046 // perform a tail call.
2047 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2049 TCChain = Copy->getOperand(0);
2050 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2053 bool HasRet = false;
2054 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2056 if (UI->getOpcode() != X86ISD::RET_FLAG)
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070 ISD::NodeType ExtendKind) const {
2072 // TODO: Is this also valid on 32-bit?
2073 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074 ReturnMVT = MVT::i8;
2076 ReturnMVT = MVT::i32;
2078 MVT MinVT = getRegisterType(ReturnMVT);
2079 return VT.bitsLT(MinVT) ? MinVT : VT;
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087 CallingConv::ID CallConv, bool isVarArg,
2088 const SmallVectorImpl<ISD::InputArg> &Ins,
2089 SDLoc dl, SelectionDAG &DAG,
2090 SmallVectorImpl<SDValue> &InVals) const {
2092 // Assign locations to each value returned by this call.
2093 SmallVector<CCValAssign, 16> RVLocs;
2094 bool Is64Bit = Subtarget->is64Bit();
2095 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096 DAG.getTarget(), RVLocs, *DAG.getContext());
2097 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2099 // Copy all of the result registers out of their specified physreg.
2100 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101 CCValAssign &VA = RVLocs[i];
2102 EVT CopyVT = VA.getValVT();
2104 // If this is x86-64, and we disabled SSE, we can't return FP values
2105 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107 report_fatal_error("SSE register return with SSE disabled");
2110 // If we prefer to use the value in xmm registers, copy it out as f80 and
2111 // use a truncate to move it from fp stack reg to xmm reg.
2112 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2113 isScalarFPTypeInSSEReg(VA.getValVT()))
2116 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2117 CopyVT, InFlag).getValue(1);
2118 SDValue Val = Chain.getValue(0);
2120 if (CopyVT != VA.getValVT())
2121 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2122 // This truncation won't change the value.
2123 DAG.getIntPtrConstant(1));
2125 InFlag = Chain.getValue(2);
2126 InVals.push_back(Val);
2132 //===----------------------------------------------------------------------===//
2133 // C & StdCall & Fast Calling Convention implementation
2134 //===----------------------------------------------------------------------===//
2135 // StdCall calling convention seems to be standard for many Windows' API
2136 // routines and around. It differs from C calling convention just a little:
2137 // callee should clean up the stack, not caller. Symbols should be also
2138 // decorated in some fancy way :) It doesn't support any vector arguments.
2139 // For info on fast calling convention see Fast Calling Convention (tail call)
2140 // implementation LowerX86_32FastCCCallTo.
2142 /// CallIsStructReturn - Determines whether a call uses struct return
2144 enum StructReturnType {
2149 static StructReturnType
2150 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2152 return NotStructReturn;
2154 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2155 if (!Flags.isSRet())
2156 return NotStructReturn;
2157 if (Flags.isInReg())
2158 return RegStructReturn;
2159 return StackStructReturn;
2162 /// ArgsAreStructReturn - Determines whether a function uses struct
2163 /// return semantics.
2164 static StructReturnType
2165 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2167 return NotStructReturn;
2169 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2170 if (!Flags.isSRet())
2171 return NotStructReturn;
2172 if (Flags.isInReg())
2173 return RegStructReturn;
2174 return StackStructReturn;
2177 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2178 /// by "Src" to address "Dst" with size and alignment information specified by
2179 /// the specific parameter attribute. The copy will be passed as a byval
2180 /// function parameter.
2182 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2183 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2185 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2187 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2188 /*isVolatile*/false, /*AlwaysInline=*/true,
2189 MachinePointerInfo(), MachinePointerInfo());
2192 /// IsTailCallConvention - Return true if the calling convention is one that
2193 /// supports tail call optimization.
2194 static bool IsTailCallConvention(CallingConv::ID CC) {
2195 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2196 CC == CallingConv::HiPE);
2199 /// \brief Return true if the calling convention is a C calling convention.
2200 static bool IsCCallConvention(CallingConv::ID CC) {
2201 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2202 CC == CallingConv::X86_64_SysV);
2205 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2206 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2210 CallingConv::ID CalleeCC = CS.getCallingConv();
2211 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2217 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2218 /// a tailcall target by changing its ABI.
2219 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2220 bool GuaranteedTailCallOpt) {
2221 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2225 X86TargetLowering::LowerMemArgument(SDValue Chain,
2226 CallingConv::ID CallConv,
2227 const SmallVectorImpl<ISD::InputArg> &Ins,
2228 SDLoc dl, SelectionDAG &DAG,
2229 const CCValAssign &VA,
2230 MachineFrameInfo *MFI,
2232 // Create the nodes corresponding to a load from this parameter slot.
2233 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2234 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2235 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2236 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2239 // If value is passed by pointer we have address passed instead of the value
2241 if (VA.getLocInfo() == CCValAssign::Indirect)
2242 ValVT = VA.getLocVT();
2244 ValVT = VA.getValVT();
2246 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2247 // changed with more analysis.
2248 // In case of tail call optimization mark all arguments mutable. Since they
2249 // could be overwritten by lowering of arguments in case of a tail call.
2250 if (Flags.isByVal()) {
2251 unsigned Bytes = Flags.getByValSize();
2252 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2253 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2254 return DAG.getFrameIndex(FI, getPointerTy());
2256 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2257 VA.getLocMemOffset(), isImmutable);
2258 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2259 return DAG.getLoad(ValVT, dl, Chain, FIN,
2260 MachinePointerInfo::getFixedStack(FI),
2261 false, false, false, 0);
2266 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2267 CallingConv::ID CallConv,
2269 const SmallVectorImpl<ISD::InputArg> &Ins,
2272 SmallVectorImpl<SDValue> &InVals)
2274 MachineFunction &MF = DAG.getMachineFunction();
2275 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2277 const Function* Fn = MF.getFunction();
2278 if (Fn->hasExternalLinkage() &&
2279 Subtarget->isTargetCygMing() &&
2280 Fn->getName() == "main")
2281 FuncInfo->setForceFramePointer(true);
2283 MachineFrameInfo *MFI = MF.getFrameInfo();
2284 bool Is64Bit = Subtarget->is64Bit();
2285 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2287 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2288 "Var args not supported with calling convention fastcc, ghc or hipe");
2290 // Assign locations to all of the incoming arguments.
2291 SmallVector<CCValAssign, 16> ArgLocs;
2292 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2293 ArgLocs, *DAG.getContext());
2295 // Allocate shadow area for Win64
2297 CCInfo.AllocateStack(32, 8);
2299 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2301 unsigned LastVal = ~0U;
2303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2304 CCValAssign &VA = ArgLocs[i];
2305 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2307 assert(VA.getValNo() != LastVal &&
2308 "Don't support value assigned to multiple locs yet");
2310 LastVal = VA.getValNo();
2312 if (VA.isRegLoc()) {
2313 EVT RegVT = VA.getLocVT();
2314 const TargetRegisterClass *RC;
2315 if (RegVT == MVT::i32)
2316 RC = &X86::GR32RegClass;
2317 else if (Is64Bit && RegVT == MVT::i64)
2318 RC = &X86::GR64RegClass;
2319 else if (RegVT == MVT::f32)
2320 RC = &X86::FR32RegClass;
2321 else if (RegVT == MVT::f64)
2322 RC = &X86::FR64RegClass;
2323 else if (RegVT.is512BitVector())
2324 RC = &X86::VR512RegClass;
2325 else if (RegVT.is256BitVector())
2326 RC = &X86::VR256RegClass;
2327 else if (RegVT.is128BitVector())
2328 RC = &X86::VR128RegClass;
2329 else if (RegVT == MVT::x86mmx)
2330 RC = &X86::VR64RegClass;
2331 else if (RegVT == MVT::i1)
2332 RC = &X86::VK1RegClass;
2333 else if (RegVT == MVT::v8i1)
2334 RC = &X86::VK8RegClass;
2335 else if (RegVT == MVT::v16i1)
2336 RC = &X86::VK16RegClass;
2337 else if (RegVT == MVT::v32i1)
2338 RC = &X86::VK32RegClass;
2339 else if (RegVT == MVT::v64i1)
2340 RC = &X86::VK64RegClass;
2342 llvm_unreachable("Unknown argument type!");
2344 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2345 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2347 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2348 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2350 if (VA.getLocInfo() == CCValAssign::SExt)
2351 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2352 DAG.getValueType(VA.getValVT()));
2353 else if (VA.getLocInfo() == CCValAssign::ZExt)
2354 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2355 DAG.getValueType(VA.getValVT()));
2356 else if (VA.getLocInfo() == CCValAssign::BCvt)
2357 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2359 if (VA.isExtInLoc()) {
2360 // Handle MMX values passed in XMM regs.
2361 if (RegVT.isVector())
2362 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2364 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2367 assert(VA.isMemLoc());
2368 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2371 // If value is passed via pointer - do a load.
2372 if (VA.getLocInfo() == CCValAssign::Indirect)
2373 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2374 MachinePointerInfo(), false, false, false, 0);
2376 InVals.push_back(ArgValue);
2379 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2380 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381 // The x86-64 ABIs require that for returning structs by value we copy
2382 // the sret argument into %rax/%eax (depending on ABI) for the return.
2383 // Win32 requires us to put the sret argument to %eax as well.
2384 // Save the argument into a virtual register so that we can access it
2385 // from the return points.
2386 if (Ins[i].Flags.isSRet()) {
2387 unsigned Reg = FuncInfo->getSRetReturnReg();
2389 MVT PtrTy = getPointerTy();
2390 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2391 FuncInfo->setSRetReturnReg(Reg);
2393 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2394 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2400 unsigned StackSize = CCInfo.getNextStackOffset();
2401 // Align stack specially for tail calls.
2402 if (FuncIsMadeTailCallSafe(CallConv,
2403 MF.getTarget().Options.GuaranteedTailCallOpt))
2404 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2406 // If the function takes variable number of arguments, make a frame index for
2407 // the start of the first vararg value... for expansion of llvm.va_start.
2409 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2410 CallConv != CallingConv::X86_ThisCall)) {
2411 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2414 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2416 // FIXME: We should really autogenerate these arrays
2417 static const MCPhysReg GPR64ArgRegsWin64[] = {
2418 X86::RCX, X86::RDX, X86::R8, X86::R9
2420 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2421 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2423 static const MCPhysReg XMMArgRegs64Bit[] = {
2424 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2425 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2427 const MCPhysReg *GPR64ArgRegs;
2428 unsigned NumXMMRegs = 0;
2431 // The XMM registers which might contain var arg parameters are shadowed
2432 // in their paired GPR. So we only need to save the GPR to their home
2434 TotalNumIntRegs = 4;
2435 GPR64ArgRegs = GPR64ArgRegsWin64;
2437 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2438 GPR64ArgRegs = GPR64ArgRegs64Bit;
2440 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2443 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2446 bool NoImplicitFloatOps = Fn->getAttributes().
2447 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2448 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2449 "SSE register cannot be used when SSE is disabled!");
2450 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2451 NoImplicitFloatOps) &&
2452 "SSE register cannot be used when SSE is disabled!");
2453 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2454 !Subtarget->hasSSE1())
2455 // Kernel mode asks for SSE to be disabled, so don't push them
2457 TotalNumXMMRegs = 0;
2460 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2461 // Get to the caller-allocated home save location. Add 8 to account
2462 // for the return address.
2463 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2464 FuncInfo->setRegSaveFrameIndex(
2465 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2466 // Fixup to set vararg frame on shadow area (4 x i64).
2468 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2470 // For X86-64, if there are vararg parameters that are passed via
2471 // registers, then we must store them to their spots on the stack so
2472 // they may be loaded by deferencing the result of va_next.
2473 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2474 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2475 FuncInfo->setRegSaveFrameIndex(
2476 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2480 // Store the integer parameter registers.
2481 SmallVector<SDValue, 8> MemOps;
2482 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2484 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2485 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2486 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2487 DAG.getIntPtrConstant(Offset));
2488 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2489 &X86::GR64RegClass);
2490 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2492 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2493 MachinePointerInfo::getFixedStack(
2494 FuncInfo->getRegSaveFrameIndex(), Offset),
2496 MemOps.push_back(Store);
2500 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2501 // Now store the XMM (fp + vector) parameter registers.
2502 SmallVector<SDValue, 11> SaveXMMOps;
2503 SaveXMMOps.push_back(Chain);
2505 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2506 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2507 SaveXMMOps.push_back(ALVal);
2509 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2510 FuncInfo->getRegSaveFrameIndex()));
2511 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2512 FuncInfo->getVarArgsFPOffset()));
2514 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2515 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2516 &X86::VR128RegClass);
2517 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2518 SaveXMMOps.push_back(Val);
2520 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2521 MVT::Other, SaveXMMOps));
2524 if (!MemOps.empty())
2525 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2529 // Some CCs need callee pop.
2530 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2531 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2532 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2534 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2535 // If this is an sret function, the return should pop the hidden pointer.
2536 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2537 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2538 argsAreStructReturn(Ins) == StackStructReturn)
2539 FuncInfo->setBytesToPopOnReturn(4);
2543 // RegSaveFrameIndex is X86-64 only.
2544 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2545 if (CallConv == CallingConv::X86_FastCall ||
2546 CallConv == CallingConv::X86_ThisCall)
2547 // fastcc functions can't have varargs.
2548 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2551 FuncInfo->setArgumentStackSize(StackSize);
2557 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2558 SDValue StackPtr, SDValue Arg,
2559 SDLoc dl, SelectionDAG &DAG,
2560 const CCValAssign &VA,
2561 ISD::ArgFlagsTy Flags) const {
2562 unsigned LocMemOffset = VA.getLocMemOffset();
2563 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2564 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2565 if (Flags.isByVal())
2566 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2568 return DAG.getStore(Chain, dl, Arg, PtrOff,
2569 MachinePointerInfo::getStack(LocMemOffset),
2573 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2574 /// optimization is performed and it is required.
2576 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2577 SDValue &OutRetAddr, SDValue Chain,
2578 bool IsTailCall, bool Is64Bit,
2579 int FPDiff, SDLoc dl) const {
2580 // Adjust the Return address stack slot.
2581 EVT VT = getPointerTy();
2582 OutRetAddr = getReturnAddressFrameIndex(DAG);
2584 // Load the "old" Return address.
2585 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2586 false, false, false, 0);
2587 return SDValue(OutRetAddr.getNode(), 1);
2590 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2591 /// optimization is performed and it is required (FPDiff!=0).
2592 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2593 SDValue Chain, SDValue RetAddrFrIdx,
2594 EVT PtrVT, unsigned SlotSize,
2595 int FPDiff, SDLoc dl) {
2596 // Store the return address to the appropriate stack slot.
2597 if (!FPDiff) return Chain;
2598 // Calculate the new stack slot for the return address.
2599 int NewReturnAddrFI =
2600 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2602 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2603 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2604 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2610 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2611 SmallVectorImpl<SDValue> &InVals) const {
2612 SelectionDAG &DAG = CLI.DAG;
2614 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2615 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2616 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2617 SDValue Chain = CLI.Chain;
2618 SDValue Callee = CLI.Callee;
2619 CallingConv::ID CallConv = CLI.CallConv;
2620 bool &isTailCall = CLI.IsTailCall;
2621 bool isVarArg = CLI.IsVarArg;
2623 MachineFunction &MF = DAG.getMachineFunction();
2624 bool Is64Bit = Subtarget->is64Bit();
2625 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2626 StructReturnType SR = callIsStructReturn(Outs);
2627 bool IsSibcall = false;
2629 if (MF.getTarget().Options.DisableTailCalls)
2632 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2634 // Force this to be a tail call. The verifier rules are enough to ensure
2635 // that we can lower this successfully without moving the return address
2638 } else if (isTailCall) {
2639 // Check if it's really possible to do a tail call.
2640 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2641 isVarArg, SR != NotStructReturn,
2642 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2643 Outs, OutVals, Ins, DAG);
2645 // Sibcalls are automatically detected tailcalls which do not require
2647 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2654 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2655 "Var args not supported with calling convention fastcc, ghc or hipe");
2657 // Analyze operands of the call, assigning locations to each operand.
2658 SmallVector<CCValAssign, 16> ArgLocs;
2659 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2660 ArgLocs, *DAG.getContext());
2662 // Allocate shadow area for Win64
2664 CCInfo.AllocateStack(32, 8);
2666 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2668 // Get a count of how many bytes are to be pushed on the stack.
2669 unsigned NumBytes = CCInfo.getNextStackOffset();
2671 // This is a sibcall. The memory operands are available in caller's
2672 // own caller's stack.
2674 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2675 IsTailCallConvention(CallConv))
2676 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2679 if (isTailCall && !IsSibcall && !IsMustTail) {
2680 // Lower arguments at fp - stackoffset + fpdiff.
2681 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2682 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2684 FPDiff = NumBytesCallerPushed - NumBytes;
2686 // Set the delta of movement of the returnaddr stackslot.
2687 // But only set if delta is greater than previous delta.
2688 if (FPDiff < X86Info->getTCReturnAddrDelta())
2689 X86Info->setTCReturnAddrDelta(FPDiff);
2692 unsigned NumBytesToPush = NumBytes;
2693 unsigned NumBytesToPop = NumBytes;
2695 // If we have an inalloca argument, all stack space has already been allocated
2696 // for us and be right at the top of the stack. We don't support multiple
2697 // arguments passed in memory when using inalloca.
2698 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2700 if (!ArgLocs.back().isMemLoc())
2701 report_fatal_error("cannot use inalloca attribute on a register "
2703 if (ArgLocs.back().getLocMemOffset() != 0)
2704 report_fatal_error("any parameter with the inalloca attribute must be "
2705 "the only memory argument");
2709 Chain = DAG.getCALLSEQ_START(
2710 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2712 SDValue RetAddrFrIdx;
2713 // Load return address for tail calls.
2714 if (isTailCall && FPDiff)
2715 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2716 Is64Bit, FPDiff, dl);
2718 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2719 SmallVector<SDValue, 8> MemOpChains;
2722 // Walk the register/memloc assignments, inserting copies/loads. In the case
2723 // of tail call optimization arguments are handle later.
2724 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2725 DAG.getSubtarget().getRegisterInfo());
2726 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2727 // Skip inalloca arguments, they have already been written.
2728 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2729 if (Flags.isInAlloca())
2732 CCValAssign &VA = ArgLocs[i];
2733 EVT RegVT = VA.getLocVT();
2734 SDValue Arg = OutVals[i];
2735 bool isByVal = Flags.isByVal();
2737 // Promote the value if needed.
2738 switch (VA.getLocInfo()) {
2739 default: llvm_unreachable("Unknown loc info!");
2740 case CCValAssign::Full: break;
2741 case CCValAssign::SExt:
2742 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2744 case CCValAssign::ZExt:
2745 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2747 case CCValAssign::AExt:
2748 if (RegVT.is128BitVector()) {
2749 // Special case: passing MMX values in XMM registers.
2750 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2751 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2752 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2754 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2756 case CCValAssign::BCvt:
2757 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2759 case CCValAssign::Indirect: {
2760 // Store the argument.
2761 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2762 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2763 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2764 MachinePointerInfo::getFixedStack(FI),
2771 if (VA.isRegLoc()) {
2772 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2773 if (isVarArg && IsWin64) {
2774 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2775 // shadow reg if callee is a varargs function.
2776 unsigned ShadowReg = 0;
2777 switch (VA.getLocReg()) {
2778 case X86::XMM0: ShadowReg = X86::RCX; break;
2779 case X86::XMM1: ShadowReg = X86::RDX; break;
2780 case X86::XMM2: ShadowReg = X86::R8; break;
2781 case X86::XMM3: ShadowReg = X86::R9; break;
2784 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2786 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2787 assert(VA.isMemLoc());
2788 if (!StackPtr.getNode())
2789 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2791 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2792 dl, DAG, VA, Flags));
2796 if (!MemOpChains.empty())
2797 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2799 if (Subtarget->isPICStyleGOT()) {
2800 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2803 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2804 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2806 // If we are tail calling and generating PIC/GOT style code load the
2807 // address of the callee into ECX. The value in ecx is used as target of
2808 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2809 // for tail calls on PIC/GOT architectures. Normally we would just put the
2810 // address of GOT into ebx and then call target@PLT. But for tail calls
2811 // ebx would be restored (since ebx is callee saved) before jumping to the
2814 // Note: The actual moving to ECX is done further down.
2815 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2816 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2817 !G->getGlobal()->hasProtectedVisibility())
2818 Callee = LowerGlobalAddress(Callee, DAG);
2819 else if (isa<ExternalSymbolSDNode>(Callee))
2820 Callee = LowerExternalSymbol(Callee, DAG);
2824 if (Is64Bit && isVarArg && !IsWin64) {
2825 // From AMD64 ABI document:
2826 // For calls that may call functions that use varargs or stdargs
2827 // (prototype-less calls or calls to functions containing ellipsis (...) in
2828 // the declaration) %al is used as hidden argument to specify the number
2829 // of SSE registers used. The contents of %al do not need to match exactly
2830 // the number of registers, but must be an ubound on the number of SSE
2831 // registers used and is in the range 0 - 8 inclusive.
2833 // Count the number of XMM registers allocated.
2834 static const MCPhysReg XMMArgRegs[] = {
2835 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2836 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2838 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2839 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2840 && "SSE registers cannot be used when SSE is disabled");
2842 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2843 DAG.getConstant(NumXMMRegs, MVT::i8)));
2846 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2847 // don't need this because the eligibility check rejects calls that require
2848 // shuffling arguments passed in memory.
2849 if (!IsSibcall && isTailCall) {
2850 // Force all the incoming stack arguments to be loaded from the stack
2851 // before any new outgoing arguments are stored to the stack, because the
2852 // outgoing stack slots may alias the incoming argument stack slots, and
2853 // the alias isn't otherwise explicit. This is slightly more conservative
2854 // than necessary, because it means that each store effectively depends
2855 // on every argument instead of just those arguments it would clobber.
2856 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2858 SmallVector<SDValue, 8> MemOpChains2;
2861 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2862 CCValAssign &VA = ArgLocs[i];
2865 assert(VA.isMemLoc());
2866 SDValue Arg = OutVals[i];
2867 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2868 // Skip inalloca arguments. They don't require any work.
2869 if (Flags.isInAlloca())
2871 // Create frame index.
2872 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2873 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2874 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2875 FIN = DAG.getFrameIndex(FI, getPointerTy());
2877 if (Flags.isByVal()) {
2878 // Copy relative to framepointer.
2879 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2880 if (!StackPtr.getNode())
2881 StackPtr = DAG.getCopyFromReg(Chain, dl,
2882 RegInfo->getStackRegister(),
2884 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2886 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2890 // Store relative to framepointer.
2891 MemOpChains2.push_back(
2892 DAG.getStore(ArgChain, dl, Arg, FIN,
2893 MachinePointerInfo::getFixedStack(FI),
2898 if (!MemOpChains2.empty())
2899 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2901 // Store the return address to the appropriate stack slot.
2902 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2903 getPointerTy(), RegInfo->getSlotSize(),
2907 // Build a sequence of copy-to-reg nodes chained together with token chain
2908 // and flag operands which copy the outgoing args into registers.
2910 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2911 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2912 RegsToPass[i].second, InFlag);
2913 InFlag = Chain.getValue(1);
2916 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2917 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2918 // In the 64-bit large code model, we have to make all calls
2919 // through a register, since the call instruction's 32-bit
2920 // pc-relative offset may not be large enough to hold the whole
2922 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2923 // If the callee is a GlobalAddress node (quite common, every direct call
2924 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2927 // We should use extra load for direct calls to dllimported functions in
2929 const GlobalValue *GV = G->getGlobal();
2930 if (!GV->hasDLLImportStorageClass()) {
2931 unsigned char OpFlags = 0;
2932 bool ExtraLoad = false;
2933 unsigned WrapperKind = ISD::DELETED_NODE;
2935 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2936 // external symbols most go through the PLT in PIC mode. If the symbol
2937 // has hidden or protected visibility, or if it is static or local, then
2938 // we don't need to use the PLT - we can directly call it.
2939 if (Subtarget->isTargetELF() &&
2940 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2941 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2942 OpFlags = X86II::MO_PLT;
2943 } else if (Subtarget->isPICStyleStubAny() &&
2944 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2945 (!Subtarget->getTargetTriple().isMacOSX() ||
2946 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2947 // PC-relative references to external symbols should go through $stub,
2948 // unless we're building with the leopard linker or later, which
2949 // automatically synthesizes these stubs.
2950 OpFlags = X86II::MO_DARWIN_STUB;
2951 } else if (Subtarget->isPICStyleRIPRel() &&
2952 isa<Function>(GV) &&
2953 cast<Function>(GV)->getAttributes().
2954 hasAttribute(AttributeSet::FunctionIndex,
2955 Attribute::NonLazyBind)) {
2956 // If the function is marked as non-lazy, generate an indirect call
2957 // which loads from the GOT directly. This avoids runtime overhead
2958 // at the cost of eager binding (and one extra byte of encoding).
2959 OpFlags = X86II::MO_GOTPCREL;
2960 WrapperKind = X86ISD::WrapperRIP;
2964 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2965 G->getOffset(), OpFlags);
2967 // Add a wrapper if needed.
2968 if (WrapperKind != ISD::DELETED_NODE)
2969 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2970 // Add extra indirection if needed.
2972 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2973 MachinePointerInfo::getGOT(),
2974 false, false, false, 0);
2976 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2977 unsigned char OpFlags = 0;
2979 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2980 // external symbols should go through the PLT.
2981 if (Subtarget->isTargetELF() &&
2982 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2983 OpFlags = X86II::MO_PLT;
2984 } else if (Subtarget->isPICStyleStubAny() &&
2985 (!Subtarget->getTargetTriple().isMacOSX() ||
2986 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2987 // PC-relative references to external symbols should go through $stub,
2988 // unless we're building with the leopard linker or later, which
2989 // automatically synthesizes these stubs.
2990 OpFlags = X86II::MO_DARWIN_STUB;
2993 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2997 // Returns a chain & a flag for retval copy to use.
2998 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2999 SmallVector<SDValue, 8> Ops;
3001 if (!IsSibcall && isTailCall) {
3002 Chain = DAG.getCALLSEQ_END(Chain,
3003 DAG.getIntPtrConstant(NumBytesToPop, true),
3004 DAG.getIntPtrConstant(0, true), InFlag, dl);
3005 InFlag = Chain.getValue(1);
3008 Ops.push_back(Chain);
3009 Ops.push_back(Callee);
3012 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3014 // Add argument registers to the end of the list so that they are known live
3016 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3017 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3018 RegsToPass[i].second.getValueType()));
3020 // Add a register mask operand representing the call-preserved registers.
3021 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3022 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3023 assert(Mask && "Missing call preserved mask for calling convention");
3024 Ops.push_back(DAG.getRegisterMask(Mask));
3026 if (InFlag.getNode())
3027 Ops.push_back(InFlag);
3031 //// If this is the first return lowered for this function, add the regs
3032 //// to the liveout set for the function.
3033 // This isn't right, although it's probably harmless on x86; liveouts
3034 // should be computed from returns not tail calls. Consider a void
3035 // function making a tail call to a function returning int.
3036 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3039 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3040 InFlag = Chain.getValue(1);
3042 // Create the CALLSEQ_END node.
3043 unsigned NumBytesForCalleeToPop;
3044 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3045 DAG.getTarget().Options.GuaranteedTailCallOpt))
3046 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3047 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3048 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3049 SR == StackStructReturn)
3050 // If this is a call to a struct-return function, the callee
3051 // pops the hidden struct pointer, so we have to push it back.
3052 // This is common for Darwin/X86, Linux & Mingw32 targets.
3053 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3054 NumBytesForCalleeToPop = 4;
3056 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3058 // Returns a flag for retval copy to use.
3060 Chain = DAG.getCALLSEQ_END(Chain,
3061 DAG.getIntPtrConstant(NumBytesToPop, true),
3062 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3065 InFlag = Chain.getValue(1);
3068 // Handle result values, copying them out of physregs into vregs that we
3070 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3071 Ins, dl, DAG, InVals);
3074 //===----------------------------------------------------------------------===//
3075 // Fast Calling Convention (tail call) implementation
3076 //===----------------------------------------------------------------------===//
3078 // Like std call, callee cleans arguments, convention except that ECX is
3079 // reserved for storing the tail called function address. Only 2 registers are
3080 // free for argument passing (inreg). Tail call optimization is performed
3082 // * tailcallopt is enabled
3083 // * caller/callee are fastcc
3084 // On X86_64 architecture with GOT-style position independent code only local
3085 // (within module) calls are supported at the moment.
3086 // To keep the stack aligned according to platform abi the function
3087 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3088 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3089 // If a tail called function callee has more arguments than the caller the
3090 // caller needs to make sure that there is room to move the RETADDR to. This is
3091 // achieved by reserving an area the size of the argument delta right after the
3092 // original RETADDR, but before the saved framepointer or the spilled registers
3093 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3105 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3106 /// for a 16 byte align requirement.
3108 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3109 SelectionDAG& DAG) const {
3110 MachineFunction &MF = DAG.getMachineFunction();
3111 const TargetMachine &TM = MF.getTarget();
3112 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3113 TM.getSubtargetImpl()->getRegisterInfo());
3114 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3115 unsigned StackAlignment = TFI.getStackAlignment();
3116 uint64_t AlignMask = StackAlignment - 1;
3117 int64_t Offset = StackSize;
3118 unsigned SlotSize = RegInfo->getSlotSize();
3119 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3120 // Number smaller than 12 so just add the difference.
3121 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3123 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3124 Offset = ((~AlignMask) & Offset) + StackAlignment +
3125 (StackAlignment-SlotSize);
3130 /// MatchingStackOffset - Return true if the given stack call argument is
3131 /// already available in the same position (relatively) of the caller's
3132 /// incoming argument stack.
3134 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3135 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3136 const X86InstrInfo *TII) {
3137 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3139 if (Arg.getOpcode() == ISD::CopyFromReg) {
3140 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3141 if (!TargetRegisterInfo::isVirtualRegister(VR))
3143 MachineInstr *Def = MRI->getVRegDef(VR);
3146 if (!Flags.isByVal()) {
3147 if (!TII->isLoadFromStackSlot(Def, FI))
3150 unsigned Opcode = Def->getOpcode();
3151 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3152 Def->getOperand(1).isFI()) {
3153 FI = Def->getOperand(1).getIndex();
3154 Bytes = Flags.getByValSize();
3158 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3159 if (Flags.isByVal())
3160 // ByVal argument is passed in as a pointer but it's now being
3161 // dereferenced. e.g.
3162 // define @foo(%struct.X* %A) {
3163 // tail call @bar(%struct.X* byval %A)
3166 SDValue Ptr = Ld->getBasePtr();
3167 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3170 FI = FINode->getIndex();
3171 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3172 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3173 FI = FINode->getIndex();
3174 Bytes = Flags.getByValSize();
3178 assert(FI != INT_MAX);
3179 if (!MFI->isFixedObjectIndex(FI))
3181 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3184 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3185 /// for tail call optimization. Targets which want to do tail call
3186 /// optimization should implement this function.
3188 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3189 CallingConv::ID CalleeCC,
3191 bool isCalleeStructRet,
3192 bool isCallerStructRet,
3194 const SmallVectorImpl<ISD::OutputArg> &Outs,
3195 const SmallVectorImpl<SDValue> &OutVals,
3196 const SmallVectorImpl<ISD::InputArg> &Ins,
3197 SelectionDAG &DAG) const {
3198 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3201 // If -tailcallopt is specified, make fastcc functions tail-callable.
3202 const MachineFunction &MF = DAG.getMachineFunction();
3203 const Function *CallerF = MF.getFunction();
3205 // If the function return type is x86_fp80 and the callee return type is not,
3206 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3207 // perform a tailcall optimization here.
3208 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3211 CallingConv::ID CallerCC = CallerF->getCallingConv();
3212 bool CCMatch = CallerCC == CalleeCC;
3213 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3214 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3216 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3217 if (IsTailCallConvention(CalleeCC) && CCMatch)
3222 // Look for obvious safe cases to perform tail call optimization that do not
3223 // require ABI changes. This is what gcc calls sibcall.
3225 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3226 // emit a special epilogue.
3227 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3228 DAG.getSubtarget().getRegisterInfo());
3229 if (RegInfo->needsStackRealignment(MF))
3232 // Also avoid sibcall optimization if either caller or callee uses struct
3233 // return semantics.
3234 if (isCalleeStructRet || isCallerStructRet)
3237 // An stdcall/thiscall caller is expected to clean up its arguments; the
3238 // callee isn't going to do that.
3239 // FIXME: this is more restrictive than needed. We could produce a tailcall
3240 // when the stack adjustment matches. For example, with a thiscall that takes
3241 // only one argument.
3242 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3243 CallerCC == CallingConv::X86_ThisCall))
3246 // Do not sibcall optimize vararg calls unless all arguments are passed via
3248 if (isVarArg && !Outs.empty()) {
3250 // Optimizing for varargs on Win64 is unlikely to be safe without
3251 // additional testing.
3252 if (IsCalleeWin64 || IsCallerWin64)
3255 SmallVector<CCValAssign, 16> ArgLocs;
3256 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3257 DAG.getTarget(), ArgLocs, *DAG.getContext());
3259 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3260 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3261 if (!ArgLocs[i].isRegLoc())
3265 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3266 // stack. Therefore, if it's not used by the call it is not safe to optimize
3267 // this into a sibcall.
3268 bool Unused = false;
3269 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3276 SmallVector<CCValAssign, 16> RVLocs;
3277 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3278 DAG.getTarget(), RVLocs, *DAG.getContext());
3279 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3280 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3281 CCValAssign &VA = RVLocs[i];
3282 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3287 // If the calling conventions do not match, then we'd better make sure the
3288 // results are returned in the same way as what the caller expects.
3290 SmallVector<CCValAssign, 16> RVLocs1;
3291 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3292 DAG.getTarget(), RVLocs1, *DAG.getContext());
3293 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3295 SmallVector<CCValAssign, 16> RVLocs2;
3296 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3297 DAG.getTarget(), RVLocs2, *DAG.getContext());
3298 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3300 if (RVLocs1.size() != RVLocs2.size())
3302 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3303 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3305 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3307 if (RVLocs1[i].isRegLoc()) {
3308 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3311 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3317 // If the callee takes no arguments then go on to check the results of the
3319 if (!Outs.empty()) {
3320 // Check if stack adjustment is needed. For now, do not do this if any
3321 // argument is passed on the stack.
3322 SmallVector<CCValAssign, 16> ArgLocs;
3323 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3324 DAG.getTarget(), ArgLocs, *DAG.getContext());
3326 // Allocate shadow area for Win64
3328 CCInfo.AllocateStack(32, 8);
3330 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3331 if (CCInfo.getNextStackOffset()) {
3332 MachineFunction &MF = DAG.getMachineFunction();
3333 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3336 // Check if the arguments are already laid out in the right way as
3337 // the caller's fixed stack objects.
3338 MachineFrameInfo *MFI = MF.getFrameInfo();
3339 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3340 const X86InstrInfo *TII =
3341 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3342 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3343 CCValAssign &VA = ArgLocs[i];
3344 SDValue Arg = OutVals[i];
3345 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3346 if (VA.getLocInfo() == CCValAssign::Indirect)
3348 if (!VA.isRegLoc()) {
3349 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3356 // If the tailcall address may be in a register, then make sure it's
3357 // possible to register allocate for it. In 32-bit, the call address can
3358 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3359 // callee-saved registers are restored. These happen to be the same
3360 // registers used to pass 'inreg' arguments so watch out for those.
3361 if (!Subtarget->is64Bit() &&
3362 ((!isa<GlobalAddressSDNode>(Callee) &&
3363 !isa<ExternalSymbolSDNode>(Callee)) ||
3364 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3365 unsigned NumInRegs = 0;
3366 // In PIC we need an extra register to formulate the address computation
3368 unsigned MaxInRegs =
3369 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3371 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3372 CCValAssign &VA = ArgLocs[i];
3375 unsigned Reg = VA.getLocReg();
3378 case X86::EAX: case X86::EDX: case X86::ECX:
3379 if (++NumInRegs == MaxInRegs)
3391 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3392 const TargetLibraryInfo *libInfo) const {
3393 return X86::createFastISel(funcInfo, libInfo);
3396 //===----------------------------------------------------------------------===//
3397 // Other Lowering Hooks
3398 //===----------------------------------------------------------------------===//
3400 static bool MayFoldLoad(SDValue Op) {
3401 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3404 static bool MayFoldIntoStore(SDValue Op) {
3405 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3408 static bool isTargetShuffle(unsigned Opcode) {
3410 default: return false;
3411 case X86ISD::PSHUFB:
3412 case X86ISD::PSHUFD:
3413 case X86ISD::PSHUFHW:
3414 case X86ISD::PSHUFLW:
3416 case X86ISD::PALIGNR:
3417 case X86ISD::MOVLHPS:
3418 case X86ISD::MOVLHPD:
3419 case X86ISD::MOVHLPS:
3420 case X86ISD::MOVLPS:
3421 case X86ISD::MOVLPD:
3422 case X86ISD::MOVSHDUP:
3423 case X86ISD::MOVSLDUP:
3424 case X86ISD::MOVDDUP:
3427 case X86ISD::UNPCKL:
3428 case X86ISD::UNPCKH:
3429 case X86ISD::VPERMILP:
3430 case X86ISD::VPERM2X128:
3431 case X86ISD::VPERMI:
3436 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3437 SDValue V1, SelectionDAG &DAG) {
3439 default: llvm_unreachable("Unknown x86 shuffle node");
3440 case X86ISD::MOVSHDUP:
3441 case X86ISD::MOVSLDUP:
3442 case X86ISD::MOVDDUP:
3443 return DAG.getNode(Opc, dl, VT, V1);
3447 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3448 SDValue V1, unsigned TargetMask,
3449 SelectionDAG &DAG) {
3451 default: llvm_unreachable("Unknown x86 shuffle node");
3452 case X86ISD::PSHUFD:
3453 case X86ISD::PSHUFHW:
3454 case X86ISD::PSHUFLW:
3455 case X86ISD::VPERMILP:
3456 case X86ISD::VPERMI:
3457 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3461 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3462 SDValue V1, SDValue V2, unsigned TargetMask,
3463 SelectionDAG &DAG) {
3465 default: llvm_unreachable("Unknown x86 shuffle node");
3466 case X86ISD::PALIGNR:
3468 case X86ISD::VPERM2X128:
3469 return DAG.getNode(Opc, dl, VT, V1, V2,
3470 DAG.getConstant(TargetMask, MVT::i8));
3474 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3475 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3477 default: llvm_unreachable("Unknown x86 shuffle node");
3478 case X86ISD::MOVLHPS:
3479 case X86ISD::MOVLHPD:
3480 case X86ISD::MOVHLPS:
3481 case X86ISD::MOVLPS:
3482 case X86ISD::MOVLPD:
3485 case X86ISD::UNPCKL:
3486 case X86ISD::UNPCKH:
3487 return DAG.getNode(Opc, dl, VT, V1, V2);
3491 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3492 MachineFunction &MF = DAG.getMachineFunction();
3493 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3494 DAG.getSubtarget().getRegisterInfo());
3495 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3496 int ReturnAddrIndex = FuncInfo->getRAIndex();
3498 if (ReturnAddrIndex == 0) {
3499 // Set up a frame object for the return address.
3500 unsigned SlotSize = RegInfo->getSlotSize();
3501 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3504 FuncInfo->setRAIndex(ReturnAddrIndex);
3507 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3510 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3511 bool hasSymbolicDisplacement) {
3512 // Offset should fit into 32 bit immediate field.
3513 if (!isInt<32>(Offset))
3516 // If we don't have a symbolic displacement - we don't have any extra
3518 if (!hasSymbolicDisplacement)
3521 // FIXME: Some tweaks might be needed for medium code model.
3522 if (M != CodeModel::Small && M != CodeModel::Kernel)
3525 // For small code model we assume that latest object is 16MB before end of 31
3526 // bits boundary. We may also accept pretty large negative constants knowing
3527 // that all objects are in the positive half of address space.
3528 if (M == CodeModel::Small && Offset < 16*1024*1024)
3531 // For kernel code model we know that all object resist in the negative half
3532 // of 32bits address space. We may not accept negative offsets, since they may
3533 // be just off and we may accept pretty large positive ones.
3534 if (M == CodeModel::Kernel && Offset > 0)
3540 /// isCalleePop - Determines whether the callee is required to pop its
3541 /// own arguments. Callee pop is necessary to support tail calls.
3542 bool X86::isCalleePop(CallingConv::ID CallingConv,
3543 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3547 switch (CallingConv) {
3550 case CallingConv::X86_StdCall:
3552 case CallingConv::X86_FastCall:
3554 case CallingConv::X86_ThisCall:
3556 case CallingConv::Fast:
3558 case CallingConv::GHC:
3560 case CallingConv::HiPE:
3565 /// \brief Return true if the condition is an unsigned comparison operation.
3566 static bool isX86CCUnsigned(unsigned X86CC) {
3568 default: llvm_unreachable("Invalid integer condition!");
3569 case X86::COND_E: return true;
3570 case X86::COND_G: return false;
3571 case X86::COND_GE: return false;
3572 case X86::COND_L: return false;
3573 case X86::COND_LE: return false;
3574 case X86::COND_NE: return true;
3575 case X86::COND_B: return true;
3576 case X86::COND_A: return true;
3577 case X86::COND_BE: return true;
3578 case X86::COND_AE: return true;
3580 llvm_unreachable("covered switch fell through?!");
3583 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3584 /// specific condition code, returning the condition code and the LHS/RHS of the
3585 /// comparison to make.
3586 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3587 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3589 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3590 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3591 // X > -1 -> X == 0, jump !sign.
3592 RHS = DAG.getConstant(0, RHS.getValueType());
3593 return X86::COND_NS;
3595 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3596 // X < 0 -> X == 0, jump on sign.
3599 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3601 RHS = DAG.getConstant(0, RHS.getValueType());
3602 return X86::COND_LE;
3606 switch (SetCCOpcode) {
3607 default: llvm_unreachable("Invalid integer condition!");
3608 case ISD::SETEQ: return X86::COND_E;
3609 case ISD::SETGT: return X86::COND_G;
3610 case ISD::SETGE: return X86::COND_GE;
3611 case ISD::SETLT: return X86::COND_L;
3612 case ISD::SETLE: return X86::COND_LE;
3613 case ISD::SETNE: return X86::COND_NE;
3614 case ISD::SETULT: return X86::COND_B;
3615 case ISD::SETUGT: return X86::COND_A;
3616 case ISD::SETULE: return X86::COND_BE;
3617 case ISD::SETUGE: return X86::COND_AE;
3621 // First determine if it is required or is profitable to flip the operands.
3623 // If LHS is a foldable load, but RHS is not, flip the condition.
3624 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3625 !ISD::isNON_EXTLoad(RHS.getNode())) {
3626 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3627 std::swap(LHS, RHS);
3630 switch (SetCCOpcode) {
3636 std::swap(LHS, RHS);
3640 // On a floating point condition, the flags are set as follows:
3642 // 0 | 0 | 0 | X > Y
3643 // 0 | 0 | 1 | X < Y
3644 // 1 | 0 | 0 | X == Y
3645 // 1 | 1 | 1 | unordered
3646 switch (SetCCOpcode) {
3647 default: llvm_unreachable("Condcode should be pre-legalized away");
3649 case ISD::SETEQ: return X86::COND_E;
3650 case ISD::SETOLT: // flipped
3652 case ISD::SETGT: return X86::COND_A;
3653 case ISD::SETOLE: // flipped
3655 case ISD::SETGE: return X86::COND_AE;
3656 case ISD::SETUGT: // flipped
3658 case ISD::SETLT: return X86::COND_B;
3659 case ISD::SETUGE: // flipped
3661 case ISD::SETLE: return X86::COND_BE;
3663 case ISD::SETNE: return X86::COND_NE;
3664 case ISD::SETUO: return X86::COND_P;
3665 case ISD::SETO: return X86::COND_NP;
3667 case ISD::SETUNE: return X86::COND_INVALID;
3671 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3672 /// code. Current x86 isa includes the following FP cmov instructions:
3673 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3674 static bool hasFPCMov(unsigned X86CC) {
3690 /// isFPImmLegal - Returns true if the target can instruction select the
3691 /// specified FP immediate natively. If false, the legalizer will
3692 /// materialize the FP immediate as a load from a constant pool.
3693 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3694 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3695 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3701 /// \brief Returns true if it is beneficial to convert a load of a constant
3702 /// to just the constant itself.
3703 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3705 assert(Ty->isIntegerTy());
3707 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3708 if (BitSize == 0 || BitSize > 64)
3713 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3714 /// the specified range (L, H].
3715 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3716 return (Val < 0) || (Val >= Low && Val < Hi);
3719 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3720 /// specified value.
3721 static bool isUndefOrEqual(int Val, int CmpVal) {
3722 return (Val < 0 || Val == CmpVal);
3725 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3726 /// from position Pos and ending in Pos+Size, falls within the specified
3727 /// sequential range (L, L+Pos]. or is undef.
3728 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3729 unsigned Pos, unsigned Size, int Low) {
3730 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3731 if (!isUndefOrEqual(Mask[i], Low))
3736 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3737 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3738 /// the second operand.
3739 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3740 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3741 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3742 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3743 return (Mask[0] < 2 && Mask[1] < 2);
3747 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3748 /// is suitable for input to PSHUFHW.
3749 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3750 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3753 // Lower quadword copied in order or undef.
3754 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3757 // Upper quadword shuffled.
3758 for (unsigned i = 4; i != 8; ++i)
3759 if (!isUndefOrInRange(Mask[i], 4, 8))
3762 if (VT == MVT::v16i16) {
3763 // Lower quadword copied in order or undef.
3764 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3767 // Upper quadword shuffled.
3768 for (unsigned i = 12; i != 16; ++i)
3769 if (!isUndefOrInRange(Mask[i], 12, 16))
3776 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3777 /// is suitable for input to PSHUFLW.
3778 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3779 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3782 // Upper quadword copied in order.
3783 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3786 // Lower quadword shuffled.
3787 for (unsigned i = 0; i != 4; ++i)
3788 if (!isUndefOrInRange(Mask[i], 0, 4))
3791 if (VT == MVT::v16i16) {
3792 // Upper quadword copied in order.
3793 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3796 // Lower quadword shuffled.
3797 for (unsigned i = 8; i != 12; ++i)
3798 if (!isUndefOrInRange(Mask[i], 8, 12))
3805 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3806 /// is suitable for input to PALIGNR.
3807 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3808 const X86Subtarget *Subtarget) {
3809 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3810 (VT.is256BitVector() && !Subtarget->hasInt256()))
3813 unsigned NumElts = VT.getVectorNumElements();
3814 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3815 unsigned NumLaneElts = NumElts/NumLanes;
3817 // Do not handle 64-bit element shuffles with palignr.
3818 if (NumLaneElts == 2)
3821 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3823 for (i = 0; i != NumLaneElts; ++i) {
3828 // Lane is all undef, go to next lane
3829 if (i == NumLaneElts)
3832 int Start = Mask[i+l];
3834 // Make sure its in this lane in one of the sources
3835 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3836 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3839 // If not lane 0, then we must match lane 0
3840 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3843 // Correct second source to be contiguous with first source
3844 if (Start >= (int)NumElts)
3845 Start -= NumElts - NumLaneElts;
3847 // Make sure we're shifting in the right direction.
3848 if (Start <= (int)(i+l))
3853 // Check the rest of the elements to see if they are consecutive.
3854 for (++i; i != NumLaneElts; ++i) {
3855 int Idx = Mask[i+l];
3857 // Make sure its in this lane
3858 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3859 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3862 // If not lane 0, then we must match lane 0
3863 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3866 if (Idx >= (int)NumElts)
3867 Idx -= NumElts - NumLaneElts;
3869 if (!isUndefOrEqual(Idx, Start+i))
3878 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3879 /// the two vector operands have swapped position.
3880 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3881 unsigned NumElems) {
3882 for (unsigned i = 0; i != NumElems; ++i) {
3886 else if (idx < (int)NumElems)
3887 Mask[i] = idx + NumElems;
3889 Mask[i] = idx - NumElems;
3893 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3895 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3896 /// reverse of what x86 shuffles want.
3897 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3899 unsigned NumElems = VT.getVectorNumElements();
3900 unsigned NumLanes = VT.getSizeInBits()/128;
3901 unsigned NumLaneElems = NumElems/NumLanes;
3903 if (NumLaneElems != 2 && NumLaneElems != 4)
3906 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3907 bool symetricMaskRequired =
3908 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3910 // VSHUFPSY divides the resulting vector into 4 chunks.
3911 // The sources are also splitted into 4 chunks, and each destination
3912 // chunk must come from a different source chunk.
3914 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3915 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3917 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3918 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3920 // VSHUFPDY divides the resulting vector into 4 chunks.
3921 // The sources are also splitted into 4 chunks, and each destination
3922 // chunk must come from a different source chunk.
3924 // SRC1 => X3 X2 X1 X0
3925 // SRC2 => Y3 Y2 Y1 Y0
3927 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3929 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3930 unsigned HalfLaneElems = NumLaneElems/2;
3931 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3932 for (unsigned i = 0; i != NumLaneElems; ++i) {
3933 int Idx = Mask[i+l];
3934 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3935 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3937 // For VSHUFPSY, the mask of the second half must be the same as the
3938 // first but with the appropriate offsets. This works in the same way as
3939 // VPERMILPS works with masks.
3940 if (!symetricMaskRequired || Idx < 0)
3942 if (MaskVal[i] < 0) {
3943 MaskVal[i] = Idx - l;
3946 if ((signed)(Idx - l) != MaskVal[i])
3954 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3955 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3956 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3957 if (!VT.is128BitVector())
3960 unsigned NumElems = VT.getVectorNumElements();
3965 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3966 return isUndefOrEqual(Mask[0], 6) &&
3967 isUndefOrEqual(Mask[1], 7) &&
3968 isUndefOrEqual(Mask[2], 2) &&
3969 isUndefOrEqual(Mask[3], 3);
3972 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3973 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3975 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3976 if (!VT.is128BitVector())
3979 unsigned NumElems = VT.getVectorNumElements();
3984 return isUndefOrEqual(Mask[0], 2) &&
3985 isUndefOrEqual(Mask[1], 3) &&
3986 isUndefOrEqual(Mask[2], 2) &&
3987 isUndefOrEqual(Mask[3], 3);
3990 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3991 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3992 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3993 if (!VT.is128BitVector())
3996 unsigned NumElems = VT.getVectorNumElements();
3998 if (NumElems != 2 && NumElems != 4)
4001 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4002 if (!isUndefOrEqual(Mask[i], i + NumElems))
4005 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4006 if (!isUndefOrEqual(Mask[i], i))
4012 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4013 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4014 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4015 if (!VT.is128BitVector())
4018 unsigned NumElems = VT.getVectorNumElements();
4020 if (NumElems != 2 && NumElems != 4)
4023 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4024 if (!isUndefOrEqual(Mask[i], i))
4027 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4028 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4034 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4035 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4036 /// i. e: If all but one element come from the same vector.
4037 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4038 // TODO: Deal with AVX's VINSERTPS
4039 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4042 unsigned CorrectPosV1 = 0;
4043 unsigned CorrectPosV2 = 0;
4044 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4045 if (Mask[i] == -1) {
4053 else if (Mask[i] == i + 4)
4057 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4058 // We have 3 elements (undefs count as elements from any vector) from one
4059 // vector, and one from another.
4066 // Some special combinations that can be optimized.
4069 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4070 SelectionDAG &DAG) {
4071 MVT VT = SVOp->getSimpleValueType(0);
4074 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4077 ArrayRef<int> Mask = SVOp->getMask();
4079 // These are the special masks that may be optimized.
4080 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4081 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4082 bool MatchEvenMask = true;
4083 bool MatchOddMask = true;
4084 for (int i=0; i<8; ++i) {
4085 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4086 MatchEvenMask = false;
4087 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4088 MatchOddMask = false;
4091 if (!MatchEvenMask && !MatchOddMask)
4094 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4096 SDValue Op0 = SVOp->getOperand(0);
4097 SDValue Op1 = SVOp->getOperand(1);
4099 if (MatchEvenMask) {
4100 // Shift the second operand right to 32 bits.
4101 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4102 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4104 // Shift the first operand left to 32 bits.
4105 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4106 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4108 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4109 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4112 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4113 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4114 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4115 bool HasInt256, bool V2IsSplat = false) {
4117 assert(VT.getSizeInBits() >= 128 &&
4118 "Unsupported vector type for unpckl");
4120 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4122 unsigned NumOf256BitLanes;
4123 unsigned NumElts = VT.getVectorNumElements();
4124 if (VT.is256BitVector()) {
4125 if (NumElts != 4 && NumElts != 8 &&
4126 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4129 NumOf256BitLanes = 1;
4130 } else if (VT.is512BitVector()) {
4131 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4132 "Unsupported vector type for unpckh");
4134 NumOf256BitLanes = 2;
4137 NumOf256BitLanes = 1;
4140 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4141 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4143 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4144 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4145 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4146 int BitI = Mask[l256*NumEltsInStride+l+i];
4147 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4148 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4150 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4152 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4160 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4161 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4162 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4163 bool HasInt256, bool V2IsSplat = false) {
4164 assert(VT.getSizeInBits() >= 128 &&
4165 "Unsupported vector type for unpckh");
4167 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4169 unsigned NumOf256BitLanes;
4170 unsigned NumElts = VT.getVectorNumElements();
4171 if (VT.is256BitVector()) {
4172 if (NumElts != 4 && NumElts != 8 &&
4173 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4176 NumOf256BitLanes = 1;
4177 } else if (VT.is512BitVector()) {
4178 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4179 "Unsupported vector type for unpckh");
4181 NumOf256BitLanes = 2;
4184 NumOf256BitLanes = 1;
4187 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4188 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4190 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4191 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4192 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4193 int BitI = Mask[l256*NumEltsInStride+l+i];
4194 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4195 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4197 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4199 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4207 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4208 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4210 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4211 unsigned NumElts = VT.getVectorNumElements();
4212 bool Is256BitVec = VT.is256BitVector();
4214 if (VT.is512BitVector())
4216 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4217 "Unsupported vector type for unpckh");
4219 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4220 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4223 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4224 // FIXME: Need a better way to get rid of this, there's no latency difference
4225 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4226 // the former later. We should also remove the "_undef" special mask.
4227 if (NumElts == 4 && Is256BitVec)
4230 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4231 // independently on 128-bit lanes.
4232 unsigned NumLanes = VT.getSizeInBits()/128;
4233 unsigned NumLaneElts = NumElts/NumLanes;
4235 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4236 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4237 int BitI = Mask[l+i];
4238 int BitI1 = Mask[l+i+1];
4240 if (!isUndefOrEqual(BitI, j))
4242 if (!isUndefOrEqual(BitI1, j))
4250 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4251 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4253 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4254 unsigned NumElts = VT.getVectorNumElements();
4256 if (VT.is512BitVector())
4259 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4260 "Unsupported vector type for unpckh");
4262 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4263 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4266 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4267 // independently on 128-bit lanes.
4268 unsigned NumLanes = VT.getSizeInBits()/128;
4269 unsigned NumLaneElts = NumElts/NumLanes;
4271 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4272 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4273 int BitI = Mask[l+i];
4274 int BitI1 = Mask[l+i+1];
4275 if (!isUndefOrEqual(BitI, j))
4277 if (!isUndefOrEqual(BitI1, j))
4284 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4285 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4286 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4287 if (!VT.is512BitVector())
4290 unsigned NumElts = VT.getVectorNumElements();
4291 unsigned HalfSize = NumElts/2;
4292 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4293 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4298 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4299 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4307 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4308 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4309 /// MOVSD, and MOVD, i.e. setting the lowest element.
4310 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4311 if (VT.getVectorElementType().getSizeInBits() < 32)
4313 if (!VT.is128BitVector())
4316 unsigned NumElts = VT.getVectorNumElements();
4318 if (!isUndefOrEqual(Mask[0], NumElts))
4321 for (unsigned i = 1; i != NumElts; ++i)
4322 if (!isUndefOrEqual(Mask[i], i))
4328 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4329 /// as permutations between 128-bit chunks or halves. As an example: this
4331 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4332 /// The first half comes from the second half of V1 and the second half from the
4333 /// the second half of V2.
4334 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4335 if (!HasFp256 || !VT.is256BitVector())
4338 // The shuffle result is divided into half A and half B. In total the two
4339 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4340 // B must come from C, D, E or F.
4341 unsigned HalfSize = VT.getVectorNumElements()/2;
4342 bool MatchA = false, MatchB = false;
4344 // Check if A comes from one of C, D, E, F.
4345 for (unsigned Half = 0; Half != 4; ++Half) {
4346 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4352 // Check if B comes from one of C, D, E, F.
4353 for (unsigned Half = 0; Half != 4; ++Half) {
4354 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4360 return MatchA && MatchB;
4363 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4364 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4365 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4366 MVT VT = SVOp->getSimpleValueType(0);
4368 unsigned HalfSize = VT.getVectorNumElements()/2;
4370 unsigned FstHalf = 0, SndHalf = 0;
4371 for (unsigned i = 0; i < HalfSize; ++i) {
4372 if (SVOp->getMaskElt(i) > 0) {
4373 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4377 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4378 if (SVOp->getMaskElt(i) > 0) {
4379 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4384 return (FstHalf | (SndHalf << 4));
4387 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4388 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4389 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4393 unsigned NumElts = VT.getVectorNumElements();
4395 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4396 for (unsigned i = 0; i != NumElts; ++i) {
4399 Imm8 |= Mask[i] << (i*2);
4404 unsigned LaneSize = 4;
4405 SmallVector<int, 4> MaskVal(LaneSize, -1);
4407 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4408 for (unsigned i = 0; i != LaneSize; ++i) {
4409 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4413 if (MaskVal[i] < 0) {
4414 MaskVal[i] = Mask[i+l] - l;
4415 Imm8 |= MaskVal[i] << (i*2);
4418 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4425 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4426 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4427 /// Note that VPERMIL mask matching is different depending whether theunderlying
4428 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4429 /// to the same elements of the low, but to the higher half of the source.
4430 /// In VPERMILPD the two lanes could be shuffled independently of each other
4431 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4432 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4433 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4434 if (VT.getSizeInBits() < 256 || EltSize < 32)
4436 bool symetricMaskRequired = (EltSize == 32);
4437 unsigned NumElts = VT.getVectorNumElements();
4439 unsigned NumLanes = VT.getSizeInBits()/128;
4440 unsigned LaneSize = NumElts/NumLanes;
4441 // 2 or 4 elements in one lane
4443 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4444 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4445 for (unsigned i = 0; i != LaneSize; ++i) {
4446 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4448 if (symetricMaskRequired) {
4449 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4450 ExpectedMaskVal[i] = Mask[i+l] - l;
4453 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4461 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4462 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4463 /// element of vector 2 and the other elements to come from vector 1 in order.
4464 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4465 bool V2IsSplat = false, bool V2IsUndef = false) {
4466 if (!VT.is128BitVector())
4469 unsigned NumOps = VT.getVectorNumElements();
4470 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4473 if (!isUndefOrEqual(Mask[0], 0))
4476 for (unsigned i = 1; i != NumOps; ++i)
4477 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4478 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4479 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4485 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4486 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4487 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4488 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4489 const X86Subtarget *Subtarget) {
4490 if (!Subtarget->hasSSE3())
4493 unsigned NumElems = VT.getVectorNumElements();
4495 if ((VT.is128BitVector() && NumElems != 4) ||
4496 (VT.is256BitVector() && NumElems != 8) ||
4497 (VT.is512BitVector() && NumElems != 16))
4500 // "i+1" is the value the indexed mask element must have
4501 for (unsigned i = 0; i != NumElems; i += 2)
4502 if (!isUndefOrEqual(Mask[i], i+1) ||
4503 !isUndefOrEqual(Mask[i+1], i+1))
4509 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4510 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4511 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4512 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4513 const X86Subtarget *Subtarget) {
4514 if (!Subtarget->hasSSE3())
4517 unsigned NumElems = VT.getVectorNumElements();
4519 if ((VT.is128BitVector() && NumElems != 4) ||
4520 (VT.is256BitVector() && NumElems != 8) ||
4521 (VT.is512BitVector() && NumElems != 16))
4524 // "i" is the value the indexed mask element must have
4525 for (unsigned i = 0; i != NumElems; i += 2)
4526 if (!isUndefOrEqual(Mask[i], i) ||
4527 !isUndefOrEqual(Mask[i+1], i))
4533 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4534 /// specifies a shuffle of elements that is suitable for input to 256-bit
4535 /// version of MOVDDUP.
4536 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4537 if (!HasFp256 || !VT.is256BitVector())
4540 unsigned NumElts = VT.getVectorNumElements();
4544 for (unsigned i = 0; i != NumElts/2; ++i)
4545 if (!isUndefOrEqual(Mask[i], 0))
4547 for (unsigned i = NumElts/2; i != NumElts; ++i)
4548 if (!isUndefOrEqual(Mask[i], NumElts/2))
4553 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4554 /// specifies a shuffle of elements that is suitable for input to 128-bit
4555 /// version of MOVDDUP.
4556 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4557 if (!VT.is128BitVector())
4560 unsigned e = VT.getVectorNumElements() / 2;
4561 for (unsigned i = 0; i != e; ++i)
4562 if (!isUndefOrEqual(Mask[i], i))
4564 for (unsigned i = 0; i != e; ++i)
4565 if (!isUndefOrEqual(Mask[e+i], i))
4570 /// isVEXTRACTIndex - Return true if the specified
4571 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4572 /// suitable for instruction that extract 128 or 256 bit vectors
4573 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4574 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4575 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4578 // The index should be aligned on a vecWidth-bit boundary.
4580 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4582 MVT VT = N->getSimpleValueType(0);
4583 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4584 bool Result = (Index * ElSize) % vecWidth == 0;
4589 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4590 /// operand specifies a subvector insert that is suitable for input to
4591 /// insertion of 128 or 256-bit subvectors
4592 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4593 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4594 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4596 // The index should be aligned on a vecWidth-bit boundary.
4598 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4600 MVT VT = N->getSimpleValueType(0);
4601 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4602 bool Result = (Index * ElSize) % vecWidth == 0;
4607 bool X86::isVINSERT128Index(SDNode *N) {
4608 return isVINSERTIndex(N, 128);
4611 bool X86::isVINSERT256Index(SDNode *N) {
4612 return isVINSERTIndex(N, 256);
4615 bool X86::isVEXTRACT128Index(SDNode *N) {
4616 return isVEXTRACTIndex(N, 128);
4619 bool X86::isVEXTRACT256Index(SDNode *N) {
4620 return isVEXTRACTIndex(N, 256);
4623 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4624 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4625 /// Handles 128-bit and 256-bit.
4626 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4627 MVT VT = N->getSimpleValueType(0);
4629 assert((VT.getSizeInBits() >= 128) &&
4630 "Unsupported vector type for PSHUF/SHUFP");
4632 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4633 // independently on 128-bit lanes.
4634 unsigned NumElts = VT.getVectorNumElements();
4635 unsigned NumLanes = VT.getSizeInBits()/128;
4636 unsigned NumLaneElts = NumElts/NumLanes;
4638 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4639 "Only supports 2, 4 or 8 elements per lane");
4641 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4643 for (unsigned i = 0; i != NumElts; ++i) {
4644 int Elt = N->getMaskElt(i);
4645 if (Elt < 0) continue;
4646 Elt &= NumLaneElts - 1;
4647 unsigned ShAmt = (i << Shift) % 8;
4648 Mask |= Elt << ShAmt;
4654 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4655 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4656 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4657 MVT VT = N->getSimpleValueType(0);
4659 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4660 "Unsupported vector type for PSHUFHW");
4662 unsigned NumElts = VT.getVectorNumElements();
4665 for (unsigned l = 0; l != NumElts; l += 8) {
4666 // 8 nodes per lane, but we only care about the last 4.
4667 for (unsigned i = 0; i < 4; ++i) {
4668 int Elt = N->getMaskElt(l+i+4);
4669 if (Elt < 0) continue;
4670 Elt &= 0x3; // only 2-bits.
4671 Mask |= Elt << (i * 2);
4678 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4679 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4680 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4681 MVT VT = N->getSimpleValueType(0);
4683 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4684 "Unsupported vector type for PSHUFHW");
4686 unsigned NumElts = VT.getVectorNumElements();
4689 for (unsigned l = 0; l != NumElts; l += 8) {
4690 // 8 nodes per lane, but we only care about the first 4.
4691 for (unsigned i = 0; i < 4; ++i) {
4692 int Elt = N->getMaskElt(l+i);
4693 if (Elt < 0) continue;
4694 Elt &= 0x3; // only 2-bits
4695 Mask |= Elt << (i * 2);
4702 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4703 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4704 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4705 MVT VT = SVOp->getSimpleValueType(0);
4706 unsigned EltSize = VT.is512BitVector() ? 1 :
4707 VT.getVectorElementType().getSizeInBits() >> 3;
4709 unsigned NumElts = VT.getVectorNumElements();
4710 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4711 unsigned NumLaneElts = NumElts/NumLanes;
4715 for (i = 0; i != NumElts; ++i) {
4716 Val = SVOp->getMaskElt(i);
4720 if (Val >= (int)NumElts)
4721 Val -= NumElts - NumLaneElts;
4723 assert(Val - i > 0 && "PALIGNR imm should be positive");
4724 return (Val - i) * EltSize;
4727 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4728 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4729 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4730 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4733 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4735 MVT VecVT = N->getOperand(0).getSimpleValueType();
4736 MVT ElVT = VecVT.getVectorElementType();
4738 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4739 return Index / NumElemsPerChunk;
4742 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4743 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4744 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4745 llvm_unreachable("Illegal insert subvector for VINSERT");
4748 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4750 MVT VecVT = N->getSimpleValueType(0);
4751 MVT ElVT = VecVT.getVectorElementType();
4753 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4754 return Index / NumElemsPerChunk;
4757 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4758 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4759 /// and VINSERTI128 instructions.
4760 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4761 return getExtractVEXTRACTImmediate(N, 128);
4764 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4765 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4766 /// and VINSERTI64x4 instructions.
4767 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4768 return getExtractVEXTRACTImmediate(N, 256);
4771 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4772 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4773 /// and VINSERTI128 instructions.
4774 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4775 return getInsertVINSERTImmediate(N, 128);
4778 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4779 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4780 /// and VINSERTI64x4 instructions.
4781 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4782 return getInsertVINSERTImmediate(N, 256);
4785 /// isZero - Returns true if Elt is a constant integer zero
4786 static bool isZero(SDValue V) {
4787 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4788 return C && C->isNullValue();
4791 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4793 bool X86::isZeroNode(SDValue Elt) {
4796 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4797 return CFP->getValueAPF().isPosZero();
4801 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4802 /// match movhlps. The lower half elements should come from upper half of
4803 /// V1 (and in order), and the upper half elements should come from the upper
4804 /// half of V2 (and in order).
4805 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4806 if (!VT.is128BitVector())
4808 if (VT.getVectorNumElements() != 4)
4810 for (unsigned i = 0, e = 2; i != e; ++i)
4811 if (!isUndefOrEqual(Mask[i], i+2))
4813 for (unsigned i = 2; i != 4; ++i)
4814 if (!isUndefOrEqual(Mask[i], i+4))
4819 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4820 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4822 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4823 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4825 N = N->getOperand(0).getNode();
4826 if (!ISD::isNON_EXTLoad(N))
4829 *LD = cast<LoadSDNode>(N);
4833 // Test whether the given value is a vector value which will be legalized
4835 static bool WillBeConstantPoolLoad(SDNode *N) {
4836 if (N->getOpcode() != ISD::BUILD_VECTOR)
4839 // Check for any non-constant elements.
4840 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4841 switch (N->getOperand(i).getNode()->getOpcode()) {
4843 case ISD::ConstantFP:
4850 // Vectors of all-zeros and all-ones are materialized with special
4851 // instructions rather than being loaded.
4852 return !ISD::isBuildVectorAllZeros(N) &&
4853 !ISD::isBuildVectorAllOnes(N);
4856 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4857 /// match movlp{s|d}. The lower half elements should come from lower half of
4858 /// V1 (and in order), and the upper half elements should come from the upper
4859 /// half of V2 (and in order). And since V1 will become the source of the
4860 /// MOVLP, it must be either a vector load or a scalar load to vector.
4861 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4862 ArrayRef<int> Mask, MVT VT) {
4863 if (!VT.is128BitVector())
4866 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4868 // Is V2 is a vector load, don't do this transformation. We will try to use
4869 // load folding shufps op.
4870 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4873 unsigned NumElems = VT.getVectorNumElements();
4875 if (NumElems != 2 && NumElems != 4)
4877 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4878 if (!isUndefOrEqual(Mask[i], i))
4880 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4881 if (!isUndefOrEqual(Mask[i], i+NumElems))
4886 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4887 /// to an zero vector.
4888 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4889 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4890 SDValue V1 = N->getOperand(0);
4891 SDValue V2 = N->getOperand(1);
4892 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4893 for (unsigned i = 0; i != NumElems; ++i) {
4894 int Idx = N->getMaskElt(i);
4895 if (Idx >= (int)NumElems) {
4896 unsigned Opc = V2.getOpcode();
4897 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4899 if (Opc != ISD::BUILD_VECTOR ||
4900 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4902 } else if (Idx >= 0) {
4903 unsigned Opc = V1.getOpcode();
4904 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4906 if (Opc != ISD::BUILD_VECTOR ||
4907 !X86::isZeroNode(V1.getOperand(Idx)))
4914 /// getZeroVector - Returns a vector of specified type with all zero elements.
4916 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4917 SelectionDAG &DAG, SDLoc dl) {
4918 assert(VT.isVector() && "Expected a vector type");
4920 // Always build SSE zero vectors as <4 x i32> bitcasted
4921 // to their dest type. This ensures they get CSE'd.
4923 if (VT.is128BitVector()) { // SSE
4924 if (Subtarget->hasSSE2()) { // SSE2
4925 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4926 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4928 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4929 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4931 } else if (VT.is256BitVector()) { // AVX
4932 if (Subtarget->hasInt256()) { // AVX2
4933 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4934 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4935 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4937 // 256-bit logic and arithmetic instructions in AVX are all
4938 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4939 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4940 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4941 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4943 } else if (VT.is512BitVector()) { // AVX-512
4944 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4945 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4946 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4947 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4948 } else if (VT.getScalarType() == MVT::i1) {
4949 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4950 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4951 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4952 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4954 llvm_unreachable("Unexpected vector type");
4956 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4959 /// getOnesVector - Returns a vector of specified type with all bits set.
4960 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4961 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4962 /// Then bitcast to their original type, ensuring they get CSE'd.
4963 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4965 assert(VT.isVector() && "Expected a vector type");
4967 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4969 if (VT.is256BitVector()) {
4970 if (HasInt256) { // AVX2
4971 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4972 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4974 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4975 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4977 } else if (VT.is128BitVector()) {
4978 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4980 llvm_unreachable("Unexpected vector type");
4982 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4985 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4986 /// that point to V2 points to its first element.
4987 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4988 for (unsigned i = 0; i != NumElems; ++i) {
4989 if (Mask[i] > (int)NumElems) {
4995 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4996 /// operation of specified width.
4997 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4999 unsigned NumElems = VT.getVectorNumElements();
5000 SmallVector<int, 8> Mask;
5001 Mask.push_back(NumElems);
5002 for (unsigned i = 1; i != NumElems; ++i)
5004 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5007 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5008 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5010 unsigned NumElems = VT.getVectorNumElements();
5011 SmallVector<int, 8> Mask;
5012 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5014 Mask.push_back(i + NumElems);
5016 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5019 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5020 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5022 unsigned NumElems = VT.getVectorNumElements();
5023 SmallVector<int, 8> Mask;
5024 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5025 Mask.push_back(i + Half);
5026 Mask.push_back(i + NumElems + Half);
5028 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5031 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5032 // a generic shuffle instruction because the target has no such instructions.
5033 // Generate shuffles which repeat i16 and i8 several times until they can be
5034 // represented by v4f32 and then be manipulated by target suported shuffles.
5035 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5036 MVT VT = V.getSimpleValueType();
5037 int NumElems = VT.getVectorNumElements();
5040 while (NumElems > 4) {
5041 if (EltNo < NumElems/2) {
5042 V = getUnpackl(DAG, dl, VT, V, V);
5044 V = getUnpackh(DAG, dl, VT, V, V);
5045 EltNo -= NumElems/2;
5052 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5053 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5054 MVT VT = V.getSimpleValueType();
5057 if (VT.is128BitVector()) {
5058 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5059 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5060 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5062 } else if (VT.is256BitVector()) {
5063 // To use VPERMILPS to splat scalars, the second half of indicies must
5064 // refer to the higher part, which is a duplication of the lower one,
5065 // because VPERMILPS can only handle in-lane permutations.
5066 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5067 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5069 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5070 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5073 llvm_unreachable("Vector size not supported");
5075 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5078 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5079 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5080 MVT SrcVT = SV->getSimpleValueType(0);
5081 SDValue V1 = SV->getOperand(0);
5084 int EltNo = SV->getSplatIndex();
5085 int NumElems = SrcVT.getVectorNumElements();
5086 bool Is256BitVec = SrcVT.is256BitVector();
5088 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5089 "Unknown how to promote splat for type");
5091 // Extract the 128-bit part containing the splat element and update
5092 // the splat element index when it refers to the higher register.
5094 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5095 if (EltNo >= NumElems/2)
5096 EltNo -= NumElems/2;
5099 // All i16 and i8 vector types can't be used directly by a generic shuffle
5100 // instruction because the target has no such instruction. Generate shuffles
5101 // which repeat i16 and i8 several times until they fit in i32, and then can
5102 // be manipulated by target suported shuffles.
5103 MVT EltVT = SrcVT.getVectorElementType();
5104 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5105 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5107 // Recreate the 256-bit vector and place the same 128-bit vector
5108 // into the low and high part. This is necessary because we want
5109 // to use VPERM* to shuffle the vectors
5111 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5114 return getLegalSplat(DAG, V1, EltNo);
5117 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5118 /// vector of zero or undef vector. This produces a shuffle where the low
5119 /// element of V2 is swizzled into the zero/undef vector, landing at element
5120 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5121 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5123 const X86Subtarget *Subtarget,
5124 SelectionDAG &DAG) {
5125 MVT VT = V2.getSimpleValueType();
5127 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5128 unsigned NumElems = VT.getVectorNumElements();
5129 SmallVector<int, 16> MaskVec;
5130 for (unsigned i = 0; i != NumElems; ++i)
5131 // If this is the insertion idx, put the low elt of V2 here.
5132 MaskVec.push_back(i == Idx ? NumElems : i);
5133 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5136 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5137 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5138 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5139 /// shuffles which use a single input multiple times, and in those cases it will
5140 /// adjust the mask to only have indices within that single input.
5141 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5142 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5143 unsigned NumElems = VT.getVectorNumElements();
5147 bool IsFakeUnary = false;
5148 switch(N->getOpcode()) {
5150 ImmN = N->getOperand(N->getNumOperands()-1);
5151 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5154 case X86ISD::UNPCKH:
5155 DecodeUNPCKHMask(VT, Mask);
5156 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5158 case X86ISD::UNPCKL:
5159 DecodeUNPCKLMask(VT, Mask);
5160 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5162 case X86ISD::MOVHLPS:
5163 DecodeMOVHLPSMask(NumElems, Mask);
5164 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5166 case X86ISD::MOVLHPS:
5167 DecodeMOVLHPSMask(NumElems, Mask);
5168 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5170 case X86ISD::PALIGNR:
5171 ImmN = N->getOperand(N->getNumOperands()-1);
5172 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5174 case X86ISD::PSHUFD:
5175 case X86ISD::VPERMILP:
5176 ImmN = N->getOperand(N->getNumOperands()-1);
5177 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180 case X86ISD::PSHUFHW:
5181 ImmN = N->getOperand(N->getNumOperands()-1);
5182 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5185 case X86ISD::PSHUFLW:
5186 ImmN = N->getOperand(N->getNumOperands()-1);
5187 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5190 case X86ISD::PSHUFB: {
5192 SDValue MaskNode = N->getOperand(1);
5193 while (MaskNode->getOpcode() == ISD::BITCAST)
5194 MaskNode = MaskNode->getOperand(0);
5196 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5197 // If we have a build-vector, then things are easy.
5198 EVT VT = MaskNode.getValueType();
5199 assert(VT.isVector() &&
5200 "Can't produce a non-vector with a build_vector!");
5201 if (!VT.isInteger())
5204 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5206 SmallVector<uint64_t, 32> RawMask;
5207 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5208 auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5211 APInt MaskElement = CN->getAPIntValue();
5213 // We now have to decode the element which could be any integer size and
5214 // extract each byte of it.
5215 for (int j = 0; j < NumBytesPerElement; ++j) {
5216 // Note that this is x86 and so always little endian: the low byte is
5217 // the first byte of the mask.
5218 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5219 MaskElement = MaskElement.lshr(8);
5222 DecodePSHUFBMask(RawMask, Mask);
5226 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5230 SDValue Ptr = MaskLoad->getBasePtr();
5231 if (Ptr->getOpcode() == X86ISD::Wrapper)
5232 Ptr = Ptr->getOperand(0);
5234 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5235 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5238 if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5239 // FIXME: Support AVX-512 here.
5240 if (!C->getType()->isVectorTy() ||
5241 (C->getNumElements() != 16 && C->getNumElements() != 32))
5244 assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5245 DecodePSHUFBMask(C, Mask);
5251 case X86ISD::VPERMI:
5252 ImmN = N->getOperand(N->getNumOperands()-1);
5253 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5257 case X86ISD::MOVSD: {
5258 // The index 0 always comes from the first element of the second source,
5259 // this is why MOVSS and MOVSD are used in the first place. The other
5260 // elements come from the other positions of the first source vector
5261 Mask.push_back(NumElems);
5262 for (unsigned i = 1; i != NumElems; ++i) {
5267 case X86ISD::VPERM2X128:
5268 ImmN = N->getOperand(N->getNumOperands()-1);
5269 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5270 if (Mask.empty()) return false;
5272 case X86ISD::MOVDDUP:
5273 case X86ISD::MOVLHPD:
5274 case X86ISD::MOVLPD:
5275 case X86ISD::MOVLPS:
5276 case X86ISD::MOVSHDUP:
5277 case X86ISD::MOVSLDUP:
5278 // Not yet implemented
5280 default: llvm_unreachable("unknown target shuffle node");
5283 // If we have a fake unary shuffle, the shuffle mask is spread across two
5284 // inputs that are actually the same node. Re-map the mask to always point
5285 // into the first input.
5288 if (M >= (int)Mask.size())
5294 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5295 /// element of the result of the vector shuffle.
5296 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5299 return SDValue(); // Limit search depth.
5301 SDValue V = SDValue(N, 0);
5302 EVT VT = V.getValueType();
5303 unsigned Opcode = V.getOpcode();
5305 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5306 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5307 int Elt = SV->getMaskElt(Index);
5310 return DAG.getUNDEF(VT.getVectorElementType());
5312 unsigned NumElems = VT.getVectorNumElements();
5313 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5314 : SV->getOperand(1);
5315 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5318 // Recurse into target specific vector shuffles to find scalars.
5319 if (isTargetShuffle(Opcode)) {
5320 MVT ShufVT = V.getSimpleValueType();
5321 unsigned NumElems = ShufVT.getVectorNumElements();
5322 SmallVector<int, 16> ShuffleMask;
5325 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5328 int Elt = ShuffleMask[Index];
5330 return DAG.getUNDEF(ShufVT.getVectorElementType());
5332 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5334 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5338 // Actual nodes that may contain scalar elements
5339 if (Opcode == ISD::BITCAST) {
5340 V = V.getOperand(0);
5341 EVT SrcVT = V.getValueType();
5342 unsigned NumElems = VT.getVectorNumElements();
5344 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5348 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5349 return (Index == 0) ? V.getOperand(0)
5350 : DAG.getUNDEF(VT.getVectorElementType());
5352 if (V.getOpcode() == ISD::BUILD_VECTOR)
5353 return V.getOperand(Index);
5358 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5359 /// shuffle operation which come from a consecutively from a zero. The
5360 /// search can start in two different directions, from left or right.
5361 /// We count undefs as zeros until PreferredNum is reached.
5362 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5363 unsigned NumElems, bool ZerosFromLeft,
5365 unsigned PreferredNum = -1U) {
5366 unsigned NumZeros = 0;
5367 for (unsigned i = 0; i != NumElems; ++i) {
5368 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5369 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5373 if (X86::isZeroNode(Elt))
5375 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5376 NumZeros = std::min(NumZeros + 1, PreferredNum);
5384 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5385 /// correspond consecutively to elements from one of the vector operands,
5386 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5388 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5389 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5390 unsigned NumElems, unsigned &OpNum) {
5391 bool SeenV1 = false;
5392 bool SeenV2 = false;
5394 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5395 int Idx = SVOp->getMaskElt(i);
5396 // Ignore undef indicies
5400 if (Idx < (int)NumElems)
5405 // Only accept consecutive elements from the same vector
5406 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5410 OpNum = SeenV1 ? 0 : 1;
5414 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5415 /// logical left shift of a vector.
5416 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5417 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5419 SVOp->getSimpleValueType(0).getVectorNumElements();
5420 unsigned NumZeros = getNumOfConsecutiveZeros(
5421 SVOp, NumElems, false /* check zeros from right */, DAG,
5422 SVOp->getMaskElt(0));
5428 // Considering the elements in the mask that are not consecutive zeros,
5429 // check if they consecutively come from only one of the source vectors.
5431 // V1 = {X, A, B, C} 0
5433 // vector_shuffle V1, V2 <1, 2, 3, X>
5435 if (!isShuffleMaskConsecutive(SVOp,
5436 0, // Mask Start Index
5437 NumElems-NumZeros, // Mask End Index(exclusive)
5438 NumZeros, // Where to start looking in the src vector
5439 NumElems, // Number of elements in vector
5440 OpSrc)) // Which source operand ?
5445 ShVal = SVOp->getOperand(OpSrc);
5449 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5450 /// logical left shift of a vector.
5451 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5452 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5454 SVOp->getSimpleValueType(0).getVectorNumElements();
5455 unsigned NumZeros = getNumOfConsecutiveZeros(
5456 SVOp, NumElems, true /* check zeros from left */, DAG,
5457 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5463 // Considering the elements in the mask that are not consecutive zeros,
5464 // check if they consecutively come from only one of the source vectors.
5466 // 0 { A, B, X, X } = V2
5468 // vector_shuffle V1, V2 <X, X, 4, 5>
5470 if (!isShuffleMaskConsecutive(SVOp,
5471 NumZeros, // Mask Start Index
5472 NumElems, // Mask End Index(exclusive)
5473 0, // Where to start looking in the src vector
5474 NumElems, // Number of elements in vector
5475 OpSrc)) // Which source operand ?
5480 ShVal = SVOp->getOperand(OpSrc);
5484 /// isVectorShift - Returns true if the shuffle can be implemented as a
5485 /// logical left or right shift of a vector.
5486 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5487 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5488 // Although the logic below support any bitwidth size, there are no
5489 // shift instructions which handle more than 128-bit vectors.
5490 if (!SVOp->getSimpleValueType(0).is128BitVector())
5493 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5494 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5500 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5502 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5503 unsigned NumNonZero, unsigned NumZero,
5505 const X86Subtarget* Subtarget,
5506 const TargetLowering &TLI) {
5513 for (unsigned i = 0; i < 16; ++i) {
5514 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5515 if (ThisIsNonZero && First) {
5517 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5519 V = DAG.getUNDEF(MVT::v8i16);
5524 SDValue ThisElt, LastElt;
5525 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5526 if (LastIsNonZero) {
5527 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5528 MVT::i16, Op.getOperand(i-1));
5530 if (ThisIsNonZero) {
5531 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5532 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5533 ThisElt, DAG.getConstant(8, MVT::i8));
5535 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5539 if (ThisElt.getNode())
5540 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5541 DAG.getIntPtrConstant(i/2));
5545 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5548 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5550 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5551 unsigned NumNonZero, unsigned NumZero,
5553 const X86Subtarget* Subtarget,
5554 const TargetLowering &TLI) {
5561 for (unsigned i = 0; i < 8; ++i) {
5562 bool isNonZero = (NonZeros & (1 << i)) != 0;
5566 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5568 V = DAG.getUNDEF(MVT::v8i16);
5571 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5572 MVT::v8i16, V, Op.getOperand(i),
5573 DAG.getIntPtrConstant(i));
5580 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5581 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5582 unsigned NonZeros, unsigned NumNonZero,
5583 unsigned NumZero, SelectionDAG &DAG,
5584 const X86Subtarget *Subtarget,
5585 const TargetLowering &TLI) {
5586 // We know there's at least one non-zero element
5587 unsigned FirstNonZeroIdx = 0;
5588 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5589 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5590 X86::isZeroNode(FirstNonZero)) {
5592 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5595 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5596 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5599 SDValue V = FirstNonZero.getOperand(0);
5600 MVT VVT = V.getSimpleValueType();
5601 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5604 unsigned FirstNonZeroDst =
5605 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5606 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5607 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5608 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5610 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5611 SDValue Elem = Op.getOperand(Idx);
5612 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5615 // TODO: What else can be here? Deal with it.
5616 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5619 // TODO: Some optimizations are still possible here
5620 // ex: Getting one element from a vector, and the rest from another.
5621 if (Elem.getOperand(0) != V)
5624 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5627 else if (IncorrectIdx == -1U) {
5631 // There was already one element with an incorrect index.
5632 // We can't optimize this case to an insertps.
5636 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5638 EVT VT = Op.getSimpleValueType();
5639 unsigned ElementMoveMask = 0;
5640 if (IncorrectIdx == -1U)
5641 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5643 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5645 SDValue InsertpsMask =
5646 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5647 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5653 /// getVShift - Return a vector logical shift node.
5655 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5656 unsigned NumBits, SelectionDAG &DAG,
5657 const TargetLowering &TLI, SDLoc dl) {
5658 assert(VT.is128BitVector() && "Unknown type for VShift");
5659 EVT ShVT = MVT::v2i64;
5660 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5661 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5662 return DAG.getNode(ISD::BITCAST, dl, VT,
5663 DAG.getNode(Opc, dl, ShVT, SrcOp,
5664 DAG.getConstant(NumBits,
5665 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5669 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5671 // Check if the scalar load can be widened into a vector load. And if
5672 // the address is "base + cst" see if the cst can be "absorbed" into
5673 // the shuffle mask.
5674 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5675 SDValue Ptr = LD->getBasePtr();
5676 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5678 EVT PVT = LD->getValueType(0);
5679 if (PVT != MVT::i32 && PVT != MVT::f32)
5684 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5685 FI = FINode->getIndex();
5687 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5688 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5689 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5690 Offset = Ptr.getConstantOperandVal(1);
5691 Ptr = Ptr.getOperand(0);
5696 // FIXME: 256-bit vector instructions don't require a strict alignment,
5697 // improve this code to support it better.
5698 unsigned RequiredAlign = VT.getSizeInBits()/8;
5699 SDValue Chain = LD->getChain();
5700 // Make sure the stack object alignment is at least 16 or 32.
5701 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5702 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5703 if (MFI->isFixedObjectIndex(FI)) {
5704 // Can't change the alignment. FIXME: It's possible to compute
5705 // the exact stack offset and reference FI + adjust offset instead.
5706 // If someone *really* cares about this. That's the way to implement it.
5709 MFI->setObjectAlignment(FI, RequiredAlign);
5713 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5714 // Ptr + (Offset & ~15).
5717 if ((Offset % RequiredAlign) & 3)
5719 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5721 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5722 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5724 int EltNo = (Offset - StartOffset) >> 2;
5725 unsigned NumElems = VT.getVectorNumElements();
5727 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5728 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5729 LD->getPointerInfo().getWithOffset(StartOffset),
5730 false, false, false, 0);
5732 SmallVector<int, 8> Mask;
5733 for (unsigned i = 0; i != NumElems; ++i)
5734 Mask.push_back(EltNo);
5736 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5742 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5743 /// vector of type 'VT', see if the elements can be replaced by a single large
5744 /// load which has the same value as a build_vector whose operands are 'elts'.
5746 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5748 /// FIXME: we'd also like to handle the case where the last elements are zero
5749 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5750 /// There's even a handy isZeroNode for that purpose.
5751 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5752 SDLoc &DL, SelectionDAG &DAG,
5753 bool isAfterLegalize) {
5754 EVT EltVT = VT.getVectorElementType();
5755 unsigned NumElems = Elts.size();
5757 LoadSDNode *LDBase = nullptr;
5758 unsigned LastLoadedElt = -1U;
5760 // For each element in the initializer, see if we've found a load or an undef.
5761 // If we don't find an initial load element, or later load elements are
5762 // non-consecutive, bail out.
5763 for (unsigned i = 0; i < NumElems; ++i) {
5764 SDValue Elt = Elts[i];
5766 if (!Elt.getNode() ||
5767 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5770 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5772 LDBase = cast<LoadSDNode>(Elt.getNode());
5776 if (Elt.getOpcode() == ISD::UNDEF)
5779 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5780 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5785 // If we have found an entire vector of loads and undefs, then return a large
5786 // load of the entire vector width starting at the base pointer. If we found
5787 // consecutive loads for the low half, generate a vzext_load node.
5788 if (LastLoadedElt == NumElems - 1) {
5790 if (isAfterLegalize &&
5791 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5794 SDValue NewLd = SDValue();
5796 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5797 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5798 LDBase->getPointerInfo(),
5799 LDBase->isVolatile(), LDBase->isNonTemporal(),
5800 LDBase->isInvariant(), 0);
5801 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5802 LDBase->getPointerInfo(),
5803 LDBase->isVolatile(), LDBase->isNonTemporal(),
5804 LDBase->isInvariant(), LDBase->getAlignment());
5806 if (LDBase->hasAnyUseOfValue(1)) {
5807 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5809 SDValue(NewLd.getNode(), 1));
5810 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5811 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5812 SDValue(NewLd.getNode(), 1));
5817 if (NumElems == 4 && LastLoadedElt == 1 &&
5818 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5819 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5820 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5822 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5823 LDBase->getPointerInfo(),
5824 LDBase->getAlignment(),
5825 false/*isVolatile*/, true/*ReadMem*/,
5828 // Make sure the newly-created LOAD is in the same position as LDBase in
5829 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5830 // update uses of LDBase's output chain to use the TokenFactor.
5831 if (LDBase->hasAnyUseOfValue(1)) {
5832 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5833 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5834 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5835 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5836 SDValue(ResNode.getNode(), 1));
5839 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5844 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5845 /// to generate a splat value for the following cases:
5846 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5847 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5848 /// a scalar load, or a constant.
5849 /// The VBROADCAST node is returned when a pattern is found,
5850 /// or SDValue() otherwise.
5851 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5852 SelectionDAG &DAG) {
5853 if (!Subtarget->hasFp256())
5856 MVT VT = Op.getSimpleValueType();
5859 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5860 "Unsupported vector type for broadcast.");
5865 switch (Op.getOpcode()) {
5867 // Unknown pattern found.
5870 case ISD::BUILD_VECTOR: {
5871 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5872 BitVector UndefElements;
5873 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5875 // We need a splat of a single value to use broadcast, and it doesn't
5876 // make any sense if the value is only in one element of the vector.
5877 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5881 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5882 Ld.getOpcode() == ISD::ConstantFP);
5884 // Make sure that all of the users of a non-constant load are from the
5885 // BUILD_VECTOR node.
5886 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5891 case ISD::VECTOR_SHUFFLE: {
5892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5894 // Shuffles must have a splat mask where the first element is
5896 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5899 SDValue Sc = Op.getOperand(0);
5900 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5901 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5903 if (!Subtarget->hasInt256())
5906 // Use the register form of the broadcast instruction available on AVX2.
5907 if (VT.getSizeInBits() >= 256)
5908 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5909 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5912 Ld = Sc.getOperand(0);
5913 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5914 Ld.getOpcode() == ISD::ConstantFP);
5916 // The scalar_to_vector node and the suspected
5917 // load node must have exactly one user.
5918 // Constants may have multiple users.
5920 // AVX-512 has register version of the broadcast
5921 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5922 Ld.getValueType().getSizeInBits() >= 32;
5923 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5930 bool IsGE256 = (VT.getSizeInBits() >= 256);
5932 // Handle the broadcasting a single constant scalar from the constant pool
5933 // into a vector. On Sandybridge it is still better to load a constant vector
5934 // from the constant pool and not to broadcast it from a scalar.
5935 if (ConstSplatVal && Subtarget->hasInt256()) {
5936 EVT CVT = Ld.getValueType();
5937 assert(!CVT.isVector() && "Must not broadcast a vector type");
5938 unsigned ScalarSize = CVT.getSizeInBits();
5940 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5941 const Constant *C = nullptr;
5942 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5943 C = CI->getConstantIntValue();
5944 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5945 C = CF->getConstantFPValue();
5947 assert(C && "Invalid constant type");
5949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5950 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5951 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5952 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5953 MachinePointerInfo::getConstantPool(),
5954 false, false, false, Alignment);
5956 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5960 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5961 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5963 // Handle AVX2 in-register broadcasts.
5964 if (!IsLoad && Subtarget->hasInt256() &&
5965 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5966 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5968 // The scalar source must be a normal load.
5972 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5973 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5975 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5976 // double since there is no vbroadcastsd xmm
5977 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5978 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5979 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5982 // Unsupported broadcast.
5986 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5987 /// underlying vector and index.
5989 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5991 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5993 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5994 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5997 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5999 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6001 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6002 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6005 // In this case the vector is the extract_subvector expression and the index
6006 // is 2, as specified by the shuffle.
6007 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6008 SDValue ShuffleVec = SVOp->getOperand(0);
6009 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6010 assert(ShuffleVecVT.getVectorElementType() ==
6011 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6013 int ShuffleIdx = SVOp->getMaskElt(Idx);
6014 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6015 ExtractedFromVec = ShuffleVec;
6021 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6022 MVT VT = Op.getSimpleValueType();
6024 // Skip if insert_vec_elt is not supported.
6025 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6026 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6030 unsigned NumElems = Op.getNumOperands();
6034 SmallVector<unsigned, 4> InsertIndices;
6035 SmallVector<int, 8> Mask(NumElems, -1);
6037 for (unsigned i = 0; i != NumElems; ++i) {
6038 unsigned Opc = Op.getOperand(i).getOpcode();
6040 if (Opc == ISD::UNDEF)
6043 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6044 // Quit if more than 1 elements need inserting.
6045 if (InsertIndices.size() > 1)
6048 InsertIndices.push_back(i);
6052 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6053 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6054 // Quit if non-constant index.
6055 if (!isa<ConstantSDNode>(ExtIdx))
6057 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6059 // Quit if extracted from vector of different type.
6060 if (ExtractedFromVec.getValueType() != VT)
6063 if (!VecIn1.getNode())
6064 VecIn1 = ExtractedFromVec;
6065 else if (VecIn1 != ExtractedFromVec) {
6066 if (!VecIn2.getNode())
6067 VecIn2 = ExtractedFromVec;
6068 else if (VecIn2 != ExtractedFromVec)
6069 // Quit if more than 2 vectors to shuffle
6073 if (ExtractedFromVec == VecIn1)
6075 else if (ExtractedFromVec == VecIn2)
6076 Mask[i] = Idx + NumElems;
6079 if (!VecIn1.getNode())
6082 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6083 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6084 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6085 unsigned Idx = InsertIndices[i];
6086 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6087 DAG.getIntPtrConstant(Idx));
6093 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6095 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6097 MVT VT = Op.getSimpleValueType();
6098 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6099 "Unexpected type in LowerBUILD_VECTORvXi1!");
6102 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6103 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6104 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6105 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6108 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6109 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6110 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6111 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6114 bool AllContants = true;
6115 uint64_t Immediate = 0;
6116 int NonConstIdx = -1;
6117 bool IsSplat = true;
6118 unsigned NumNonConsts = 0;
6119 unsigned NumConsts = 0;
6120 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6121 SDValue In = Op.getOperand(idx);
6122 if (In.getOpcode() == ISD::UNDEF)
6124 if (!isa<ConstantSDNode>(In)) {
6125 AllContants = false;
6131 if (cast<ConstantSDNode>(In)->getZExtValue())
6132 Immediate |= (1ULL << idx);
6134 if (In != Op.getOperand(0))
6139 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6140 DAG.getConstant(Immediate, MVT::i16));
6141 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6142 DAG.getIntPtrConstant(0));
6145 if (NumNonConsts == 1 && NonConstIdx != 0) {
6148 SDValue VecAsImm = DAG.getConstant(Immediate,
6149 MVT::getIntegerVT(VT.getSizeInBits()));
6150 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6153 DstVec = DAG.getUNDEF(VT);
6154 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6155 Op.getOperand(NonConstIdx),
6156 DAG.getIntPtrConstant(NonConstIdx));
6158 if (!IsSplat && (NonConstIdx != 0))
6159 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6160 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6163 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6164 DAG.getConstant(-1, SelectVT),
6165 DAG.getConstant(0, SelectVT));
6167 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6168 DAG.getConstant((Immediate | 1), SelectVT),
6169 DAG.getConstant(Immediate, SelectVT));
6170 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6173 /// \brief Return true if \p N implements a horizontal binop and return the
6174 /// operands for the horizontal binop into V0 and V1.
6176 /// This is a helper function of PerformBUILD_VECTORCombine.
6177 /// This function checks that the build_vector \p N in input implements a
6178 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6179 /// operation to match.
6180 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6181 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6182 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6185 /// This function only analyzes elements of \p N whose indices are
6186 /// in range [BaseIdx, LastIdx).
6187 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6189 unsigned BaseIdx, unsigned LastIdx,
6190 SDValue &V0, SDValue &V1) {
6191 EVT VT = N->getValueType(0);
6193 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6194 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6195 "Invalid Vector in input!");
6197 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6198 bool CanFold = true;
6199 unsigned ExpectedVExtractIdx = BaseIdx;
6200 unsigned NumElts = LastIdx - BaseIdx;
6201 V0 = DAG.getUNDEF(VT);
6202 V1 = DAG.getUNDEF(VT);
6204 // Check if N implements a horizontal binop.
6205 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6206 SDValue Op = N->getOperand(i + BaseIdx);
6209 if (Op->getOpcode() == ISD::UNDEF) {
6210 // Update the expected vector extract index.
6211 if (i * 2 == NumElts)
6212 ExpectedVExtractIdx = BaseIdx;
6213 ExpectedVExtractIdx += 2;
6217 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6222 SDValue Op0 = Op.getOperand(0);
6223 SDValue Op1 = Op.getOperand(1);
6225 // Try to match the following pattern:
6226 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6227 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6228 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6229 Op0.getOperand(0) == Op1.getOperand(0) &&
6230 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6231 isa<ConstantSDNode>(Op1.getOperand(1)));
6235 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6236 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6238 if (i * 2 < NumElts) {
6239 if (V0.getOpcode() == ISD::UNDEF)
6240 V0 = Op0.getOperand(0);
6242 if (V1.getOpcode() == ISD::UNDEF)
6243 V1 = Op0.getOperand(0);
6244 if (i * 2 == NumElts)
6245 ExpectedVExtractIdx = BaseIdx;
6248 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6249 if (I0 == ExpectedVExtractIdx)
6250 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6251 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6252 // Try to match the following dag sequence:
6253 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6254 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6258 ExpectedVExtractIdx += 2;
6264 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6265 /// a concat_vector.
6267 /// This is a helper function of PerformBUILD_VECTORCombine.
6268 /// This function expects two 256-bit vectors called V0 and V1.
6269 /// At first, each vector is split into two separate 128-bit vectors.
6270 /// Then, the resulting 128-bit vectors are used to implement two
6271 /// horizontal binary operations.
6273 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6275 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6276 /// the two new horizontal binop.
6277 /// When Mode is set, the first horizontal binop dag node would take as input
6278 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6279 /// horizontal binop dag node would take as input the lower 128-bit of V1
6280 /// and the upper 128-bit of V1.
6282 /// HADD V0_LO, V0_HI
6283 /// HADD V1_LO, V1_HI
6285 /// Otherwise, the first horizontal binop dag node takes as input the lower
6286 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6287 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6289 /// HADD V0_LO, V1_LO
6290 /// HADD V0_HI, V1_HI
6292 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6293 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6294 /// the upper 128-bits of the result.
6295 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6296 SDLoc DL, SelectionDAG &DAG,
6297 unsigned X86Opcode, bool Mode,
6298 bool isUndefLO, bool isUndefHI) {
6299 EVT VT = V0.getValueType();
6300 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6301 "Invalid nodes in input!");
6303 unsigned NumElts = VT.getVectorNumElements();
6304 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6305 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6306 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6307 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6308 EVT NewVT = V0_LO.getValueType();
6310 SDValue LO = DAG.getUNDEF(NewVT);
6311 SDValue HI = DAG.getUNDEF(NewVT);
6314 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6315 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6316 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6317 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6318 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6320 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6321 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6322 V1_LO->getOpcode() != ISD::UNDEF))
6323 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6325 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6326 V1_HI->getOpcode() != ISD::UNDEF))
6327 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6330 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6333 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6334 /// sequence of 'vadd + vsub + blendi'.
6335 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6336 const X86Subtarget *Subtarget) {
6338 EVT VT = BV->getValueType(0);
6339 unsigned NumElts = VT.getVectorNumElements();
6340 SDValue InVec0 = DAG.getUNDEF(VT);
6341 SDValue InVec1 = DAG.getUNDEF(VT);
6343 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6344 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6346 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6348 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6351 // Odd-numbered elements in the input build vector are obtained from
6352 // adding two integer/float elements.
6353 // Even-numbered elements in the input build vector are obtained from
6354 // subtracting two integer/float elements.
6355 unsigned ExpectedOpcode = ISD::FSUB;
6356 unsigned NextExpectedOpcode = ISD::FADD;
6357 bool AddFound = false;
6358 bool SubFound = false;
6360 for (unsigned i = 0, e = NumElts; i != e; i++) {
6361 SDValue Op = BV->getOperand(i);
6363 // Skip 'undef' values.
6364 unsigned Opcode = Op.getOpcode();
6365 if (Opcode == ISD::UNDEF) {
6366 std::swap(ExpectedOpcode, NextExpectedOpcode);
6370 // Early exit if we found an unexpected opcode.
6371 if (Opcode != ExpectedOpcode)
6374 SDValue Op0 = Op.getOperand(0);
6375 SDValue Op1 = Op.getOperand(1);
6377 // Try to match the following pattern:
6378 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6379 // Early exit if we cannot match that sequence.
6380 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6381 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6382 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6383 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6384 Op0.getOperand(1) != Op1.getOperand(1))
6387 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6391 // We found a valid add/sub node. Update the information accordingly.
6397 // Update InVec0 and InVec1.
6398 if (InVec0.getOpcode() == ISD::UNDEF)
6399 InVec0 = Op0.getOperand(0);
6400 if (InVec1.getOpcode() == ISD::UNDEF)
6401 InVec1 = Op1.getOperand(0);
6403 // Make sure that operands in input to each add/sub node always
6404 // come from a same pair of vectors.
6405 if (InVec0 != Op0.getOperand(0)) {
6406 if (ExpectedOpcode == ISD::FSUB)
6409 // FADD is commutable. Try to commute the operands
6410 // and then test again.
6411 std::swap(Op0, Op1);
6412 if (InVec0 != Op0.getOperand(0))
6416 if (InVec1 != Op1.getOperand(0))
6419 // Update the pair of expected opcodes.
6420 std::swap(ExpectedOpcode, NextExpectedOpcode);
6423 // Don't try to fold this build_vector into a VSELECT if it has
6424 // too many UNDEF operands.
6425 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6426 InVec1.getOpcode() != ISD::UNDEF) {
6427 // Emit a sequence of vector add and sub followed by a VSELECT.
6428 // The new VSELECT will be lowered into a BLENDI.
6429 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6430 // and emit a single ADDSUB instruction.
6431 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6432 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6434 // Construct the VSELECT mask.
6435 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6436 EVT SVT = MaskVT.getVectorElementType();
6437 unsigned SVTBits = SVT.getSizeInBits();
6438 SmallVector<SDValue, 8> Ops;
6440 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6441 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6442 APInt::getAllOnesValue(SVTBits);
6443 SDValue Constant = DAG.getConstant(Value, SVT);
6444 Ops.push_back(Constant);
6447 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6448 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6454 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6455 const X86Subtarget *Subtarget) {
6457 EVT VT = N->getValueType(0);
6458 unsigned NumElts = VT.getVectorNumElements();
6459 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6460 SDValue InVec0, InVec1;
6462 // Try to match an ADDSUB.
6463 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6464 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6465 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6466 if (Value.getNode())
6470 // Try to match horizontal ADD/SUB.
6471 unsigned NumUndefsLO = 0;
6472 unsigned NumUndefsHI = 0;
6473 unsigned Half = NumElts/2;
6475 // Count the number of UNDEF operands in the build_vector in input.
6476 for (unsigned i = 0, e = Half; i != e; ++i)
6477 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6480 for (unsigned i = Half, e = NumElts; i != e; ++i)
6481 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6484 // Early exit if this is either a build_vector of all UNDEFs or all the
6485 // operands but one are UNDEF.
6486 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6489 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6490 // Try to match an SSE3 float HADD/HSUB.
6491 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6492 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6494 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6495 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6496 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6497 // Try to match an SSSE3 integer HADD/HSUB.
6498 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6499 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6501 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6502 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6505 if (!Subtarget->hasAVX())
6508 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6509 // Try to match an AVX horizontal add/sub of packed single/double
6510 // precision floating point values from 256-bit vectors.
6511 SDValue InVec2, InVec3;
6512 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6513 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6514 ((InVec0.getOpcode() == ISD::UNDEF ||
6515 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6516 ((InVec1.getOpcode() == ISD::UNDEF ||
6517 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6518 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6520 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6521 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6522 ((InVec0.getOpcode() == ISD::UNDEF ||
6523 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6524 ((InVec1.getOpcode() == ISD::UNDEF ||
6525 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6526 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6527 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6528 // Try to match an AVX2 horizontal add/sub of signed integers.
6529 SDValue InVec2, InVec3;
6531 bool CanFold = true;
6533 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6534 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6535 ((InVec0.getOpcode() == ISD::UNDEF ||
6536 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6537 ((InVec1.getOpcode() == ISD::UNDEF ||
6538 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6539 X86Opcode = X86ISD::HADD;
6540 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6541 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6542 ((InVec0.getOpcode() == ISD::UNDEF ||
6543 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6544 ((InVec1.getOpcode() == ISD::UNDEF ||
6545 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6546 X86Opcode = X86ISD::HSUB;
6551 // Fold this build_vector into a single horizontal add/sub.
6552 // Do this only if the target has AVX2.
6553 if (Subtarget->hasAVX2())
6554 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6556 // Do not try to expand this build_vector into a pair of horizontal
6557 // add/sub if we can emit a pair of scalar add/sub.
6558 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6561 // Convert this build_vector into a pair of horizontal binop followed by
6563 bool isUndefLO = NumUndefsLO == Half;
6564 bool isUndefHI = NumUndefsHI == Half;
6565 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6566 isUndefLO, isUndefHI);
6570 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6571 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6573 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6574 X86Opcode = X86ISD::HADD;
6575 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6576 X86Opcode = X86ISD::HSUB;
6577 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6578 X86Opcode = X86ISD::FHADD;
6579 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6580 X86Opcode = X86ISD::FHSUB;
6584 // Don't try to expand this build_vector into a pair of horizontal add/sub
6585 // if we can simply emit a pair of scalar add/sub.
6586 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6589 // Convert this build_vector into two horizontal add/sub followed by
6591 bool isUndefLO = NumUndefsLO == Half;
6592 bool isUndefHI = NumUndefsHI == Half;
6593 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6594 isUndefLO, isUndefHI);
6601 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6604 MVT VT = Op.getSimpleValueType();
6605 MVT ExtVT = VT.getVectorElementType();
6606 unsigned NumElems = Op.getNumOperands();
6608 // Generate vectors for predicate vectors.
6609 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6610 return LowerBUILD_VECTORvXi1(Op, DAG);
6612 // Vectors containing all zeros can be matched by pxor and xorps later
6613 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6614 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6615 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6616 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6619 return getZeroVector(VT, Subtarget, DAG, dl);
6622 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6623 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6624 // vpcmpeqd on 256-bit vectors.
6625 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6626 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6629 if (!VT.is512BitVector())
6630 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6633 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6634 if (Broadcast.getNode())
6637 unsigned EVTBits = ExtVT.getSizeInBits();
6639 unsigned NumZero = 0;
6640 unsigned NumNonZero = 0;
6641 unsigned NonZeros = 0;
6642 bool IsAllConstants = true;
6643 SmallSet<SDValue, 8> Values;
6644 for (unsigned i = 0; i < NumElems; ++i) {
6645 SDValue Elt = Op.getOperand(i);
6646 if (Elt.getOpcode() == ISD::UNDEF)
6649 if (Elt.getOpcode() != ISD::Constant &&
6650 Elt.getOpcode() != ISD::ConstantFP)
6651 IsAllConstants = false;
6652 if (X86::isZeroNode(Elt))
6655 NonZeros |= (1 << i);
6660 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6661 if (NumNonZero == 0)
6662 return DAG.getUNDEF(VT);
6664 // Special case for single non-zero, non-undef, element.
6665 if (NumNonZero == 1) {
6666 unsigned Idx = countTrailingZeros(NonZeros);
6667 SDValue Item = Op.getOperand(Idx);
6669 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6670 // the value are obviously zero, truncate the value to i32 and do the
6671 // insertion that way. Only do this if the value is non-constant or if the
6672 // value is a constant being inserted into element 0. It is cheaper to do
6673 // a constant pool load than it is to do a movd + shuffle.
6674 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6675 (!IsAllConstants || Idx == 0)) {
6676 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6678 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6679 EVT VecVT = MVT::v4i32;
6680 unsigned VecElts = 4;
6682 // Truncate the value (which may itself be a constant) to i32, and
6683 // convert it to a vector with movd (S2V+shuffle to zero extend).
6684 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6685 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6686 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6688 // Now we have our 32-bit value zero extended in the low element of
6689 // a vector. If Idx != 0, swizzle it into place.
6691 SmallVector<int, 4> Mask;
6692 Mask.push_back(Idx);
6693 for (unsigned i = 1; i != VecElts; ++i)
6695 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6698 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6702 // If we have a constant or non-constant insertion into the low element of
6703 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6704 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6705 // depending on what the source datatype is.
6708 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6710 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6711 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6712 if (VT.is256BitVector() || VT.is512BitVector()) {
6713 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6714 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6715 Item, DAG.getIntPtrConstant(0));
6717 assert(VT.is128BitVector() && "Expected an SSE value type!");
6718 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6719 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6720 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6723 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6724 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6725 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6726 if (VT.is256BitVector()) {
6727 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6728 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6730 assert(VT.is128BitVector() && "Expected an SSE value type!");
6731 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6733 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6737 // Is it a vector logical left shift?
6738 if (NumElems == 2 && Idx == 1 &&
6739 X86::isZeroNode(Op.getOperand(0)) &&
6740 !X86::isZeroNode(Op.getOperand(1))) {
6741 unsigned NumBits = VT.getSizeInBits();
6742 return getVShift(true, VT,
6743 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6744 VT, Op.getOperand(1)),
6745 NumBits/2, DAG, *this, dl);
6748 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6751 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6752 // is a non-constant being inserted into an element other than the low one,
6753 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6754 // movd/movss) to move this into the low element, then shuffle it into
6756 if (EVTBits == 32) {
6757 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6759 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6760 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6761 SmallVector<int, 8> MaskVec;
6762 for (unsigned i = 0; i != NumElems; ++i)
6763 MaskVec.push_back(i == Idx ? 0 : 1);
6764 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6768 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6769 if (Values.size() == 1) {
6770 if (EVTBits == 32) {
6771 // Instead of a shuffle like this:
6772 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6773 // Check if it's possible to issue this instead.
6774 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6775 unsigned Idx = countTrailingZeros(NonZeros);
6776 SDValue Item = Op.getOperand(Idx);
6777 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6778 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6783 // A vector full of immediates; various special cases are already
6784 // handled, so this is best done with a single constant-pool load.
6788 // For AVX-length vectors, build the individual 128-bit pieces and use
6789 // shuffles to put them in place.
6790 if (VT.is256BitVector() || VT.is512BitVector()) {
6791 SmallVector<SDValue, 64> V;
6792 for (unsigned i = 0; i != NumElems; ++i)
6793 V.push_back(Op.getOperand(i));
6795 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6797 // Build both the lower and upper subvector.
6798 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6799 makeArrayRef(&V[0], NumElems/2));
6800 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6801 makeArrayRef(&V[NumElems / 2], NumElems/2));
6803 // Recreate the wider vector with the lower and upper part.
6804 if (VT.is256BitVector())
6805 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6806 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6809 // Let legalizer expand 2-wide build_vectors.
6810 if (EVTBits == 64) {
6811 if (NumNonZero == 1) {
6812 // One half is zero or undef.
6813 unsigned Idx = countTrailingZeros(NonZeros);
6814 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6815 Op.getOperand(Idx));
6816 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6821 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6822 if (EVTBits == 8 && NumElems == 16) {
6823 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6825 if (V.getNode()) return V;
6828 if (EVTBits == 16 && NumElems == 8) {
6829 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6831 if (V.getNode()) return V;
6834 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6835 if (EVTBits == 32 && NumElems == 4) {
6836 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6837 NumZero, DAG, Subtarget, *this);
6842 // If element VT is == 32 bits, turn it into a number of shuffles.
6843 SmallVector<SDValue, 8> V(NumElems);
6844 if (NumElems == 4 && NumZero > 0) {
6845 for (unsigned i = 0; i < 4; ++i) {
6846 bool isZero = !(NonZeros & (1 << i));
6848 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6850 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6853 for (unsigned i = 0; i < 2; ++i) {
6854 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6857 V[i] = V[i*2]; // Must be a zero vector.
6860 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6863 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6866 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6871 bool Reverse1 = (NonZeros & 0x3) == 2;
6872 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6876 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6877 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6879 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6882 if (Values.size() > 1 && VT.is128BitVector()) {
6883 // Check for a build vector of consecutive loads.
6884 for (unsigned i = 0; i < NumElems; ++i)
6885 V[i] = Op.getOperand(i);
6887 // Check for elements which are consecutive loads.
6888 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6892 // Check for a build vector from mostly shuffle plus few inserting.
6893 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6897 // For SSE 4.1, use insertps to put the high elements into the low element.
6898 if (getSubtarget()->hasSSE41()) {
6900 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6901 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6903 Result = DAG.getUNDEF(VT);
6905 for (unsigned i = 1; i < NumElems; ++i) {
6906 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6907 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6908 Op.getOperand(i), DAG.getIntPtrConstant(i));
6913 // Otherwise, expand into a number of unpckl*, start by extending each of
6914 // our (non-undef) elements to the full vector width with the element in the
6915 // bottom slot of the vector (which generates no code for SSE).
6916 for (unsigned i = 0; i < NumElems; ++i) {
6917 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6918 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6920 V[i] = DAG.getUNDEF(VT);
6923 // Next, we iteratively mix elements, e.g. for v4f32:
6924 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6925 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6926 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6927 unsigned EltStride = NumElems >> 1;
6928 while (EltStride != 0) {
6929 for (unsigned i = 0; i < EltStride; ++i) {
6930 // If V[i+EltStride] is undef and this is the first round of mixing,
6931 // then it is safe to just drop this shuffle: V[i] is already in the
6932 // right place, the one element (since it's the first round) being
6933 // inserted as undef can be dropped. This isn't safe for successive
6934 // rounds because they will permute elements within both vectors.
6935 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6936 EltStride == NumElems/2)
6939 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6948 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6949 // to create 256-bit vectors from two other 128-bit ones.
6950 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6952 MVT ResVT = Op.getSimpleValueType();
6954 assert((ResVT.is256BitVector() ||
6955 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6957 SDValue V1 = Op.getOperand(0);
6958 SDValue V2 = Op.getOperand(1);
6959 unsigned NumElems = ResVT.getVectorNumElements();
6960 if(ResVT.is256BitVector())
6961 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6963 if (Op.getNumOperands() == 4) {
6964 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6965 ResVT.getVectorNumElements()/2);
6966 SDValue V3 = Op.getOperand(2);
6967 SDValue V4 = Op.getOperand(3);
6968 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6969 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6971 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6974 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6975 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6976 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6977 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6978 Op.getNumOperands() == 4)));
6980 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6981 // from two other 128-bit ones.
6983 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6984 return LowerAVXCONCAT_VECTORS(Op, DAG);
6988 //===----------------------------------------------------------------------===//
6989 // Vector shuffle lowering
6991 // This is an experimental code path for lowering vector shuffles on x86. It is
6992 // designed to handle arbitrary vector shuffles and blends, gracefully
6993 // degrading performance as necessary. It works hard to recognize idiomatic
6994 // shuffles and lower them to optimal instruction patterns without leaving
6995 // a framework that allows reasonably efficient handling of all vector shuffle
6997 //===----------------------------------------------------------------------===//
6999 /// \brief Tiny helper function to identify a no-op mask.
7001 /// This is a somewhat boring predicate function. It checks whether the mask
7002 /// array input, which is assumed to be a single-input shuffle mask of the kind
7003 /// used by the X86 shuffle instructions (not a fully general
7004 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7005 /// in-place shuffle are 'no-op's.
7006 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7007 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7008 if (Mask[i] != -1 && Mask[i] != i)
7013 /// \brief Helper function to classify a mask as a single-input mask.
7015 /// This isn't a generic single-input test because in the vector shuffle
7016 /// lowering we canonicalize single inputs to be the first input operand. This
7017 /// means we can more quickly test for a single input by only checking whether
7018 /// an input from the second operand exists. We also assume that the size of
7019 /// mask corresponds to the size of the input vectors which isn't true in the
7020 /// fully general case.
7021 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7023 if (M >= (int)Mask.size())
7028 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7030 /// This helper function produces an 8-bit shuffle immediate corresponding to
7031 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7032 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7035 /// NB: We rely heavily on "undef" masks preserving the input lane.
7036 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7037 SelectionDAG &DAG) {
7038 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7039 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7040 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7041 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7042 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7045 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7046 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7047 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7048 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7049 return DAG.getConstant(Imm, MVT::i8);
7052 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7054 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7055 /// support for floating point shuffles but not integer shuffles. These
7056 /// instructions will incur a domain crossing penalty on some chips though so
7057 /// it is better to avoid lowering through this for integer vectors where
7059 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7060 const X86Subtarget *Subtarget,
7061 SelectionDAG &DAG) {
7063 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7064 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7065 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7066 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7067 ArrayRef<int> Mask = SVOp->getMask();
7068 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7070 if (isSingleInputShuffleMask(Mask)) {
7071 // Straight shuffle of a single input vector. Simulate this by using the
7072 // single input as both of the "inputs" to this instruction..
7073 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7074 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7075 DAG.getConstant(SHUFPDMask, MVT::i8));
7077 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7078 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7080 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7081 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7082 DAG.getConstant(SHUFPDMask, MVT::i8));
7085 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7087 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7088 /// the integer unit to minimize domain crossing penalties. However, for blends
7089 /// it falls back to the floating point shuffle operation with appropriate bit
7091 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7092 const X86Subtarget *Subtarget,
7093 SelectionDAG &DAG) {
7095 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7096 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7097 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7098 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7099 ArrayRef<int> Mask = SVOp->getMask();
7100 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7102 if (isSingleInputShuffleMask(Mask)) {
7103 // Straight shuffle of a single input vector. For everything from SSE2
7104 // onward this has a single fast instruction with no scary immediates.
7105 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7106 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7107 int WidenedMask[4] = {
7108 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7109 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7111 ISD::BITCAST, DL, MVT::v2i64,
7112 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7113 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7116 // We implement this with SHUFPD which is pretty lame because it will likely
7117 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7118 // However, all the alternatives are still more cycles and newer chips don't
7119 // have this problem. It would be really nice if x86 had better shuffles here.
7120 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7121 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7122 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7123 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7126 /// \brief Lower 4-lane 32-bit floating point shuffles.
7128 /// Uses instructions exclusively from the floating point unit to minimize
7129 /// domain crossing penalties, as these are sufficient to implement all v4f32
7131 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7132 const X86Subtarget *Subtarget,
7133 SelectionDAG &DAG) {
7135 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7136 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7137 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7138 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7139 ArrayRef<int> Mask = SVOp->getMask();
7140 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7142 SDValue LowV = V1, HighV = V2;
7143 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7146 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7148 if (NumV2Elements == 0)
7149 // Straight shuffle of a single input vector. We pass the input vector to
7150 // both operands to simulate this with a SHUFPS.
7151 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7152 getV4X86ShuffleImm8ForMask(Mask, DAG));
7154 if (NumV2Elements == 1) {
7156 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7158 // Compute the index adjacent to V2Index and in the same half by toggling
7160 int V2AdjIndex = V2Index ^ 1;
7162 if (Mask[V2AdjIndex] == -1) {
7163 // Handles all the cases where we have a single V2 element and an undef.
7164 // This will only ever happen in the high lanes because we commute the
7165 // vector otherwise.
7167 std::swap(LowV, HighV);
7168 NewMask[V2Index] -= 4;
7170 // Handle the case where the V2 element ends up adjacent to a V1 element.
7171 // To make this work, blend them together as the first step.
7172 int V1Index = V2AdjIndex;
7173 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7174 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7175 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7177 // Now proceed to reconstruct the final blend as we have the necessary
7178 // high or low half formed.
7185 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7186 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7188 } else if (NumV2Elements == 2) {
7189 if (Mask[0] < 4 && Mask[1] < 4) {
7190 // Handle the easy case where we have V1 in the low lanes and V2 in the
7191 // high lanes. We never see this reversed because we sort the shuffle.
7195 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7196 // trying to place elements directly, just blend them and set up the final
7197 // shuffle to place them.
7199 // The first two blend mask elements are for V1, the second two are for
7201 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7202 Mask[2] < 4 ? Mask[2] : Mask[3],
7203 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7204 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7205 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7206 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7208 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7211 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7212 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7213 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7214 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7217 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7218 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7221 /// \brief Lower 4-lane i32 vector shuffles.
7223 /// We try to handle these with integer-domain shuffles where we can, but for
7224 /// blends we use the floating point domain blend instructions.
7225 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7226 const X86Subtarget *Subtarget,
7227 SelectionDAG &DAG) {
7229 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7230 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7231 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7232 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7233 ArrayRef<int> Mask = SVOp->getMask();
7234 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7236 if (isSingleInputShuffleMask(Mask))
7237 // Straight shuffle of a single input vector. For everything from SSE2
7238 // onward this has a single fast instruction with no scary immediates.
7239 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7240 getV4X86ShuffleImm8ForMask(Mask, DAG));
7242 // We implement this with SHUFPS because it can blend from two vectors.
7243 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7244 // up the inputs, bypassing domain shift penalties that we would encur if we
7245 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7247 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7248 DAG.getVectorShuffle(
7250 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7251 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7254 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7255 /// shuffle lowering, and the most complex part.
7257 /// The lowering strategy is to try to form pairs of input lanes which are
7258 /// targeted at the same half of the final vector, and then use a dword shuffle
7259 /// to place them onto the right half, and finally unpack the paired lanes into
7260 /// their final position.
7262 /// The exact breakdown of how to form these dword pairs and align them on the
7263 /// correct sides is really tricky. See the comments within the function for
7264 /// more of the details.
7265 static SDValue lowerV8I16SingleInputVectorShuffle(
7266 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7267 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7268 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7269 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7270 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7272 SmallVector<int, 4> LoInputs;
7273 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7274 [](int M) { return M >= 0; });
7275 std::sort(LoInputs.begin(), LoInputs.end());
7276 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7277 SmallVector<int, 4> HiInputs;
7278 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7279 [](int M) { return M >= 0; });
7280 std::sort(HiInputs.begin(), HiInputs.end());
7281 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7283 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7284 int NumHToL = LoInputs.size() - NumLToL;
7286 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7287 int NumHToH = HiInputs.size() - NumLToH;
7288 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7289 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7290 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7291 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7293 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7294 // such inputs we can swap two of the dwords across the half mark and end up
7295 // with <=2 inputs to each half in each half. Once there, we can fall through
7296 // to the generic code below. For example:
7298 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7299 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7301 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7303 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7304 int ThreeInputHalfSum, int OneInputHalfOffset) {
7305 // Compute the index of dword with only one word among the three inputs in
7306 // a half by taking the sum of the half with three inputs and subtracting
7307 // the sum of the actual three inputs. The difference is the remaining
7309 int DWordA = (ThreeInputHalfSum -
7310 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7312 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7314 int PSHUFDMask[] = {0, 1, 2, 3};
7315 PSHUFDMask[DWordA] = DWordB;
7316 PSHUFDMask[DWordB] = DWordA;
7317 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7318 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7319 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7320 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7322 // Adjust the mask to match the new locations of A and B.
7324 if (M != -1 && M/2 == DWordA)
7325 M = 2 * DWordB + M % 2;
7326 else if (M != -1 && M/2 == DWordB)
7327 M = 2 * DWordA + M % 2;
7329 // Recurse back into this routine to re-compute state now that this isn't
7330 // a 3 and 1 problem.
7331 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7334 if (NumLToL == 3 && NumHToL == 1)
7335 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7336 else if (NumLToL == 1 && NumHToL == 3)
7337 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7338 else if (NumLToH == 1 && NumHToH == 3)
7339 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7340 else if (NumLToH == 3 && NumHToH == 1)
7341 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7343 // At this point there are at most two inputs to the low and high halves from
7344 // each half. That means the inputs can always be grouped into dwords and
7345 // those dwords can then be moved to the correct half with a dword shuffle.
7346 // We use at most one low and one high word shuffle to collect these paired
7347 // inputs into dwords, and finally a dword shuffle to place them.
7348 int PSHUFLMask[4] = {-1, -1, -1, -1};
7349 int PSHUFHMask[4] = {-1, -1, -1, -1};
7350 int PSHUFDMask[4] = {-1, -1, -1, -1};
7352 // First fix the masks for all the inputs that are staying in their
7353 // original halves. This will then dictate the targets of the cross-half
7355 auto fixInPlaceInputs = [&PSHUFDMask](
7356 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7357 MutableArrayRef<int> HalfMask, int HalfOffset) {
7358 if (InPlaceInputs.empty())
7360 if (InPlaceInputs.size() == 1) {
7361 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7362 InPlaceInputs[0] - HalfOffset;
7363 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7367 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7368 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7369 InPlaceInputs[0] - HalfOffset;
7370 // Put the second input next to the first so that they are packed into
7371 // a dword. We find the adjacent index by toggling the low bit.
7372 int AdjIndex = InPlaceInputs[0] ^ 1;
7373 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7374 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7375 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7377 if (!HToLInputs.empty())
7378 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7379 if (!LToHInputs.empty())
7380 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7382 // Now gather the cross-half inputs and place them into a free dword of
7383 // their target half.
7384 // FIXME: This operation could almost certainly be simplified dramatically to
7385 // look more like the 3-1 fixing operation.
7386 auto moveInputsToRightHalf = [&PSHUFDMask](
7387 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7388 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7389 int SourceOffset, int DestOffset) {
7390 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7391 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7393 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7395 int LowWord = Word & ~1;
7396 int HighWord = Word | 1;
7397 return isWordClobbered(SourceHalfMask, LowWord) ||
7398 isWordClobbered(SourceHalfMask, HighWord);
7401 if (IncomingInputs.empty())
7404 if (ExistingInputs.empty()) {
7405 // Map any dwords with inputs from them into the right half.
7406 for (int Input : IncomingInputs) {
7407 // If the source half mask maps over the inputs, turn those into
7408 // swaps and use the swapped lane.
7409 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7410 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7411 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7412 Input - SourceOffset;
7413 // We have to swap the uses in our half mask in one sweep.
7414 for (int &M : HalfMask)
7415 if (M == SourceHalfMask[Input - SourceOffset])
7417 else if (M == Input)
7418 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7420 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7421 Input - SourceOffset &&
7422 "Previous placement doesn't match!");
7424 // Note that this correctly re-maps both when we do a swap and when
7425 // we observe the other side of the swap above. We rely on that to
7426 // avoid swapping the members of the input list directly.
7427 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7430 // Map the input's dword into the correct half.
7431 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7432 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7434 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7436 "Previous placement doesn't match!");
7439 // And just directly shift any other-half mask elements to be same-half
7440 // as we will have mirrored the dword containing the element into the
7441 // same position within that half.
7442 for (int &M : HalfMask)
7443 if (M >= SourceOffset && M < SourceOffset + 4) {
7444 M = M - SourceOffset + DestOffset;
7445 assert(M >= 0 && "This should never wrap below zero!");
7450 // Ensure we have the input in a viable dword of its current half. This
7451 // is particularly tricky because the original position may be clobbered
7452 // by inputs being moved and *staying* in that half.
7453 if (IncomingInputs.size() == 1) {
7454 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7455 int InputFixed = std::find(std::begin(SourceHalfMask),
7456 std::end(SourceHalfMask), -1) -
7457 std::begin(SourceHalfMask) + SourceOffset;
7458 SourceHalfMask[InputFixed - SourceOffset] =
7459 IncomingInputs[0] - SourceOffset;
7460 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7462 IncomingInputs[0] = InputFixed;
7464 } else if (IncomingInputs.size() == 2) {
7465 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7466 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7467 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7468 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7469 "Not all dwords can be clobbered!");
7470 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7471 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7472 for (int &M : HalfMask)
7473 if (M == IncomingInputs[0])
7474 M = SourceDWordBase + SourceOffset;
7475 else if (M == IncomingInputs[1])
7476 M = SourceDWordBase + 1 + SourceOffset;
7477 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7478 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7481 llvm_unreachable("Unhandled input size!");
7484 // Now hoist the DWord down to the right half.
7485 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7486 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7487 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7488 for (int Input : IncomingInputs)
7489 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7490 FreeDWord * 2 + Input % 2);
7492 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7493 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7494 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7495 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7497 // Now enact all the shuffles we've computed to move the inputs into their
7499 if (!isNoopShuffleMask(PSHUFLMask))
7500 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7501 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7502 if (!isNoopShuffleMask(PSHUFHMask))
7503 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7504 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7505 if (!isNoopShuffleMask(PSHUFDMask))
7506 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7507 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7508 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7509 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7511 // At this point, each half should contain all its inputs, and we can then
7512 // just shuffle them into their final position.
7513 assert(std::count_if(LoMask.begin(), LoMask.end(),
7514 [](int M) { return M >= 4; }) == 0 &&
7515 "Failed to lift all the high half inputs to the low mask!");
7516 assert(std::count_if(HiMask.begin(), HiMask.end(),
7517 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7518 "Failed to lift all the low half inputs to the high mask!");
7520 // Do a half shuffle for the low mask.
7521 if (!isNoopShuffleMask(LoMask))
7522 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7523 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7525 // Do a half shuffle with the high mask after shifting its values down.
7526 for (int &M : HiMask)
7529 if (!isNoopShuffleMask(HiMask))
7530 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7531 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7536 /// \brief Detect whether the mask pattern should be lowered through
7539 /// This essentially tests whether viewing the mask as an interleaving of two
7540 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7541 /// lowering it through interleaving is a significantly better strategy.
7542 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7543 int NumEvenInputs[2] = {0, 0};
7544 int NumOddInputs[2] = {0, 0};
7545 int NumLoInputs[2] = {0, 0};
7546 int NumHiInputs[2] = {0, 0};
7547 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7551 int InputIdx = Mask[i] >= Size;
7554 ++NumLoInputs[InputIdx];
7556 ++NumHiInputs[InputIdx];
7559 ++NumEvenInputs[InputIdx];
7561 ++NumOddInputs[InputIdx];
7564 // The minimum number of cross-input results for both the interleaved and
7565 // split cases. If interleaving results in fewer cross-input results, return
7567 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7568 NumEvenInputs[0] + NumOddInputs[1]);
7569 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7570 NumLoInputs[0] + NumHiInputs[1]);
7571 return InterleavedCrosses < SplitCrosses;
7574 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7576 /// This strategy only works when the inputs from each vector fit into a single
7577 /// half of that vector, and generally there are not so many inputs as to leave
7578 /// the in-place shuffles required highly constrained (and thus expensive). It
7579 /// shifts all the inputs into a single side of both input vectors and then
7580 /// uses an unpack to interleave these inputs in a single vector. At that
7581 /// point, we will fall back on the generic single input shuffle lowering.
7582 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7584 MutableArrayRef<int> Mask,
7585 const X86Subtarget *Subtarget,
7586 SelectionDAG &DAG) {
7587 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7588 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7589 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7590 for (int i = 0; i < 8; ++i)
7591 if (Mask[i] >= 0 && Mask[i] < 4)
7592 LoV1Inputs.push_back(i);
7593 else if (Mask[i] >= 4 && Mask[i] < 8)
7594 HiV1Inputs.push_back(i);
7595 else if (Mask[i] >= 8 && Mask[i] < 12)
7596 LoV2Inputs.push_back(i);
7597 else if (Mask[i] >= 12)
7598 HiV2Inputs.push_back(i);
7600 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7601 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7604 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7605 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7606 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7608 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7609 HiV1Inputs.size() + HiV2Inputs.size();
7611 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7612 ArrayRef<int> HiInputs, bool MoveToLo,
7614 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7615 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7616 if (BadInputs.empty())
7619 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7620 int MoveOffset = MoveToLo ? 0 : 4;
7622 if (GoodInputs.empty()) {
7623 for (int BadInput : BadInputs) {
7624 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7625 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7628 if (GoodInputs.size() == 2) {
7629 // If the low inputs are spread across two dwords, pack them into
7631 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7632 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7633 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7634 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7636 // Otherwise pin the good inputs.
7637 for (int GoodInput : GoodInputs)
7638 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7641 if (BadInputs.size() == 2) {
7642 // If we have two bad inputs then there may be either one or two good
7643 // inputs fixed in place. Find a fixed input, and then find the *other*
7644 // two adjacent indices by using modular arithmetic.
7646 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7647 [](int M) { return M >= 0; }) -
7648 std::begin(MoveMask);
7650 (((GoodMaskIdx - MoveOffset) & ~1) + 2 % 4) + MoveOffset;
7651 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7652 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7653 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7654 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7655 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7656 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7658 assert(BadInputs.size() == 1 && "All sizes handled");
7660 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7661 std::begin(MoveMask);
7662 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7663 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7667 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7670 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7672 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7675 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7676 // cross-half traffic in the final shuffle.
7678 // Munge the mask to be a single-input mask after the unpack merges the
7682 M = 2 * (M % 4) + (M / 8);
7684 return DAG.getVectorShuffle(
7685 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7686 DL, MVT::v8i16, V1, V2),
7687 DAG.getUNDEF(MVT::v8i16), Mask);
7690 /// \brief Generic lowering of 8-lane i16 shuffles.
7692 /// This handles both single-input shuffles and combined shuffle/blends with
7693 /// two inputs. The single input shuffles are immediately delegated to
7694 /// a dedicated lowering routine.
7696 /// The blends are lowered in one of three fundamental ways. If there are few
7697 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7698 /// of the input is significantly cheaper when lowered as an interleaving of
7699 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7700 /// halves of the inputs separately (making them have relatively few inputs)
7701 /// and then concatenate them.
7702 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7703 const X86Subtarget *Subtarget,
7704 SelectionDAG &DAG) {
7706 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7707 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7708 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7709 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7710 ArrayRef<int> OrigMask = SVOp->getMask();
7711 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7712 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7713 MutableArrayRef<int> Mask(MaskStorage);
7715 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7717 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7718 auto isV2 = [](int M) { return M >= 8; };
7720 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7721 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7723 if (NumV2Inputs == 0)
7724 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7726 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7727 "to be V1-input shuffles.");
7729 if (NumV1Inputs + NumV2Inputs <= 4)
7730 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7732 // Check whether an interleaving lowering is likely to be more efficient.
7733 // This isn't perfect but it is a strong heuristic that tends to work well on
7734 // the kinds of shuffles that show up in practice.
7736 // FIXME: Handle 1x, 2x, and 4x interleaving.
7737 if (shouldLowerAsInterleaving(Mask)) {
7738 // FIXME: Figure out whether we should pack these into the low or high
7741 int EMask[8], OMask[8];
7742 for (int i = 0; i < 4; ++i) {
7743 EMask[i] = Mask[2*i];
7744 OMask[i] = Mask[2*i + 1];
7749 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7750 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7752 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7755 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7756 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7758 for (int i = 0; i < 4; ++i) {
7759 LoBlendMask[i] = Mask[i];
7760 HiBlendMask[i] = Mask[i + 4];
7763 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7764 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7765 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7766 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7768 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7769 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7772 /// \brief Check whether a compaction lowering can be done by dropping even
7773 /// elements and compute how many times even elements must be dropped.
7775 /// This handles shuffles which take every Nth element where N is a power of
7776 /// two. Example shuffle masks:
7778 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
7779 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
7780 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
7781 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
7782 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
7783 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
7785 /// Any of these lanes can of course be undef.
7787 /// This routine only supports N <= 3.
7788 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
7791 /// \returns N above, or the number of times even elements must be dropped if
7792 /// there is such a number. Otherwise returns zero.
7793 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
7794 // Figure out whether we're looping over two inputs or just one.
7795 bool IsSingleInput = isSingleInputShuffleMask(Mask);
7797 // The modulus for the shuffle vector entries is based on whether this is
7798 // a single input or not.
7799 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
7800 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
7801 "We should only be called with masks with a power-of-2 size!");
7803 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
7805 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
7806 // and 2^3 simultaneously. This is because we may have ambiguity with
7807 // partially undef inputs.
7808 bool ViableForN[3] = {true, true, true};
7810 for (int i = 0, e = Mask.size(); i < e; ++i) {
7811 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
7816 bool IsAnyViable = false;
7817 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7818 if (ViableForN[j]) {
7821 // The shuffle mask must be equal to (i * 2^N) % M.
7822 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
7825 ViableForN[j] = false;
7827 // Early exit if we exhaust the possible powers of two.
7832 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7836 // Return 0 as there is no viable power of two.
7840 /// \brief Generic lowering of v16i8 shuffles.
7842 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7843 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7844 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7845 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7847 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7848 const X86Subtarget *Subtarget,
7849 SelectionDAG &DAG) {
7851 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7852 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7853 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7854 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7855 ArrayRef<int> OrigMask = SVOp->getMask();
7856 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7857 int MaskStorage[16] = {
7858 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7859 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7860 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7861 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7862 MutableArrayRef<int> Mask(MaskStorage);
7863 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7864 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7866 // For single-input shuffles, there are some nicer lowering tricks we can use.
7867 if (isSingleInputShuffleMask(Mask)) {
7868 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7869 // Notably, this handles splat and partial-splat shuffles more efficiently.
7870 // However, it only makes sense if the pre-duplication shuffle simplifies
7871 // things significantly. Currently, this means we need to be able to
7872 // express the pre-duplication shuffle as an i16 shuffle.
7874 // FIXME: We should check for other patterns which can be widened into an
7875 // i16 shuffle as well.
7876 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7877 for (int i = 0; i < 16; i += 2) {
7878 if (Mask[i] != Mask[i + 1])
7883 auto tryToWidenViaDuplication = [&]() -> SDValue {
7884 if (!canWidenViaDuplication(Mask))
7886 SmallVector<int, 4> LoInputs;
7887 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7888 [](int M) { return M >= 0 && M < 8; });
7889 std::sort(LoInputs.begin(), LoInputs.end());
7890 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7892 SmallVector<int, 4> HiInputs;
7893 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7894 [](int M) { return M >= 8; });
7895 std::sort(HiInputs.begin(), HiInputs.end());
7896 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7899 bool TargetLo = LoInputs.size() >= HiInputs.size();
7900 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7901 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7903 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7904 SmallDenseMap<int, int, 8> LaneMap;
7905 for (int I : InPlaceInputs) {
7906 PreDupI16Shuffle[I/2] = I/2;
7909 int j = TargetLo ? 0 : 4, je = j + 4;
7910 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7911 // Check if j is already a shuffle of this input. This happens when
7912 // there are two adjacent bytes after we move the low one.
7913 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7914 // If we haven't yet mapped the input, search for a slot into which
7916 while (j < je && PreDupI16Shuffle[j] != -1)
7920 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7923 // Map this input with the i16 shuffle.
7924 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7927 // Update the lane map based on the mapping we ended up with.
7928 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7931 ISD::BITCAST, DL, MVT::v16i8,
7932 DAG.getVectorShuffle(MVT::v8i16, DL,
7933 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7934 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7936 // Unpack the bytes to form the i16s that will be shuffled into place.
7937 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7938 MVT::v16i8, V1, V1);
7940 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7941 for (int i = 0; i < 16; i += 2) {
7943 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7944 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7947 ISD::BITCAST, DL, MVT::v16i8,
7948 DAG.getVectorShuffle(MVT::v8i16, DL,
7949 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7950 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7952 if (SDValue V = tryToWidenViaDuplication())
7956 // Check whether an interleaving lowering is likely to be more efficient.
7957 // This isn't perfect but it is a strong heuristic that tends to work well on
7958 // the kinds of shuffles that show up in practice.
7960 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7961 if (shouldLowerAsInterleaving(Mask)) {
7962 // FIXME: Figure out whether we should pack these into the low or high
7965 int EMask[16], OMask[16];
7966 for (int i = 0; i < 8; ++i) {
7967 EMask[i] = Mask[2*i];
7968 OMask[i] = Mask[2*i + 1];
7973 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7974 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7976 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7979 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
7980 // with PSHUFB. It is important to do this before we attempt to generate any
7981 // blends but after all of the single-input lowerings. If the single input
7982 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
7983 // want to preserve that and we can DAG combine any longer sequences into
7984 // a PSHUFB in the end. But once we start blending from multiple inputs,
7985 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
7986 // and there are *very* few patterns that would actually be faster than the
7987 // PSHUFB approach because of its ability to zero lanes.
7989 // FIXME: The only exceptions to the above are blends which are exact
7990 // interleavings with direct instructions supporting them. We currently don't
7991 // handle those well here.
7992 if (Subtarget->hasSSSE3()) {
7995 for (int i = 0; i < 16; ++i)
7996 if (Mask[i] == -1) {
7997 V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
7999 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8001 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8003 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8004 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8005 if (isSingleInputShuffleMask(Mask))
8006 return V1; // Single inputs are easy.
8008 // Otherwise, blend the two.
8009 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8010 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8011 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8014 // Check whether a compaction lowering can be done. This handles shuffles
8015 // which take every Nth element for some even N. See the helper function for
8018 // We special case these as they can be particularly efficiently handled with
8019 // the PACKUSB instruction on x86 and they show up in common patterns of
8020 // rearranging bytes to truncate wide elements.
8021 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8022 // NumEvenDrops is the power of two stride of the elements. Another way of
8023 // thinking about it is that we need to drop the even elements this many
8024 // times to get the original input.
8025 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8027 // First we need to zero all the dropped bytes.
8028 assert(NumEvenDrops <= 3 &&
8029 "No support for dropping even elements more than 3 times.");
8030 // We use the mask type to pick which bytes are preserved based on how many
8031 // elements are dropped.
8032 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8033 SDValue ByteClearMask =
8034 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8035 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8036 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8038 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8040 // Now pack things back together.
8041 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8042 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8043 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8044 for (int i = 1; i < NumEvenDrops; ++i) {
8045 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8046 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8052 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8053 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8054 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8055 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8057 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8058 MutableArrayRef<int> V1HalfBlendMask,
8059 MutableArrayRef<int> V2HalfBlendMask) {
8060 for (int i = 0; i < 8; ++i)
8061 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8062 V1HalfBlendMask[i] = HalfMask[i];
8064 } else if (HalfMask[i] >= 16) {
8065 V2HalfBlendMask[i] = HalfMask[i] - 16;
8066 HalfMask[i] = i + 8;
8069 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8070 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8072 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8074 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8075 MutableArrayRef<int> HiBlendMask) {
8077 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8078 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8080 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8081 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8082 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8083 [](int M) { return M >= 0 && M % 2 == 1; })) {
8084 // Use a mask to drop the high bytes.
8085 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8086 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8087 DAG.getConstant(0x00FF, MVT::v8i16));
8089 // This will be a single vector shuffle instead of a blend so nuke V2.
8090 V2 = DAG.getUNDEF(MVT::v8i16);
8092 // Squash the masks to point directly into V1.
8093 for (int &M : LoBlendMask)
8096 for (int &M : HiBlendMask)
8100 // Otherwise just unpack the low half of V into V1 and the high half into
8101 // V2 so that we can blend them as i16s.
8102 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8103 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8104 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8105 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8108 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8109 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8110 return std::make_pair(BlendedLo, BlendedHi);
8112 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8113 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8114 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8116 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8117 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8119 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8122 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8124 /// This routine breaks down the specific type of 128-bit shuffle and
8125 /// dispatches to the lowering routines accordingly.
8126 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8127 MVT VT, const X86Subtarget *Subtarget,
8128 SelectionDAG &DAG) {
8129 switch (VT.SimpleTy) {
8131 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8133 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8135 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8137 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8139 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8141 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8144 llvm_unreachable("Unimplemented!");
8148 /// \brief Tiny helper function to test whether adjacent masks are sequential.
8149 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
8150 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8151 if (Mask[i] + 1 != Mask[i+1])
8157 /// \brief Top-level lowering for x86 vector shuffles.
8159 /// This handles decomposition, canonicalization, and lowering of all x86
8160 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8161 /// above in helper routines. The canonicalization attempts to widen shuffles
8162 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8163 /// s.t. only one of the two inputs needs to be tested, etc.
8164 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8165 SelectionDAG &DAG) {
8166 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8167 ArrayRef<int> Mask = SVOp->getMask();
8168 SDValue V1 = Op.getOperand(0);
8169 SDValue V2 = Op.getOperand(1);
8170 MVT VT = Op.getSimpleValueType();
8171 int NumElements = VT.getVectorNumElements();
8174 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8176 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8177 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8178 if (V1IsUndef && V2IsUndef)
8179 return DAG.getUNDEF(VT);
8181 // When we create a shuffle node we put the UNDEF node to second operand,
8182 // but in some cases the first operand may be transformed to UNDEF.
8183 // In this case we should just commute the node.
8185 return DAG.getCommutedVectorShuffle(*SVOp);
8187 // Check for non-undef masks pointing at an undef vector and make the masks
8188 // undef as well. This makes it easier to match the shuffle based solely on
8192 if (M >= NumElements) {
8193 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8194 for (int &M : NewMask)
8195 if (M >= NumElements)
8197 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8200 // For integer vector shuffles, try to collapse them into a shuffle of fewer
8201 // lanes but wider integers. We cap this to not form integers larger than i64
8202 // but it might be interesting to form i128 integers to handle flipping the
8203 // low and high halves of AVX 256-bit vectors.
8204 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8205 areAdjacentMasksSequential(Mask)) {
8206 SmallVector<int, 8> NewMask;
8207 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8208 NewMask.push_back(Mask[i] / 2);
8210 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8211 VT.getVectorNumElements() / 2);
8212 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8213 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8214 return DAG.getNode(ISD::BITCAST, dl, VT,
8215 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8218 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8219 for (int M : SVOp->getMask())
8222 else if (M < NumElements)
8227 // Commute the shuffle as needed such that more elements come from V1 than
8228 // V2. This allows us to match the shuffle pattern strictly on how many
8229 // elements come from V1 without handling the symmetric cases.
8230 if (NumV2Elements > NumV1Elements)
8231 return DAG.getCommutedVectorShuffle(*SVOp);
8233 // When the number of V1 and V2 elements are the same, try to minimize the
8234 // number of uses of V2 in the low half of the vector.
8235 if (NumV1Elements == NumV2Elements) {
8236 int LowV1Elements = 0, LowV2Elements = 0;
8237 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8238 if (M >= NumElements)
8242 if (LowV2Elements > LowV1Elements)
8243 return DAG.getCommutedVectorShuffle(*SVOp);
8246 // For each vector width, delegate to a specialized lowering routine.
8247 if (VT.getSizeInBits() == 128)
8248 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8250 llvm_unreachable("Unimplemented!");
8254 //===----------------------------------------------------------------------===//
8255 // Legacy vector shuffle lowering
8257 // This code is the legacy code handling vector shuffles until the above
8258 // replaces its functionality and performance.
8259 //===----------------------------------------------------------------------===//
8261 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8262 bool hasInt256, unsigned *MaskOut = nullptr) {
8263 MVT EltVT = VT.getVectorElementType();
8265 // There is no blend with immediate in AVX-512.
8266 if (VT.is512BitVector())
8269 if (!hasSSE41 || EltVT == MVT::i8)
8271 if (!hasInt256 && VT == MVT::v16i16)
8274 unsigned MaskValue = 0;
8275 unsigned NumElems = VT.getVectorNumElements();
8276 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8277 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8278 unsigned NumElemsInLane = NumElems / NumLanes;
8280 // Blend for v16i16 should be symetric for the both lanes.
8281 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8283 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8284 int EltIdx = MaskVals[i];
8286 if ((EltIdx < 0 || EltIdx == (int)i) &&
8287 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8290 if (((unsigned)EltIdx == (i + NumElems)) &&
8291 (SndLaneEltIdx < 0 ||
8292 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8293 MaskValue |= (1 << i);
8299 *MaskOut = MaskValue;
8303 // Try to lower a shuffle node into a simple blend instruction.
8304 // This function assumes isBlendMask returns true for this
8305 // SuffleVectorSDNode
8306 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8308 const X86Subtarget *Subtarget,
8309 SelectionDAG &DAG) {
8310 MVT VT = SVOp->getSimpleValueType(0);
8311 MVT EltVT = VT.getVectorElementType();
8312 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8313 Subtarget->hasInt256() && "Trying to lower a "
8314 "VECTOR_SHUFFLE to a Blend but "
8315 "with the wrong mask"));
8316 SDValue V1 = SVOp->getOperand(0);
8317 SDValue V2 = SVOp->getOperand(1);
8319 unsigned NumElems = VT.getVectorNumElements();
8321 // Convert i32 vectors to floating point if it is not AVX2.
8322 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8324 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8325 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8327 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8328 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8331 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8332 DAG.getConstant(MaskValue, MVT::i32));
8333 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8336 /// In vector type \p VT, return true if the element at index \p InputIdx
8337 /// falls on a different 128-bit lane than \p OutputIdx.
8338 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8339 unsigned OutputIdx) {
8340 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8341 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8344 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8345 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8346 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8347 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8349 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8350 SelectionDAG &DAG) {
8351 MVT VT = V1.getSimpleValueType();
8352 assert(VT.is128BitVector() || VT.is256BitVector());
8354 MVT EltVT = VT.getVectorElementType();
8355 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8356 unsigned NumElts = VT.getVectorNumElements();
8358 SmallVector<SDValue, 32> PshufbMask;
8359 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8360 int InputIdx = MaskVals[OutputIdx];
8361 unsigned InputByteIdx;
8363 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8364 InputByteIdx = 0x80;
8366 // Cross lane is not allowed.
8367 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8369 InputByteIdx = InputIdx * EltSizeInBytes;
8370 // Index is an byte offset within the 128-bit lane.
8371 InputByteIdx &= 0xf;
8374 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8375 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8376 if (InputByteIdx != 0x80)
8381 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8383 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8384 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8385 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8388 // v8i16 shuffles - Prefer shuffles in the following order:
8389 // 1. [all] pshuflw, pshufhw, optional move
8390 // 2. [ssse3] 1 x pshufb
8391 // 3. [ssse3] 2 x pshufb + 1 x por
8392 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8394 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8395 SelectionDAG &DAG) {
8396 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8397 SDValue V1 = SVOp->getOperand(0);
8398 SDValue V2 = SVOp->getOperand(1);
8400 SmallVector<int, 8> MaskVals;
8402 // Determine if more than 1 of the words in each of the low and high quadwords
8403 // of the result come from the same quadword of one of the two inputs. Undef
8404 // mask values count as coming from any quadword, for better codegen.
8406 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8407 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8408 unsigned LoQuad[] = { 0, 0, 0, 0 };
8409 unsigned HiQuad[] = { 0, 0, 0, 0 };
8410 // Indices of quads used.
8411 std::bitset<4> InputQuads;
8412 for (unsigned i = 0; i < 8; ++i) {
8413 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8414 int EltIdx = SVOp->getMaskElt(i);
8415 MaskVals.push_back(EltIdx);
8424 InputQuads.set(EltIdx / 4);
8427 int BestLoQuad = -1;
8428 unsigned MaxQuad = 1;
8429 for (unsigned i = 0; i < 4; ++i) {
8430 if (LoQuad[i] > MaxQuad) {
8432 MaxQuad = LoQuad[i];
8436 int BestHiQuad = -1;
8438 for (unsigned i = 0; i < 4; ++i) {
8439 if (HiQuad[i] > MaxQuad) {
8441 MaxQuad = HiQuad[i];
8445 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8446 // of the two input vectors, shuffle them into one input vector so only a
8447 // single pshufb instruction is necessary. If there are more than 2 input
8448 // quads, disable the next transformation since it does not help SSSE3.
8449 bool V1Used = InputQuads[0] || InputQuads[1];
8450 bool V2Used = InputQuads[2] || InputQuads[3];
8451 if (Subtarget->hasSSSE3()) {
8452 if (InputQuads.count() == 2 && V1Used && V2Used) {
8453 BestLoQuad = InputQuads[0] ? 0 : 1;
8454 BestHiQuad = InputQuads[2] ? 2 : 3;
8456 if (InputQuads.count() > 2) {
8462 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8463 // the shuffle mask. If a quad is scored as -1, that means that it contains
8464 // words from all 4 input quadwords.
8466 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8468 BestLoQuad < 0 ? 0 : BestLoQuad,
8469 BestHiQuad < 0 ? 1 : BestHiQuad
8471 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8472 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8473 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8474 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8476 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8477 // source words for the shuffle, to aid later transformations.
8478 bool AllWordsInNewV = true;
8479 bool InOrder[2] = { true, true };
8480 for (unsigned i = 0; i != 8; ++i) {
8481 int idx = MaskVals[i];
8483 InOrder[i/4] = false;
8484 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8486 AllWordsInNewV = false;
8490 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8491 if (AllWordsInNewV) {
8492 for (int i = 0; i != 8; ++i) {
8493 int idx = MaskVals[i];
8496 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8497 if ((idx != i) && idx < 4)
8499 if ((idx != i) && idx > 3)
8508 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8509 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8510 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8511 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8512 unsigned TargetMask = 0;
8513 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8514 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8515 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8516 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8517 getShufflePSHUFLWImmediate(SVOp);
8518 V1 = NewV.getOperand(0);
8519 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8523 // Promote splats to a larger type which usually leads to more efficient code.
8524 // FIXME: Is this true if pshufb is available?
8525 if (SVOp->isSplat())
8526 return PromoteSplat(SVOp, DAG);
8528 // If we have SSSE3, and all words of the result are from 1 input vector,
8529 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8530 // is present, fall back to case 4.
8531 if (Subtarget->hasSSSE3()) {
8532 SmallVector<SDValue,16> pshufbMask;
8534 // If we have elements from both input vectors, set the high bit of the
8535 // shuffle mask element to zero out elements that come from V2 in the V1
8536 // mask, and elements that come from V1 in the V2 mask, so that the two
8537 // results can be OR'd together.
8538 bool TwoInputs = V1Used && V2Used;
8539 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8541 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8543 // Calculate the shuffle mask for the second input, shuffle it, and
8544 // OR it with the first shuffled input.
8545 CommuteVectorShuffleMask(MaskVals, 8);
8546 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8547 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8548 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8551 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8552 // and update MaskVals with new element order.
8553 std::bitset<8> InOrder;
8554 if (BestLoQuad >= 0) {
8555 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8556 for (int i = 0; i != 4; ++i) {
8557 int idx = MaskVals[i];
8560 } else if ((idx / 4) == BestLoQuad) {
8565 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8568 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8569 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8570 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8572 getShufflePSHUFLWImmediate(SVOp), DAG);
8576 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8577 // and update MaskVals with the new element order.
8578 if (BestHiQuad >= 0) {
8579 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8580 for (unsigned i = 4; i != 8; ++i) {
8581 int idx = MaskVals[i];
8584 } else if ((idx / 4) == BestHiQuad) {
8585 MaskV[i] = (idx & 3) + 4;
8589 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8592 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8593 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8594 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8596 getShufflePSHUFHWImmediate(SVOp), DAG);
8600 // In case BestHi & BestLo were both -1, which means each quadword has a word
8601 // from each of the four input quadwords, calculate the InOrder bitvector now
8602 // before falling through to the insert/extract cleanup.
8603 if (BestLoQuad == -1 && BestHiQuad == -1) {
8605 for (int i = 0; i != 8; ++i)
8606 if (MaskVals[i] < 0 || MaskVals[i] == i)
8610 // The other elements are put in the right place using pextrw and pinsrw.
8611 for (unsigned i = 0; i != 8; ++i) {
8614 int EltIdx = MaskVals[i];
8617 SDValue ExtOp = (EltIdx < 8) ?
8618 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8619 DAG.getIntPtrConstant(EltIdx)) :
8620 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8621 DAG.getIntPtrConstant(EltIdx - 8));
8622 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8623 DAG.getIntPtrConstant(i));
8628 /// \brief v16i16 shuffles
8630 /// FIXME: We only support generation of a single pshufb currently. We can
8631 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8632 /// well (e.g 2 x pshufb + 1 x por).
8634 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8635 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8636 SDValue V1 = SVOp->getOperand(0);
8637 SDValue V2 = SVOp->getOperand(1);
8640 if (V2.getOpcode() != ISD::UNDEF)
8643 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8644 return getPSHUFB(MaskVals, V1, dl, DAG);
8647 // v16i8 shuffles - Prefer shuffles in the following order:
8648 // 1. [ssse3] 1 x pshufb
8649 // 2. [ssse3] 2 x pshufb + 1 x por
8650 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8651 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8652 const X86Subtarget* Subtarget,
8653 SelectionDAG &DAG) {
8654 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8655 SDValue V1 = SVOp->getOperand(0);
8656 SDValue V2 = SVOp->getOperand(1);
8658 ArrayRef<int> MaskVals = SVOp->getMask();
8660 // Promote splats to a larger type which usually leads to more efficient code.
8661 // FIXME: Is this true if pshufb is available?
8662 if (SVOp->isSplat())
8663 return PromoteSplat(SVOp, DAG);
8665 // If we have SSSE3, case 1 is generated when all result bytes come from
8666 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8667 // present, fall back to case 3.
8669 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8670 if (Subtarget->hasSSSE3()) {
8671 SmallVector<SDValue,16> pshufbMask;
8673 // If all result elements are from one input vector, then only translate
8674 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8676 // Otherwise, we have elements from both input vectors, and must zero out
8677 // elements that come from V2 in the first mask, and V1 in the second mask
8678 // so that we can OR them together.
8679 for (unsigned i = 0; i != 16; ++i) {
8680 int EltIdx = MaskVals[i];
8681 if (EltIdx < 0 || EltIdx >= 16)
8683 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8685 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8686 DAG.getNode(ISD::BUILD_VECTOR, dl,
8687 MVT::v16i8, pshufbMask));
8689 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8690 // the 2nd operand if it's undefined or zero.
8691 if (V2.getOpcode() == ISD::UNDEF ||
8692 ISD::isBuildVectorAllZeros(V2.getNode()))
8695 // Calculate the shuffle mask for the second input, shuffle it, and
8696 // OR it with the first shuffled input.
8698 for (unsigned i = 0; i != 16; ++i) {
8699 int EltIdx = MaskVals[i];
8700 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8701 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8703 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8704 DAG.getNode(ISD::BUILD_VECTOR, dl,
8705 MVT::v16i8, pshufbMask));
8706 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8709 // No SSSE3 - Calculate in place words and then fix all out of place words
8710 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8711 // the 16 different words that comprise the two doublequadword input vectors.
8712 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8713 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8715 for (int i = 0; i != 8; ++i) {
8716 int Elt0 = MaskVals[i*2];
8717 int Elt1 = MaskVals[i*2+1];
8719 // This word of the result is all undef, skip it.
8720 if (Elt0 < 0 && Elt1 < 0)
8723 // This word of the result is already in the correct place, skip it.
8724 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8727 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8728 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8731 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8732 // using a single extract together, load it and store it.
8733 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8734 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8735 DAG.getIntPtrConstant(Elt1 / 2));
8736 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8737 DAG.getIntPtrConstant(i));
8741 // If Elt1 is defined, extract it from the appropriate source. If the
8742 // source byte is not also odd, shift the extracted word left 8 bits
8743 // otherwise clear the bottom 8 bits if we need to do an or.
8745 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8746 DAG.getIntPtrConstant(Elt1 / 2));
8747 if ((Elt1 & 1) == 0)
8748 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8750 TLI.getShiftAmountTy(InsElt.getValueType())));
8752 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8753 DAG.getConstant(0xFF00, MVT::i16));
8755 // If Elt0 is defined, extract it from the appropriate source. If the
8756 // source byte is not also even, shift the extracted word right 8 bits. If
8757 // Elt1 was also defined, OR the extracted values together before
8758 // inserting them in the result.
8760 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8761 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8762 if ((Elt0 & 1) != 0)
8763 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8765 TLI.getShiftAmountTy(InsElt0.getValueType())));
8767 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8768 DAG.getConstant(0x00FF, MVT::i16));
8769 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8772 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8773 DAG.getIntPtrConstant(i));
8775 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8778 // v32i8 shuffles - Translate to VPSHUFB if possible.
8780 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8781 const X86Subtarget *Subtarget,
8782 SelectionDAG &DAG) {
8783 MVT VT = SVOp->getSimpleValueType(0);
8784 SDValue V1 = SVOp->getOperand(0);
8785 SDValue V2 = SVOp->getOperand(1);
8787 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8789 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8790 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8791 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8793 // VPSHUFB may be generated if
8794 // (1) one of input vector is undefined or zeroinitializer.
8795 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8796 // And (2) the mask indexes don't cross the 128-bit lane.
8797 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8798 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8801 if (V1IsAllZero && !V2IsAllZero) {
8802 CommuteVectorShuffleMask(MaskVals, 32);
8805 return getPSHUFB(MaskVals, V1, dl, DAG);
8808 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8809 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8810 /// done when every pair / quad of shuffle mask elements point to elements in
8811 /// the right sequence. e.g.
8812 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8814 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8815 SelectionDAG &DAG) {
8816 MVT VT = SVOp->getSimpleValueType(0);
8818 unsigned NumElems = VT.getVectorNumElements();
8821 switch (VT.SimpleTy) {
8822 default: llvm_unreachable("Unexpected!");
8825 return SDValue(SVOp, 0);
8826 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8827 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8828 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8829 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8830 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8831 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8834 SmallVector<int, 8> MaskVec;
8835 for (unsigned i = 0; i != NumElems; i += Scale) {
8837 for (unsigned j = 0; j != Scale; ++j) {
8838 int EltIdx = SVOp->getMaskElt(i+j);
8842 StartIdx = (EltIdx / Scale);
8843 if (EltIdx != (int)(StartIdx*Scale + j))
8846 MaskVec.push_back(StartIdx);
8849 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8850 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8851 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8854 /// getVZextMovL - Return a zero-extending vector move low node.
8856 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8857 SDValue SrcOp, SelectionDAG &DAG,
8858 const X86Subtarget *Subtarget, SDLoc dl) {
8859 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8860 LoadSDNode *LD = nullptr;
8861 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8862 LD = dyn_cast<LoadSDNode>(SrcOp);
8864 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8866 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8867 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8868 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8869 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8870 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8872 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8873 return DAG.getNode(ISD::BITCAST, dl, VT,
8874 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8875 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8883 return DAG.getNode(ISD::BITCAST, dl, VT,
8884 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8885 DAG.getNode(ISD::BITCAST, dl,
8889 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8890 /// which could not be matched by any known target speficic shuffle
8892 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8894 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8895 if (NewOp.getNode())
8898 MVT VT = SVOp->getSimpleValueType(0);
8900 unsigned NumElems = VT.getVectorNumElements();
8901 unsigned NumLaneElems = NumElems / 2;
8904 MVT EltVT = VT.getVectorElementType();
8905 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8908 SmallVector<int, 16> Mask;
8909 for (unsigned l = 0; l < 2; ++l) {
8910 // Build a shuffle mask for the output, discovering on the fly which
8911 // input vectors to use as shuffle operands (recorded in InputUsed).
8912 // If building a suitable shuffle vector proves too hard, then bail
8913 // out with UseBuildVector set.
8914 bool UseBuildVector = false;
8915 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8916 unsigned LaneStart = l * NumLaneElems;
8917 for (unsigned i = 0; i != NumLaneElems; ++i) {
8918 // The mask element. This indexes into the input.
8919 int Idx = SVOp->getMaskElt(i+LaneStart);
8921 // the mask element does not index into any input vector.
8926 // The input vector this mask element indexes into.
8927 int Input = Idx / NumLaneElems;
8929 // Turn the index into an offset from the start of the input vector.
8930 Idx -= Input * NumLaneElems;
8932 // Find or create a shuffle vector operand to hold this input.
8934 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8935 if (InputUsed[OpNo] == Input)
8936 // This input vector is already an operand.
8938 if (InputUsed[OpNo] < 0) {
8939 // Create a new operand for this input vector.
8940 InputUsed[OpNo] = Input;
8945 if (OpNo >= array_lengthof(InputUsed)) {
8946 // More than two input vectors used! Give up on trying to create a
8947 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8948 UseBuildVector = true;
8952 // Add the mask index for the new shuffle vector.
8953 Mask.push_back(Idx + OpNo * NumLaneElems);
8956 if (UseBuildVector) {
8957 SmallVector<SDValue, 16> SVOps;
8958 for (unsigned i = 0; i != NumLaneElems; ++i) {
8959 // The mask element. This indexes into the input.
8960 int Idx = SVOp->getMaskElt(i+LaneStart);
8962 SVOps.push_back(DAG.getUNDEF(EltVT));
8966 // The input vector this mask element indexes into.
8967 int Input = Idx / NumElems;
8969 // Turn the index into an offset from the start of the input vector.
8970 Idx -= Input * NumElems;
8972 // Extract the vector element by hand.
8973 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8974 SVOp->getOperand(Input),
8975 DAG.getIntPtrConstant(Idx)));
8978 // Construct the output using a BUILD_VECTOR.
8979 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8980 } else if (InputUsed[0] < 0) {
8981 // No input vectors were used! The result is undefined.
8982 Output[l] = DAG.getUNDEF(NVT);
8984 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8985 (InputUsed[0] % 2) * NumLaneElems,
8987 // If only one input was used, use an undefined vector for the other.
8988 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8989 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8990 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8991 // At least one input vector was used. Create a new shuffle vector.
8992 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8998 // Concatenate the result back
8999 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9002 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9003 /// 4 elements, and match them with several different shuffle types.
9005 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9006 SDValue V1 = SVOp->getOperand(0);
9007 SDValue V2 = SVOp->getOperand(1);
9009 MVT VT = SVOp->getSimpleValueType(0);
9011 assert(VT.is128BitVector() && "Unsupported vector size");
9013 std::pair<int, int> Locs[4];
9014 int Mask1[] = { -1, -1, -1, -1 };
9015 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9019 for (unsigned i = 0; i != 4; ++i) {
9020 int Idx = PermMask[i];
9022 Locs[i] = std::make_pair(-1, -1);
9024 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9026 Locs[i] = std::make_pair(0, NumLo);
9030 Locs[i] = std::make_pair(1, NumHi);
9032 Mask1[2+NumHi] = Idx;
9038 if (NumLo <= 2 && NumHi <= 2) {
9039 // If no more than two elements come from either vector. This can be
9040 // implemented with two shuffles. First shuffle gather the elements.
9041 // The second shuffle, which takes the first shuffle as both of its
9042 // vector operands, put the elements into the right order.
9043 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9045 int Mask2[] = { -1, -1, -1, -1 };
9047 for (unsigned i = 0; i != 4; ++i)
9048 if (Locs[i].first != -1) {
9049 unsigned Idx = (i < 2) ? 0 : 4;
9050 Idx += Locs[i].first * 2 + Locs[i].second;
9054 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9057 if (NumLo == 3 || NumHi == 3) {
9058 // Otherwise, we must have three elements from one vector, call it X, and
9059 // one element from the other, call it Y. First, use a shufps to build an
9060 // intermediate vector with the one element from Y and the element from X
9061 // that will be in the same half in the final destination (the indexes don't
9062 // matter). Then, use a shufps to build the final vector, taking the half
9063 // containing the element from Y from the intermediate, and the other half
9066 // Normalize it so the 3 elements come from V1.
9067 CommuteVectorShuffleMask(PermMask, 4);
9071 // Find the element from V2.
9073 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9074 int Val = PermMask[HiIndex];
9081 Mask1[0] = PermMask[HiIndex];
9083 Mask1[2] = PermMask[HiIndex^1];
9085 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9088 Mask1[0] = PermMask[0];
9089 Mask1[1] = PermMask[1];
9090 Mask1[2] = HiIndex & 1 ? 6 : 4;
9091 Mask1[3] = HiIndex & 1 ? 4 : 6;
9092 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9095 Mask1[0] = HiIndex & 1 ? 2 : 0;
9096 Mask1[1] = HiIndex & 1 ? 0 : 2;
9097 Mask1[2] = PermMask[2];
9098 Mask1[3] = PermMask[3];
9103 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9106 // Break it into (shuffle shuffle_hi, shuffle_lo).
9107 int LoMask[] = { -1, -1, -1, -1 };
9108 int HiMask[] = { -1, -1, -1, -1 };
9110 int *MaskPtr = LoMask;
9111 unsigned MaskIdx = 0;
9114 for (unsigned i = 0; i != 4; ++i) {
9121 int Idx = PermMask[i];
9123 Locs[i] = std::make_pair(-1, -1);
9124 } else if (Idx < 4) {
9125 Locs[i] = std::make_pair(MaskIdx, LoIdx);
9126 MaskPtr[LoIdx] = Idx;
9129 Locs[i] = std::make_pair(MaskIdx, HiIdx);
9130 MaskPtr[HiIdx] = Idx;
9135 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9136 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9137 int MaskOps[] = { -1, -1, -1, -1 };
9138 for (unsigned i = 0; i != 4; ++i)
9139 if (Locs[i].first != -1)
9140 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9141 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9144 static bool MayFoldVectorLoad(SDValue V) {
9145 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9146 V = V.getOperand(0);
9148 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9149 V = V.getOperand(0);
9150 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9151 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9152 // BUILD_VECTOR (load), undef
9153 V = V.getOperand(0);
9155 return MayFoldLoad(V);
9159 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9160 MVT VT = Op.getSimpleValueType();
9162 // Canonizalize to v2f64.
9163 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9164 return DAG.getNode(ISD::BITCAST, dl, VT,
9165 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9170 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9172 SDValue V1 = Op.getOperand(0);
9173 SDValue V2 = Op.getOperand(1);
9174 MVT VT = Op.getSimpleValueType();
9176 assert(VT != MVT::v2i64 && "unsupported shuffle type");
9178 if (HasSSE2 && VT == MVT::v2f64)
9179 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9181 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9182 return DAG.getNode(ISD::BITCAST, dl, VT,
9183 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9184 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9185 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9189 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9190 SDValue V1 = Op.getOperand(0);
9191 SDValue V2 = Op.getOperand(1);
9192 MVT VT = Op.getSimpleValueType();
9194 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9195 "unsupported shuffle type");
9197 if (V2.getOpcode() == ISD::UNDEF)
9201 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9205 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9206 SDValue V1 = Op.getOperand(0);
9207 SDValue V2 = Op.getOperand(1);
9208 MVT VT = Op.getSimpleValueType();
9209 unsigned NumElems = VT.getVectorNumElements();
9211 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9212 // operand of these instructions is only memory, so check if there's a
9213 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9215 bool CanFoldLoad = false;
9217 // Trivial case, when V2 comes from a load.
9218 if (MayFoldVectorLoad(V2))
9221 // When V1 is a load, it can be folded later into a store in isel, example:
9222 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9224 // (MOVLPSmr addr:$src1, VR128:$src2)
9225 // So, recognize this potential and also use MOVLPS or MOVLPD
9226 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9229 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9231 if (HasSSE2 && NumElems == 2)
9232 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9235 // If we don't care about the second element, proceed to use movss.
9236 if (SVOp->getMaskElt(1) != -1)
9237 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9240 // movl and movlp will both match v2i64, but v2i64 is never matched by
9241 // movl earlier because we make it strict to avoid messing with the movlp load
9242 // folding logic (see the code above getMOVLP call). Match it here then,
9243 // this is horrible, but will stay like this until we move all shuffle
9244 // matching to x86 specific nodes. Note that for the 1st condition all
9245 // types are matched with movsd.
9247 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9248 // as to remove this logic from here, as much as possible
9249 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9250 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9251 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9254 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9256 // Invert the operand order and use SHUFPS to match it.
9257 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9258 getShuffleSHUFImmediate(SVOp), DAG);
9261 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9262 SelectionDAG &DAG) {
9264 MVT VT = Load->getSimpleValueType(0);
9265 MVT EVT = VT.getVectorElementType();
9266 SDValue Addr = Load->getOperand(1);
9267 SDValue NewAddr = DAG.getNode(
9268 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9269 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9272 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9273 DAG.getMachineFunction().getMachineMemOperand(
9274 Load->getMemOperand(), 0, EVT.getStoreSize()));
9278 // It is only safe to call this function if isINSERTPSMask is true for
9279 // this shufflevector mask.
9280 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9281 SelectionDAG &DAG) {
9282 // Generate an insertps instruction when inserting an f32 from memory onto a
9283 // v4f32 or when copying a member from one v4f32 to another.
9284 // We also use it for transferring i32 from one register to another,
9285 // since it simply copies the same bits.
9286 // If we're transferring an i32 from memory to a specific element in a
9287 // register, we output a generic DAG that will match the PINSRD
9289 MVT VT = SVOp->getSimpleValueType(0);
9290 MVT EVT = VT.getVectorElementType();
9291 SDValue V1 = SVOp->getOperand(0);
9292 SDValue V2 = SVOp->getOperand(1);
9293 auto Mask = SVOp->getMask();
9294 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9295 "unsupported vector type for insertps/pinsrd");
9297 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9298 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9299 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9307 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9310 // If we have 1 element from each vector, we have to check if we're
9311 // changing V1's element's place. If so, we're done. Otherwise, we
9312 // should assume we're changing V2's element's place and behave
9314 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9315 assert(DestIndex <= INT32_MAX && "truncated destination index");
9316 if (FromV1 == FromV2 &&
9317 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9321 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9324 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9325 "More than one element from V1 and from V2, or no elements from one "
9326 "of the vectors. This case should not have returned true from "
9331 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9334 // Get an index into the source vector in the range [0,4) (the mask is
9335 // in the range [0,8) because it can address V1 and V2)
9336 unsigned SrcIndex = Mask[DestIndex] % 4;
9337 if (MayFoldLoad(From)) {
9338 // Trivial case, when From comes from a load and is only used by the
9339 // shuffle. Make it use insertps from the vector that we need from that
9342 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9343 if (!NewLoad.getNode())
9346 if (EVT == MVT::f32) {
9347 // Create this as a scalar to vector to match the instruction pattern.
9348 SDValue LoadScalarToVector =
9349 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9350 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9351 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9353 } else { // EVT == MVT::i32
9354 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9355 // instruction, to match the PINSRD instruction, which loads an i32 to a
9356 // certain vector element.
9357 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9358 DAG.getConstant(DestIndex, MVT::i32));
9362 // Vector-element-to-vector
9363 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9364 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9367 // Reduce a vector shuffle to zext.
9368 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9369 SelectionDAG &DAG) {
9370 // PMOVZX is only available from SSE41.
9371 if (!Subtarget->hasSSE41())
9374 MVT VT = Op.getSimpleValueType();
9376 // Only AVX2 support 256-bit vector integer extending.
9377 if (!Subtarget->hasInt256() && VT.is256BitVector())
9380 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9382 SDValue V1 = Op.getOperand(0);
9383 SDValue V2 = Op.getOperand(1);
9384 unsigned NumElems = VT.getVectorNumElements();
9386 // Extending is an unary operation and the element type of the source vector
9387 // won't be equal to or larger than i64.
9388 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9389 VT.getVectorElementType() == MVT::i64)
9392 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9393 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9394 while ((1U << Shift) < NumElems) {
9395 if (SVOp->getMaskElt(1U << Shift) == 1)
9398 // The maximal ratio is 8, i.e. from i8 to i64.
9403 // Check the shuffle mask.
9404 unsigned Mask = (1U << Shift) - 1;
9405 for (unsigned i = 0; i != NumElems; ++i) {
9406 int EltIdx = SVOp->getMaskElt(i);
9407 if ((i & Mask) != 0 && EltIdx != -1)
9409 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9413 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9414 MVT NeVT = MVT::getIntegerVT(NBits);
9415 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9417 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9420 // Simplify the operand as it's prepared to be fed into shuffle.
9421 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9422 if (V1.getOpcode() == ISD::BITCAST &&
9423 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9424 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9425 V1.getOperand(0).getOperand(0)
9426 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9427 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9428 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9429 ConstantSDNode *CIdx =
9430 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9431 // If it's foldable, i.e. normal load with single use, we will let code
9432 // selection to fold it. Otherwise, we will short the conversion sequence.
9433 if (CIdx && CIdx->getZExtValue() == 0 &&
9434 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9435 MVT FullVT = V.getSimpleValueType();
9436 MVT V1VT = V1.getSimpleValueType();
9437 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9438 // The "ext_vec_elt" node is wider than the result node.
9439 // In this case we should extract subvector from V.
9440 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9441 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9442 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9443 FullVT.getVectorNumElements()/Ratio);
9444 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9445 DAG.getIntPtrConstant(0));
9447 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9451 return DAG.getNode(ISD::BITCAST, DL, VT,
9452 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9455 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9456 SelectionDAG &DAG) {
9457 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9458 MVT VT = Op.getSimpleValueType();
9460 SDValue V1 = Op.getOperand(0);
9461 SDValue V2 = Op.getOperand(1);
9463 if (isZeroShuffle(SVOp))
9464 return getZeroVector(VT, Subtarget, DAG, dl);
9466 // Handle splat operations
9467 if (SVOp->isSplat()) {
9468 // Use vbroadcast whenever the splat comes from a foldable load
9469 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9470 if (Broadcast.getNode())
9474 // Check integer expanding shuffles.
9475 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9476 if (NewOp.getNode())
9479 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9481 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9483 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9484 if (NewOp.getNode())
9485 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9486 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9487 // FIXME: Figure out a cleaner way to do this.
9488 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9489 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9490 if (NewOp.getNode()) {
9491 MVT NewVT = NewOp.getSimpleValueType();
9492 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9493 NewVT, true, false))
9494 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9497 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9498 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9499 if (NewOp.getNode()) {
9500 MVT NewVT = NewOp.getSimpleValueType();
9501 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9502 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9511 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9512 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9513 SDValue V1 = Op.getOperand(0);
9514 SDValue V2 = Op.getOperand(1);
9515 MVT VT = Op.getSimpleValueType();
9517 unsigned NumElems = VT.getVectorNumElements();
9518 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9519 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9520 bool V1IsSplat = false;
9521 bool V2IsSplat = false;
9522 bool HasSSE2 = Subtarget->hasSSE2();
9523 bool HasFp256 = Subtarget->hasFp256();
9524 bool HasInt256 = Subtarget->hasInt256();
9525 MachineFunction &MF = DAG.getMachineFunction();
9526 bool OptForSize = MF.getFunction()->getAttributes().
9527 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9529 // Check if we should use the experimental vector shuffle lowering. If so,
9530 // delegate completely to that code path.
9531 if (ExperimentalVectorShuffleLowering)
9532 return lowerVectorShuffle(Op, Subtarget, DAG);
9534 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9536 if (V1IsUndef && V2IsUndef)
9537 return DAG.getUNDEF(VT);
9539 // When we create a shuffle node we put the UNDEF node to second operand,
9540 // but in some cases the first operand may be transformed to UNDEF.
9541 // In this case we should just commute the node.
9543 return DAG.getCommutedVectorShuffle(*SVOp);
9545 // Vector shuffle lowering takes 3 steps:
9547 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9548 // narrowing and commutation of operands should be handled.
9549 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9551 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9552 // so the shuffle can be broken into other shuffles and the legalizer can
9553 // try the lowering again.
9555 // The general idea is that no vector_shuffle operation should be left to
9556 // be matched during isel, all of them must be converted to a target specific
9559 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9560 // narrowing and commutation of operands should be handled. The actual code
9561 // doesn't include all of those, work in progress...
9562 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9563 if (NewOp.getNode())
9566 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9568 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9569 // unpckh_undef). Only use pshufd if speed is more important than size.
9570 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9571 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9572 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9573 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9575 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9576 V2IsUndef && MayFoldVectorLoad(V1))
9577 return getMOVDDup(Op, dl, V1, DAG);
9579 if (isMOVHLPS_v_undef_Mask(M, VT))
9580 return getMOVHighToLow(Op, dl, DAG);
9582 // Use to match splats
9583 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9584 (VT == MVT::v2f64 || VT == MVT::v2i64))
9585 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9587 if (isPSHUFDMask(M, VT)) {
9588 // The actual implementation will match the mask in the if above and then
9589 // during isel it can match several different instructions, not only pshufd
9590 // as its name says, sad but true, emulate the behavior for now...
9591 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9592 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9594 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9596 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9597 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9599 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9600 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9603 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9607 if (isPALIGNRMask(M, VT, Subtarget))
9608 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9609 getShufflePALIGNRImmediate(SVOp),
9612 // Check if this can be converted into a logical shift.
9613 bool isLeft = false;
9616 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9617 if (isShift && ShVal.hasOneUse()) {
9618 // If the shifted value has multiple uses, it may be cheaper to use
9619 // v_set0 + movlhps or movhlps, etc.
9620 MVT EltVT = VT.getVectorElementType();
9621 ShAmt *= EltVT.getSizeInBits();
9622 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9625 if (isMOVLMask(M, VT)) {
9626 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9627 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9628 if (!isMOVLPMask(M, VT)) {
9629 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9630 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9632 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9633 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9637 // FIXME: fold these into legal mask.
9638 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9639 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9641 if (isMOVHLPSMask(M, VT))
9642 return getMOVHighToLow(Op, dl, DAG);
9644 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9645 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9647 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9648 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9650 if (isMOVLPMask(M, VT))
9651 return getMOVLP(Op, dl, DAG, HasSSE2);
9653 if (ShouldXformToMOVHLPS(M, VT) ||
9654 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9655 return DAG.getCommutedVectorShuffle(*SVOp);
9658 // No better options. Use a vshldq / vsrldq.
9659 MVT EltVT = VT.getVectorElementType();
9660 ShAmt *= EltVT.getSizeInBits();
9661 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9664 bool Commuted = false;
9665 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9666 // 1,1,1,1 -> v8i16 though.
9667 BitVector UndefElements;
9668 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9669 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9671 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9672 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9675 // Canonicalize the splat or undef, if present, to be on the RHS.
9676 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9677 CommuteVectorShuffleMask(M, NumElems);
9679 std::swap(V1IsSplat, V2IsSplat);
9683 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9684 // Shuffling low element of v1 into undef, just return v1.
9687 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9688 // the instruction selector will not match, so get a canonical MOVL with
9689 // swapped operands to undo the commute.
9690 return getMOVL(DAG, dl, VT, V2, V1);
9693 if (isUNPCKLMask(M, VT, HasInt256))
9694 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9696 if (isUNPCKHMask(M, VT, HasInt256))
9697 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9700 // Normalize mask so all entries that point to V2 points to its first
9701 // element then try to match unpck{h|l} again. If match, return a
9702 // new vector_shuffle with the corrected mask.p
9703 SmallVector<int, 8> NewMask(M.begin(), M.end());
9704 NormalizeMask(NewMask, NumElems);
9705 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9706 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9707 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9708 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9712 // Commute is back and try unpck* again.
9713 // FIXME: this seems wrong.
9714 CommuteVectorShuffleMask(M, NumElems);
9716 std::swap(V1IsSplat, V2IsSplat);
9718 if (isUNPCKLMask(M, VT, HasInt256))
9719 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9721 if (isUNPCKHMask(M, VT, HasInt256))
9722 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9725 // Normalize the node to match x86 shuffle ops if needed
9726 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9727 return DAG.getCommutedVectorShuffle(*SVOp);
9729 // The checks below are all present in isShuffleMaskLegal, but they are
9730 // inlined here right now to enable us to directly emit target specific
9731 // nodes, and remove one by one until they don't return Op anymore.
9733 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9734 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9735 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9736 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9739 if (isPSHUFHWMask(M, VT, HasInt256))
9740 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9741 getShufflePSHUFHWImmediate(SVOp),
9744 if (isPSHUFLWMask(M, VT, HasInt256))
9745 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9746 getShufflePSHUFLWImmediate(SVOp),
9750 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9752 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9754 if (isSHUFPMask(M, VT))
9755 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9756 getShuffleSHUFImmediate(SVOp), DAG);
9758 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9759 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9760 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9761 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9763 //===--------------------------------------------------------------------===//
9764 // Generate target specific nodes for 128 or 256-bit shuffles only
9765 // supported in the AVX instruction set.
9768 // Handle VMOVDDUPY permutations
9769 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9770 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9772 // Handle VPERMILPS/D* permutations
9773 if (isVPERMILPMask(M, VT)) {
9774 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9775 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9776 getShuffleSHUFImmediate(SVOp), DAG);
9777 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9778 getShuffleSHUFImmediate(SVOp), DAG);
9782 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9783 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9784 Idx*(NumElems/2), DAG, dl);
9786 // Handle VPERM2F128/VPERM2I128 permutations
9787 if (isVPERM2X128Mask(M, VT, HasFp256))
9788 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9789 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9791 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9792 return getINSERTPS(SVOp, dl, DAG);
9795 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9796 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9798 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9799 VT.is512BitVector()) {
9800 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9801 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9802 SmallVector<SDValue, 16> permclMask;
9803 for (unsigned i = 0; i != NumElems; ++i) {
9804 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9807 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9809 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9810 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9811 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9812 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9813 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9816 //===--------------------------------------------------------------------===//
9817 // Since no target specific shuffle was selected for this generic one,
9818 // lower it into other known shuffles. FIXME: this isn't true yet, but
9819 // this is the plan.
9822 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9823 if (VT == MVT::v8i16) {
9824 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9825 if (NewOp.getNode())
9829 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9830 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9831 if (NewOp.getNode())
9835 if (VT == MVT::v16i8) {
9836 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9837 if (NewOp.getNode())
9841 if (VT == MVT::v32i8) {
9842 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9843 if (NewOp.getNode())
9847 // Handle all 128-bit wide vectors with 4 elements, and match them with
9848 // several different shuffle types.
9849 if (NumElems == 4 && VT.is128BitVector())
9850 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9852 // Handle general 256-bit shuffles
9853 if (VT.is256BitVector())
9854 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9859 // This function assumes its argument is a BUILD_VECTOR of constants or
9860 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9862 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9863 unsigned &MaskValue) {
9865 unsigned NumElems = BuildVector->getNumOperands();
9866 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9867 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9868 unsigned NumElemsInLane = NumElems / NumLanes;
9870 // Blend for v16i16 should be symetric for the both lanes.
9871 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9872 SDValue EltCond = BuildVector->getOperand(i);
9873 SDValue SndLaneEltCond =
9874 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9876 int Lane1Cond = -1, Lane2Cond = -1;
9877 if (isa<ConstantSDNode>(EltCond))
9878 Lane1Cond = !isZero(EltCond);
9879 if (isa<ConstantSDNode>(SndLaneEltCond))
9880 Lane2Cond = !isZero(SndLaneEltCond);
9882 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9883 // Lane1Cond != 0, means we want the first argument.
9884 // Lane1Cond == 0, means we want the second argument.
9885 // The encoding of this argument is 0 for the first argument, 1
9886 // for the second. Therefore, invert the condition.
9887 MaskValue |= !Lane1Cond << i;
9888 else if (Lane1Cond < 0)
9889 MaskValue |= !Lane2Cond << i;
9896 // Try to lower a vselect node into a simple blend instruction.
9897 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9898 SelectionDAG &DAG) {
9899 SDValue Cond = Op.getOperand(0);
9900 SDValue LHS = Op.getOperand(1);
9901 SDValue RHS = Op.getOperand(2);
9903 MVT VT = Op.getSimpleValueType();
9904 MVT EltVT = VT.getVectorElementType();
9905 unsigned NumElems = VT.getVectorNumElements();
9907 // There is no blend with immediate in AVX-512.
9908 if (VT.is512BitVector())
9911 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9913 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9916 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9919 // Check the mask for BLEND and build the value.
9920 unsigned MaskValue = 0;
9921 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9924 // Convert i32 vectors to floating point if it is not AVX2.
9925 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9927 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9928 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9930 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9931 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9934 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9935 DAG.getConstant(MaskValue, MVT::i32));
9936 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9939 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9940 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9941 if (BlendOp.getNode())
9944 // Some types for vselect were previously set to Expand, not Legal or
9945 // Custom. Return an empty SDValue so we fall-through to Expand, after
9946 // the Custom lowering phase.
9947 MVT VT = Op.getSimpleValueType();
9948 switch (VT.SimpleTy) {
9956 // We couldn't create a "Blend with immediate" node.
9957 // This node should still be legal, but we'll have to emit a blendv*
9962 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9963 MVT VT = Op.getSimpleValueType();
9966 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9969 if (VT.getSizeInBits() == 8) {
9970 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9971 Op.getOperand(0), Op.getOperand(1));
9972 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9973 DAG.getValueType(VT));
9974 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9977 if (VT.getSizeInBits() == 16) {
9978 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9979 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9981 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9982 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9983 DAG.getNode(ISD::BITCAST, dl,
9987 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9988 Op.getOperand(0), Op.getOperand(1));
9989 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9990 DAG.getValueType(VT));
9991 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9994 if (VT == MVT::f32) {
9995 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9996 // the result back to FR32 register. It's only worth matching if the
9997 // result has a single use which is a store or a bitcast to i32. And in
9998 // the case of a store, it's not worth it if the index is a constant 0,
9999 // because a MOVSSmr can be used instead, which is smaller and faster.
10000 if (!Op.hasOneUse())
10002 SDNode *User = *Op.getNode()->use_begin();
10003 if ((User->getOpcode() != ISD::STORE ||
10004 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10005 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10006 (User->getOpcode() != ISD::BITCAST ||
10007 User->getValueType(0) != MVT::i32))
10009 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10010 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10013 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10016 if (VT == MVT::i32 || VT == MVT::i64) {
10017 // ExtractPS/pextrq works with constant index.
10018 if (isa<ConstantSDNode>(Op.getOperand(1)))
10024 /// Extract one bit from mask vector, like v16i1 or v8i1.
10025 /// AVX-512 feature.
10027 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10028 SDValue Vec = Op.getOperand(0);
10030 MVT VecVT = Vec.getSimpleValueType();
10031 SDValue Idx = Op.getOperand(1);
10032 MVT EltVT = Op.getSimpleValueType();
10034 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10036 // variable index can't be handled in mask registers,
10037 // extend vector to VR512
10038 if (!isa<ConstantSDNode>(Idx)) {
10039 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10040 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10041 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10042 ExtVT.getVectorElementType(), Ext, Idx);
10043 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10046 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10047 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10048 unsigned MaxSift = rc->getSize()*8 - 1;
10049 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10050 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10051 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10052 DAG.getConstant(MaxSift, MVT::i8));
10053 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10054 DAG.getIntPtrConstant(0));
10058 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10059 SelectionDAG &DAG) const {
10061 SDValue Vec = Op.getOperand(0);
10062 MVT VecVT = Vec.getSimpleValueType();
10063 SDValue Idx = Op.getOperand(1);
10065 if (Op.getSimpleValueType() == MVT::i1)
10066 return ExtractBitFromMaskVector(Op, DAG);
10068 if (!isa<ConstantSDNode>(Idx)) {
10069 if (VecVT.is512BitVector() ||
10070 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10071 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10074 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10075 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10076 MaskEltVT.getSizeInBits());
10078 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10079 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10080 getZeroVector(MaskVT, Subtarget, DAG, dl),
10081 Idx, DAG.getConstant(0, getPointerTy()));
10082 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10083 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10084 Perm, DAG.getConstant(0, getPointerTy()));
10089 // If this is a 256-bit vector result, first extract the 128-bit vector and
10090 // then extract the element from the 128-bit vector.
10091 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10093 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10094 // Get the 128-bit vector.
10095 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10096 MVT EltVT = VecVT.getVectorElementType();
10098 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10100 //if (IdxVal >= NumElems/2)
10101 // IdxVal -= NumElems/2;
10102 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10103 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10104 DAG.getConstant(IdxVal, MVT::i32));
10107 assert(VecVT.is128BitVector() && "Unexpected vector length");
10109 if (Subtarget->hasSSE41()) {
10110 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10115 MVT VT = Op.getSimpleValueType();
10116 // TODO: handle v16i8.
10117 if (VT.getSizeInBits() == 16) {
10118 SDValue Vec = Op.getOperand(0);
10119 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10121 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10122 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10123 DAG.getNode(ISD::BITCAST, dl,
10125 Op.getOperand(1)));
10126 // Transform it so it match pextrw which produces a 32-bit result.
10127 MVT EltVT = MVT::i32;
10128 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10129 Op.getOperand(0), Op.getOperand(1));
10130 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10131 DAG.getValueType(VT));
10132 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10135 if (VT.getSizeInBits() == 32) {
10136 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10140 // SHUFPS the element to the lowest double word, then movss.
10141 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10142 MVT VVT = Op.getOperand(0).getSimpleValueType();
10143 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10144 DAG.getUNDEF(VVT), Mask);
10145 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10146 DAG.getIntPtrConstant(0));
10149 if (VT.getSizeInBits() == 64) {
10150 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10151 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10152 // to match extract_elt for f64.
10153 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10157 // UNPCKHPD the element to the lowest double word, then movsd.
10158 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10159 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10160 int Mask[2] = { 1, -1 };
10161 MVT VVT = Op.getOperand(0).getSimpleValueType();
10162 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10163 DAG.getUNDEF(VVT), Mask);
10164 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10165 DAG.getIntPtrConstant(0));
10171 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10172 MVT VT = Op.getSimpleValueType();
10173 MVT EltVT = VT.getVectorElementType();
10176 SDValue N0 = Op.getOperand(0);
10177 SDValue N1 = Op.getOperand(1);
10178 SDValue N2 = Op.getOperand(2);
10180 if (!VT.is128BitVector())
10183 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10184 isa<ConstantSDNode>(N2)) {
10186 if (VT == MVT::v8i16)
10187 Opc = X86ISD::PINSRW;
10188 else if (VT == MVT::v16i8)
10189 Opc = X86ISD::PINSRB;
10191 Opc = X86ISD::PINSRB;
10193 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10195 if (N1.getValueType() != MVT::i32)
10196 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10197 if (N2.getValueType() != MVT::i32)
10198 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10199 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10202 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10203 // Bits [7:6] of the constant are the source select. This will always be
10204 // zero here. The DAG Combiner may combine an extract_elt index into these
10205 // bits. For example (insert (extract, 3), 2) could be matched by putting
10206 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10207 // Bits [5:4] of the constant are the destination select. This is the
10208 // value of the incoming immediate.
10209 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10210 // combine either bitwise AND or insert of float 0.0 to set these bits.
10211 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10212 // Create this as a scalar to vector..
10213 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10214 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10217 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10218 // PINSR* works with constant index.
10224 /// Insert one bit to mask vector, like v16i1 or v8i1.
10225 /// AVX-512 feature.
10227 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10229 SDValue Vec = Op.getOperand(0);
10230 SDValue Elt = Op.getOperand(1);
10231 SDValue Idx = Op.getOperand(2);
10232 MVT VecVT = Vec.getSimpleValueType();
10234 if (!isa<ConstantSDNode>(Idx)) {
10235 // Non constant index. Extend source and destination,
10236 // insert element and then truncate the result.
10237 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10238 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10239 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10240 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10241 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10242 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10245 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10246 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10247 if (Vec.getOpcode() == ISD::UNDEF)
10248 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10249 DAG.getConstant(IdxVal, MVT::i8));
10250 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10251 unsigned MaxSift = rc->getSize()*8 - 1;
10252 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10253 DAG.getConstant(MaxSift, MVT::i8));
10254 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10255 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10256 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10259 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10260 MVT VT = Op.getSimpleValueType();
10261 MVT EltVT = VT.getVectorElementType();
10263 if (EltVT == MVT::i1)
10264 return InsertBitToMaskVector(Op, DAG);
10267 SDValue N0 = Op.getOperand(0);
10268 SDValue N1 = Op.getOperand(1);
10269 SDValue N2 = Op.getOperand(2);
10271 // If this is a 256-bit vector result, first extract the 128-bit vector,
10272 // insert the element into the extracted half and then place it back.
10273 if (VT.is256BitVector() || VT.is512BitVector()) {
10274 if (!isa<ConstantSDNode>(N2))
10277 // Get the desired 128-bit vector half.
10278 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10279 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10281 // Insert the element into the desired half.
10282 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10283 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10285 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10286 DAG.getConstant(IdxIn128, MVT::i32));
10288 // Insert the changed part back to the 256-bit vector
10289 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10292 if (Subtarget->hasSSE41())
10293 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10295 if (EltVT == MVT::i8)
10298 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10299 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10300 // as its second argument.
10301 if (N1.getValueType() != MVT::i32)
10302 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10303 if (N2.getValueType() != MVT::i32)
10304 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10305 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10310 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10312 MVT OpVT = Op.getSimpleValueType();
10314 // If this is a 256-bit vector result, first insert into a 128-bit
10315 // vector and then insert into the 256-bit vector.
10316 if (!OpVT.is128BitVector()) {
10317 // Insert into a 128-bit vector.
10318 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10319 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10320 OpVT.getVectorNumElements() / SizeFactor);
10322 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10324 // Insert the 128-bit vector.
10325 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10328 if (OpVT == MVT::v1i64 &&
10329 Op.getOperand(0).getValueType() == MVT::i64)
10330 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10332 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10333 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10334 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10335 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10338 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10339 // a simple subregister reference or explicit instructions to grab
10340 // upper bits of a vector.
10341 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10342 SelectionDAG &DAG) {
10344 SDValue In = Op.getOperand(0);
10345 SDValue Idx = Op.getOperand(1);
10346 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10347 MVT ResVT = Op.getSimpleValueType();
10348 MVT InVT = In.getSimpleValueType();
10350 if (Subtarget->hasFp256()) {
10351 if (ResVT.is128BitVector() &&
10352 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10353 isa<ConstantSDNode>(Idx)) {
10354 return Extract128BitVector(In, IdxVal, DAG, dl);
10356 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10357 isa<ConstantSDNode>(Idx)) {
10358 return Extract256BitVector(In, IdxVal, DAG, dl);
10364 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10365 // simple superregister reference or explicit instructions to insert
10366 // the upper bits of a vector.
10367 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10368 SelectionDAG &DAG) {
10369 if (Subtarget->hasFp256()) {
10370 SDLoc dl(Op.getNode());
10371 SDValue Vec = Op.getNode()->getOperand(0);
10372 SDValue SubVec = Op.getNode()->getOperand(1);
10373 SDValue Idx = Op.getNode()->getOperand(2);
10375 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10376 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10377 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10378 isa<ConstantSDNode>(Idx)) {
10379 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10380 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10383 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10384 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10385 isa<ConstantSDNode>(Idx)) {
10386 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10387 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10393 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10394 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10395 // one of the above mentioned nodes. It has to be wrapped because otherwise
10396 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10397 // be used to form addressing mode. These wrapped nodes will be selected
10400 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10401 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10403 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10404 // global base reg.
10405 unsigned char OpFlag = 0;
10406 unsigned WrapperKind = X86ISD::Wrapper;
10407 CodeModel::Model M = DAG.getTarget().getCodeModel();
10409 if (Subtarget->isPICStyleRIPRel() &&
10410 (M == CodeModel::Small || M == CodeModel::Kernel))
10411 WrapperKind = X86ISD::WrapperRIP;
10412 else if (Subtarget->isPICStyleGOT())
10413 OpFlag = X86II::MO_GOTOFF;
10414 else if (Subtarget->isPICStyleStubPIC())
10415 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10417 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10418 CP->getAlignment(),
10419 CP->getOffset(), OpFlag);
10421 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10422 // With PIC, the address is actually $g + Offset.
10424 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10425 DAG.getNode(X86ISD::GlobalBaseReg,
10426 SDLoc(), getPointerTy()),
10433 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10434 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10436 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10437 // global base reg.
10438 unsigned char OpFlag = 0;
10439 unsigned WrapperKind = X86ISD::Wrapper;
10440 CodeModel::Model M = DAG.getTarget().getCodeModel();
10442 if (Subtarget->isPICStyleRIPRel() &&
10443 (M == CodeModel::Small || M == CodeModel::Kernel))
10444 WrapperKind = X86ISD::WrapperRIP;
10445 else if (Subtarget->isPICStyleGOT())
10446 OpFlag = X86II::MO_GOTOFF;
10447 else if (Subtarget->isPICStyleStubPIC())
10448 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10450 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10453 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10455 // With PIC, the address is actually $g + Offset.
10457 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10458 DAG.getNode(X86ISD::GlobalBaseReg,
10459 SDLoc(), getPointerTy()),
10466 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10467 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10469 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10470 // global base reg.
10471 unsigned char OpFlag = 0;
10472 unsigned WrapperKind = X86ISD::Wrapper;
10473 CodeModel::Model M = DAG.getTarget().getCodeModel();
10475 if (Subtarget->isPICStyleRIPRel() &&
10476 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10477 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10478 OpFlag = X86II::MO_GOTPCREL;
10479 WrapperKind = X86ISD::WrapperRIP;
10480 } else if (Subtarget->isPICStyleGOT()) {
10481 OpFlag = X86II::MO_GOT;
10482 } else if (Subtarget->isPICStyleStubPIC()) {
10483 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10484 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10485 OpFlag = X86II::MO_DARWIN_NONLAZY;
10488 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10491 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10493 // With PIC, the address is actually $g + Offset.
10494 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10495 !Subtarget->is64Bit()) {
10496 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10497 DAG.getNode(X86ISD::GlobalBaseReg,
10498 SDLoc(), getPointerTy()),
10502 // For symbols that require a load from a stub to get the address, emit the
10504 if (isGlobalStubReference(OpFlag))
10505 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10506 MachinePointerInfo::getGOT(), false, false, false, 0);
10512 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10513 // Create the TargetBlockAddressAddress node.
10514 unsigned char OpFlags =
10515 Subtarget->ClassifyBlockAddressReference();
10516 CodeModel::Model M = DAG.getTarget().getCodeModel();
10517 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10518 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10520 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10523 if (Subtarget->isPICStyleRIPRel() &&
10524 (M == CodeModel::Small || M == CodeModel::Kernel))
10525 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10527 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10529 // With PIC, the address is actually $g + Offset.
10530 if (isGlobalRelativeToPICBase(OpFlags)) {
10531 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10532 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10540 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10541 int64_t Offset, SelectionDAG &DAG) const {
10542 // Create the TargetGlobalAddress node, folding in the constant
10543 // offset if it is legal.
10544 unsigned char OpFlags =
10545 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10546 CodeModel::Model M = DAG.getTarget().getCodeModel();
10548 if (OpFlags == X86II::MO_NO_FLAG &&
10549 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10550 // A direct static reference to a global.
10551 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10554 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10557 if (Subtarget->isPICStyleRIPRel() &&
10558 (M == CodeModel::Small || M == CodeModel::Kernel))
10559 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10561 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10563 // With PIC, the address is actually $g + Offset.
10564 if (isGlobalRelativeToPICBase(OpFlags)) {
10565 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10566 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10570 // For globals that require a load from a stub to get the address, emit the
10572 if (isGlobalStubReference(OpFlags))
10573 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10574 MachinePointerInfo::getGOT(), false, false, false, 0);
10576 // If there was a non-zero offset that we didn't fold, create an explicit
10577 // addition for it.
10579 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10580 DAG.getConstant(Offset, getPointerTy()));
10586 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10587 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10588 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10589 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10593 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10594 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10595 unsigned char OperandFlags, bool LocalDynamic = false) {
10596 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10597 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10599 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10600 GA->getValueType(0),
10604 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10608 SDValue Ops[] = { Chain, TGA, *InFlag };
10609 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10611 SDValue Ops[] = { Chain, TGA };
10612 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10615 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10616 MFI->setAdjustsStack(true);
10618 SDValue Flag = Chain.getValue(1);
10619 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10622 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10624 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10627 SDLoc dl(GA); // ? function entry point might be better
10628 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10629 DAG.getNode(X86ISD::GlobalBaseReg,
10630 SDLoc(), PtrVT), InFlag);
10631 InFlag = Chain.getValue(1);
10633 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10636 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10638 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10640 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10641 X86::RAX, X86II::MO_TLSGD);
10644 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10650 // Get the start address of the TLS block for this module.
10651 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10652 .getInfo<X86MachineFunctionInfo>();
10653 MFI->incNumLocalDynamicTLSAccesses();
10657 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10658 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10661 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10662 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10663 InFlag = Chain.getValue(1);
10664 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10665 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10668 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10672 unsigned char OperandFlags = X86II::MO_DTPOFF;
10673 unsigned WrapperKind = X86ISD::Wrapper;
10674 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10675 GA->getValueType(0),
10676 GA->getOffset(), OperandFlags);
10677 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10679 // Add x@dtpoff with the base.
10680 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10683 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10684 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10685 const EVT PtrVT, TLSModel::Model model,
10686 bool is64Bit, bool isPIC) {
10689 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10690 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10691 is64Bit ? 257 : 256));
10693 SDValue ThreadPointer =
10694 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10695 MachinePointerInfo(Ptr), false, false, false, 0);
10697 unsigned char OperandFlags = 0;
10698 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10700 unsigned WrapperKind = X86ISD::Wrapper;
10701 if (model == TLSModel::LocalExec) {
10702 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10703 } else if (model == TLSModel::InitialExec) {
10705 OperandFlags = X86II::MO_GOTTPOFF;
10706 WrapperKind = X86ISD::WrapperRIP;
10708 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10711 llvm_unreachable("Unexpected model");
10714 // emit "addl x@ntpoff,%eax" (local exec)
10715 // or "addl x@indntpoff,%eax" (initial exec)
10716 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10718 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10719 GA->getOffset(), OperandFlags);
10720 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10722 if (model == TLSModel::InitialExec) {
10723 if (isPIC && !is64Bit) {
10724 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10725 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10729 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10730 MachinePointerInfo::getGOT(), false, false, false, 0);
10733 // The address of the thread local variable is the add of the thread
10734 // pointer with the offset of the variable.
10735 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10739 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10741 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10742 const GlobalValue *GV = GA->getGlobal();
10744 if (Subtarget->isTargetELF()) {
10745 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10748 case TLSModel::GeneralDynamic:
10749 if (Subtarget->is64Bit())
10750 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10751 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10752 case TLSModel::LocalDynamic:
10753 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10754 Subtarget->is64Bit());
10755 case TLSModel::InitialExec:
10756 case TLSModel::LocalExec:
10757 return LowerToTLSExecModel(
10758 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10759 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10761 llvm_unreachable("Unknown TLS model.");
10764 if (Subtarget->isTargetDarwin()) {
10765 // Darwin only has one model of TLS. Lower to that.
10766 unsigned char OpFlag = 0;
10767 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10768 X86ISD::WrapperRIP : X86ISD::Wrapper;
10770 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10771 // global base reg.
10772 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10773 !Subtarget->is64Bit();
10775 OpFlag = X86II::MO_TLVP_PIC_BASE;
10777 OpFlag = X86II::MO_TLVP;
10779 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10780 GA->getValueType(0),
10781 GA->getOffset(), OpFlag);
10782 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10784 // With PIC32, the address is actually $g + Offset.
10786 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10787 DAG.getNode(X86ISD::GlobalBaseReg,
10788 SDLoc(), getPointerTy()),
10791 // Lowering the machine isd will make sure everything is in the right
10793 SDValue Chain = DAG.getEntryNode();
10794 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10795 SDValue Args[] = { Chain, Offset };
10796 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10798 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10799 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10800 MFI->setAdjustsStack(true);
10802 // And our return value (tls address) is in the standard call return value
10804 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10805 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10806 Chain.getValue(1));
10809 if (Subtarget->isTargetKnownWindowsMSVC() ||
10810 Subtarget->isTargetWindowsGNU()) {
10811 // Just use the implicit TLS architecture
10812 // Need to generate someting similar to:
10813 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10815 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10816 // mov rcx, qword [rdx+rcx*8]
10817 // mov eax, .tls$:tlsvar
10818 // [rax+rcx] contains the address
10819 // Windows 64bit: gs:0x58
10820 // Windows 32bit: fs:__tls_array
10823 SDValue Chain = DAG.getEntryNode();
10825 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10826 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10827 // use its literal value of 0x2C.
10828 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10829 ? Type::getInt8PtrTy(*DAG.getContext(),
10831 : Type::getInt32PtrTy(*DAG.getContext(),
10835 Subtarget->is64Bit()
10836 ? DAG.getIntPtrConstant(0x58)
10837 : (Subtarget->isTargetWindowsGNU()
10838 ? DAG.getIntPtrConstant(0x2C)
10839 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10841 SDValue ThreadPointer =
10842 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10843 MachinePointerInfo(Ptr), false, false, false, 0);
10845 // Load the _tls_index variable
10846 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10847 if (Subtarget->is64Bit())
10848 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10849 IDX, MachinePointerInfo(), MVT::i32,
10850 false, false, false, 0);
10852 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10853 false, false, false, 0);
10855 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10857 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10859 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10860 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10861 false, false, false, 0);
10863 // Get the offset of start of .tls section
10864 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10865 GA->getValueType(0),
10866 GA->getOffset(), X86II::MO_SECREL);
10867 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10869 // The address of the thread local variable is the add of the thread
10870 // pointer with the offset of the variable.
10871 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10874 llvm_unreachable("TLS not implemented for this target.");
10877 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10878 /// and take a 2 x i32 value to shift plus a shift amount.
10879 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10880 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10881 MVT VT = Op.getSimpleValueType();
10882 unsigned VTBits = VT.getSizeInBits();
10884 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10885 SDValue ShOpLo = Op.getOperand(0);
10886 SDValue ShOpHi = Op.getOperand(1);
10887 SDValue ShAmt = Op.getOperand(2);
10888 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10889 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10891 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10892 DAG.getConstant(VTBits - 1, MVT::i8));
10893 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10894 DAG.getConstant(VTBits - 1, MVT::i8))
10895 : DAG.getConstant(0, VT);
10897 SDValue Tmp2, Tmp3;
10898 if (Op.getOpcode() == ISD::SHL_PARTS) {
10899 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10900 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10902 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10903 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10906 // If the shift amount is larger or equal than the width of a part we can't
10907 // rely on the results of shld/shrd. Insert a test and select the appropriate
10908 // values for large shift amounts.
10909 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10910 DAG.getConstant(VTBits, MVT::i8));
10911 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10912 AndNode, DAG.getConstant(0, MVT::i8));
10915 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10916 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10917 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10919 if (Op.getOpcode() == ISD::SHL_PARTS) {
10920 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10921 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10923 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10924 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10927 SDValue Ops[2] = { Lo, Hi };
10928 return DAG.getMergeValues(Ops, dl);
10931 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10932 SelectionDAG &DAG) const {
10933 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10935 if (SrcVT.isVector())
10938 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10939 "Unknown SINT_TO_FP to lower!");
10941 // These are really Legal; return the operand so the caller accepts it as
10943 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10945 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10946 Subtarget->is64Bit()) {
10951 unsigned Size = SrcVT.getSizeInBits()/8;
10952 MachineFunction &MF = DAG.getMachineFunction();
10953 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10954 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10955 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10957 MachinePointerInfo::getFixedStack(SSFI),
10959 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10962 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10964 SelectionDAG &DAG) const {
10968 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10970 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10972 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10974 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10976 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10977 MachineMemOperand *MMO;
10979 int SSFI = FI->getIndex();
10981 DAG.getMachineFunction()
10982 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10983 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10985 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10986 StackSlot = StackSlot.getOperand(1);
10988 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10989 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10991 Tys, Ops, SrcVT, MMO);
10994 Chain = Result.getValue(1);
10995 SDValue InFlag = Result.getValue(2);
10997 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10998 // shouldn't be necessary except that RFP cannot be live across
10999 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11000 MachineFunction &MF = DAG.getMachineFunction();
11001 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11002 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11003 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11004 Tys = DAG.getVTList(MVT::Other);
11006 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11008 MachineMemOperand *MMO =
11009 DAG.getMachineFunction()
11010 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11011 MachineMemOperand::MOStore, SSFISize, SSFISize);
11013 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11014 Ops, Op.getValueType(), MMO);
11015 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11016 MachinePointerInfo::getFixedStack(SSFI),
11017 false, false, false, 0);
11023 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11024 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11025 SelectionDAG &DAG) const {
11026 // This algorithm is not obvious. Here it is what we're trying to output:
11029 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11030 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11032 haddpd %xmm0, %xmm0
11034 pshufd $0x4e, %xmm0, %xmm1
11040 LLVMContext *Context = DAG.getContext();
11042 // Build some magic constants.
11043 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11044 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11045 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11047 SmallVector<Constant*,2> CV1;
11049 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11050 APInt(64, 0x4330000000000000ULL))));
11052 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11053 APInt(64, 0x4530000000000000ULL))));
11054 Constant *C1 = ConstantVector::get(CV1);
11055 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11057 // Load the 64-bit value into an XMM register.
11058 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11060 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11061 MachinePointerInfo::getConstantPool(),
11062 false, false, false, 16);
11063 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11064 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11067 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11068 MachinePointerInfo::getConstantPool(),
11069 false, false, false, 16);
11070 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11071 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11074 if (Subtarget->hasSSE3()) {
11075 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11076 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11078 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11079 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11081 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11082 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11086 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11087 DAG.getIntPtrConstant(0));
11090 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11091 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11092 SelectionDAG &DAG) const {
11094 // FP constant to bias correct the final result.
11095 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11098 // Load the 32-bit value into an XMM register.
11099 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11102 // Zero out the upper parts of the register.
11103 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11105 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11106 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11107 DAG.getIntPtrConstant(0));
11109 // Or the load with the bias.
11110 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11111 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11112 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11113 MVT::v2f64, Load)),
11114 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11115 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11116 MVT::v2f64, Bias)));
11117 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11118 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11119 DAG.getIntPtrConstant(0));
11121 // Subtract the bias.
11122 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11124 // Handle final rounding.
11125 EVT DestVT = Op.getValueType();
11127 if (DestVT.bitsLT(MVT::f64))
11128 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11129 DAG.getIntPtrConstant(0));
11130 if (DestVT.bitsGT(MVT::f64))
11131 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11133 // Handle final rounding.
11137 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11138 SelectionDAG &DAG) const {
11139 SDValue N0 = Op.getOperand(0);
11140 MVT SVT = N0.getSimpleValueType();
11143 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11144 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11145 "Custom UINT_TO_FP is not supported!");
11147 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11148 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11149 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11152 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11153 SelectionDAG &DAG) const {
11154 SDValue N0 = Op.getOperand(0);
11157 if (Op.getValueType().isVector())
11158 return lowerUINT_TO_FP_vec(Op, DAG);
11160 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11161 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11162 // the optimization here.
11163 if (DAG.SignBitIsZero(N0))
11164 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11166 MVT SrcVT = N0.getSimpleValueType();
11167 MVT DstVT = Op.getSimpleValueType();
11168 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11169 return LowerUINT_TO_FP_i64(Op, DAG);
11170 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11171 return LowerUINT_TO_FP_i32(Op, DAG);
11172 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11175 // Make a 64-bit buffer, and use it to build an FILD.
11176 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11177 if (SrcVT == MVT::i32) {
11178 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11179 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11180 getPointerTy(), StackSlot, WordOff);
11181 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11182 StackSlot, MachinePointerInfo(),
11184 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11185 OffsetSlot, MachinePointerInfo(),
11187 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11191 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11192 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11193 StackSlot, MachinePointerInfo(),
11195 // For i64 source, we need to add the appropriate power of 2 if the input
11196 // was negative. This is the same as the optimization in
11197 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11198 // we must be careful to do the computation in x87 extended precision, not
11199 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11200 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11201 MachineMemOperand *MMO =
11202 DAG.getMachineFunction()
11203 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11204 MachineMemOperand::MOLoad, 8, 8);
11206 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11207 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11208 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11211 APInt FF(32, 0x5F800000ULL);
11213 // Check whether the sign bit is set.
11214 SDValue SignSet = DAG.getSetCC(dl,
11215 getSetCCResultType(*DAG.getContext(), MVT::i64),
11216 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11219 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11220 SDValue FudgePtr = DAG.getConstantPool(
11221 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11224 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11225 SDValue Zero = DAG.getIntPtrConstant(0);
11226 SDValue Four = DAG.getIntPtrConstant(4);
11227 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11229 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11231 // Load the value out, extending it from f32 to f80.
11232 // FIXME: Avoid the extend by constructing the right constant pool?
11233 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11234 FudgePtr, MachinePointerInfo::getConstantPool(),
11235 MVT::f32, false, false, false, 4);
11236 // Extend everything to 80 bits to force it to be done on x87.
11237 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11238 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11241 std::pair<SDValue,SDValue>
11242 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11243 bool IsSigned, bool IsReplace) const {
11246 EVT DstTy = Op.getValueType();
11248 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11249 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11253 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11254 DstTy.getSimpleVT() >= MVT::i16 &&
11255 "Unknown FP_TO_INT to lower!");
11257 // These are really Legal.
11258 if (DstTy == MVT::i32 &&
11259 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11260 return std::make_pair(SDValue(), SDValue());
11261 if (Subtarget->is64Bit() &&
11262 DstTy == MVT::i64 &&
11263 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11264 return std::make_pair(SDValue(), SDValue());
11266 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11267 // stack slot, or into the FTOL runtime function.
11268 MachineFunction &MF = DAG.getMachineFunction();
11269 unsigned MemSize = DstTy.getSizeInBits()/8;
11270 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11271 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11274 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11275 Opc = X86ISD::WIN_FTOL;
11277 switch (DstTy.getSimpleVT().SimpleTy) {
11278 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11279 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11280 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11281 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11284 SDValue Chain = DAG.getEntryNode();
11285 SDValue Value = Op.getOperand(0);
11286 EVT TheVT = Op.getOperand(0).getValueType();
11287 // FIXME This causes a redundant load/store if the SSE-class value is already
11288 // in memory, such as if it is on the callstack.
11289 if (isScalarFPTypeInSSEReg(TheVT)) {
11290 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11291 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11292 MachinePointerInfo::getFixedStack(SSFI),
11294 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11296 Chain, StackSlot, DAG.getValueType(TheVT)
11299 MachineMemOperand *MMO =
11300 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11301 MachineMemOperand::MOLoad, MemSize, MemSize);
11302 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11303 Chain = Value.getValue(1);
11304 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11305 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11308 MachineMemOperand *MMO =
11309 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11310 MachineMemOperand::MOStore, MemSize, MemSize);
11312 if (Opc != X86ISD::WIN_FTOL) {
11313 // Build the FP_TO_INT*_IN_MEM
11314 SDValue Ops[] = { Chain, Value, StackSlot };
11315 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11317 return std::make_pair(FIST, StackSlot);
11319 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11320 DAG.getVTList(MVT::Other, MVT::Glue),
11322 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11323 MVT::i32, ftol.getValue(1));
11324 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11325 MVT::i32, eax.getValue(2));
11326 SDValue Ops[] = { eax, edx };
11327 SDValue pair = IsReplace
11328 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11329 : DAG.getMergeValues(Ops, DL);
11330 return std::make_pair(pair, SDValue());
11334 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11335 const X86Subtarget *Subtarget) {
11336 MVT VT = Op->getSimpleValueType(0);
11337 SDValue In = Op->getOperand(0);
11338 MVT InVT = In.getSimpleValueType();
11341 // Optimize vectors in AVX mode:
11344 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11345 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11346 // Concat upper and lower parts.
11349 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11350 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11351 // Concat upper and lower parts.
11354 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11355 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11356 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11359 if (Subtarget->hasInt256())
11360 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11362 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11363 SDValue Undef = DAG.getUNDEF(InVT);
11364 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11365 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11366 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11368 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11369 VT.getVectorNumElements()/2);
11371 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11372 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11374 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11377 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11378 SelectionDAG &DAG) {
11379 MVT VT = Op->getSimpleValueType(0);
11380 SDValue In = Op->getOperand(0);
11381 MVT InVT = In.getSimpleValueType();
11383 unsigned int NumElts = VT.getVectorNumElements();
11384 if (NumElts != 8 && NumElts != 16)
11387 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11388 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11390 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11392 // Now we have only mask extension
11393 assert(InVT.getVectorElementType() == MVT::i1);
11394 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11395 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11396 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11397 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11398 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11399 MachinePointerInfo::getConstantPool(),
11400 false, false, false, Alignment);
11402 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11403 if (VT.is512BitVector())
11405 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11408 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11409 SelectionDAG &DAG) {
11410 if (Subtarget->hasFp256()) {
11411 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11419 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11420 SelectionDAG &DAG) {
11422 MVT VT = Op.getSimpleValueType();
11423 SDValue In = Op.getOperand(0);
11424 MVT SVT = In.getSimpleValueType();
11426 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11427 return LowerZERO_EXTEND_AVX512(Op, DAG);
11429 if (Subtarget->hasFp256()) {
11430 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11435 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11436 VT.getVectorNumElements() != SVT.getVectorNumElements());
11440 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11442 MVT VT = Op.getSimpleValueType();
11443 SDValue In = Op.getOperand(0);
11444 MVT InVT = In.getSimpleValueType();
11446 if (VT == MVT::i1) {
11447 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11448 "Invalid scalar TRUNCATE operation");
11449 if (InVT == MVT::i32)
11451 if (InVT.getSizeInBits() == 64)
11452 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11453 else if (InVT.getSizeInBits() < 32)
11454 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11455 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11457 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11458 "Invalid TRUNCATE operation");
11460 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11461 if (VT.getVectorElementType().getSizeInBits() >=8)
11462 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11464 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11465 unsigned NumElts = InVT.getVectorNumElements();
11466 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11467 if (InVT.getSizeInBits() < 512) {
11468 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11469 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11473 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11474 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11475 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11476 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11477 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11478 MachinePointerInfo::getConstantPool(),
11479 false, false, false, Alignment);
11480 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11481 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11482 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11485 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11486 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11487 if (Subtarget->hasInt256()) {
11488 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11489 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11490 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11492 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11493 DAG.getIntPtrConstant(0));
11496 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11497 DAG.getIntPtrConstant(0));
11498 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11499 DAG.getIntPtrConstant(2));
11500 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11501 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11502 static const int ShufMask[] = {0, 2, 4, 6};
11503 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11506 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11507 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11508 if (Subtarget->hasInt256()) {
11509 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11511 SmallVector<SDValue,32> pshufbMask;
11512 for (unsigned i = 0; i < 2; ++i) {
11513 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11514 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11515 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11516 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11517 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11518 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11519 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11520 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11521 for (unsigned j = 0; j < 8; ++j)
11522 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11524 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11525 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11526 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11528 static const int ShufMask[] = {0, 2, -1, -1};
11529 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11531 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11532 DAG.getIntPtrConstant(0));
11533 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11536 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11537 DAG.getIntPtrConstant(0));
11539 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11540 DAG.getIntPtrConstant(4));
11542 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11543 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11545 // The PSHUFB mask:
11546 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11547 -1, -1, -1, -1, -1, -1, -1, -1};
11549 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11550 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11551 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11553 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11554 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11556 // The MOVLHPS Mask:
11557 static const int ShufMask2[] = {0, 1, 4, 5};
11558 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11559 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11562 // Handle truncation of V256 to V128 using shuffles.
11563 if (!VT.is128BitVector() || !InVT.is256BitVector())
11566 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11568 unsigned NumElems = VT.getVectorNumElements();
11569 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11571 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11572 // Prepare truncation shuffle mask
11573 for (unsigned i = 0; i != NumElems; ++i)
11574 MaskVec[i] = i * 2;
11575 SDValue V = DAG.getVectorShuffle(NVT, DL,
11576 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11577 DAG.getUNDEF(NVT), &MaskVec[0]);
11578 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11579 DAG.getIntPtrConstant(0));
11582 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11583 SelectionDAG &DAG) const {
11584 assert(!Op.getSimpleValueType().isVector());
11586 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11587 /*IsSigned=*/ true, /*IsReplace=*/ false);
11588 SDValue FIST = Vals.first, StackSlot = Vals.second;
11589 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11590 if (!FIST.getNode()) return Op;
11592 if (StackSlot.getNode())
11593 // Load the result.
11594 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11595 FIST, StackSlot, MachinePointerInfo(),
11596 false, false, false, 0);
11598 // The node is the result.
11602 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11603 SelectionDAG &DAG) const {
11604 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11605 /*IsSigned=*/ false, /*IsReplace=*/ false);
11606 SDValue FIST = Vals.first, StackSlot = Vals.second;
11607 assert(FIST.getNode() && "Unexpected failure");
11609 if (StackSlot.getNode())
11610 // Load the result.
11611 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11612 FIST, StackSlot, MachinePointerInfo(),
11613 false, false, false, 0);
11615 // The node is the result.
11619 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11621 MVT VT = Op.getSimpleValueType();
11622 SDValue In = Op.getOperand(0);
11623 MVT SVT = In.getSimpleValueType();
11625 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11627 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11628 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11629 In, DAG.getUNDEF(SVT)));
11632 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11633 LLVMContext *Context = DAG.getContext();
11635 MVT VT = Op.getSimpleValueType();
11637 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11638 if (VT.isVector()) {
11639 EltVT = VT.getVectorElementType();
11640 NumElts = VT.getVectorNumElements();
11643 if (EltVT == MVT::f64)
11644 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11645 APInt(64, ~(1ULL << 63))));
11647 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11648 APInt(32, ~(1U << 31))));
11649 C = ConstantVector::getSplat(NumElts, C);
11650 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11651 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11652 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11653 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11654 MachinePointerInfo::getConstantPool(),
11655 false, false, false, Alignment);
11656 if (VT.isVector()) {
11657 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11658 return DAG.getNode(ISD::BITCAST, dl, VT,
11659 DAG.getNode(ISD::AND, dl, ANDVT,
11660 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11662 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11664 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11667 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11668 LLVMContext *Context = DAG.getContext();
11670 MVT VT = Op.getSimpleValueType();
11672 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11673 if (VT.isVector()) {
11674 EltVT = VT.getVectorElementType();
11675 NumElts = VT.getVectorNumElements();
11678 if (EltVT == MVT::f64)
11679 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11680 APInt(64, 1ULL << 63)));
11682 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11683 APInt(32, 1U << 31)));
11684 C = ConstantVector::getSplat(NumElts, C);
11685 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11686 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11687 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11688 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11689 MachinePointerInfo::getConstantPool(),
11690 false, false, false, Alignment);
11691 if (VT.isVector()) {
11692 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11693 return DAG.getNode(ISD::BITCAST, dl, VT,
11694 DAG.getNode(ISD::XOR, dl, XORVT,
11695 DAG.getNode(ISD::BITCAST, dl, XORVT,
11697 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11700 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11703 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11704 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11705 LLVMContext *Context = DAG.getContext();
11706 SDValue Op0 = Op.getOperand(0);
11707 SDValue Op1 = Op.getOperand(1);
11709 MVT VT = Op.getSimpleValueType();
11710 MVT SrcVT = Op1.getSimpleValueType();
11712 // If second operand is smaller, extend it first.
11713 if (SrcVT.bitsLT(VT)) {
11714 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11717 // And if it is bigger, shrink it first.
11718 if (SrcVT.bitsGT(VT)) {
11719 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11723 // At this point the operands and the result should have the same
11724 // type, and that won't be f80 since that is not custom lowered.
11726 // First get the sign bit of second operand.
11727 SmallVector<Constant*,4> CV;
11728 if (SrcVT == MVT::f64) {
11729 const fltSemantics &Sem = APFloat::IEEEdouble;
11730 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11731 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11733 const fltSemantics &Sem = APFloat::IEEEsingle;
11734 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11735 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11736 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11737 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11739 Constant *C = ConstantVector::get(CV);
11740 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11741 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11742 MachinePointerInfo::getConstantPool(),
11743 false, false, false, 16);
11744 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11746 // Shift sign bit right or left if the two operands have different types.
11747 if (SrcVT.bitsGT(VT)) {
11748 // Op0 is MVT::f32, Op1 is MVT::f64.
11749 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11750 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11751 DAG.getConstant(32, MVT::i32));
11752 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11753 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11754 DAG.getIntPtrConstant(0));
11757 // Clear first operand sign bit.
11759 if (VT == MVT::f64) {
11760 const fltSemantics &Sem = APFloat::IEEEdouble;
11761 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11762 APInt(64, ~(1ULL << 63)))));
11763 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11765 const fltSemantics &Sem = APFloat::IEEEsingle;
11766 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11767 APInt(32, ~(1U << 31)))));
11768 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11769 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11770 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11772 C = ConstantVector::get(CV);
11773 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11774 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11775 MachinePointerInfo::getConstantPool(),
11776 false, false, false, 16);
11777 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11779 // Or the value with the sign bit.
11780 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11783 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11784 SDValue N0 = Op.getOperand(0);
11786 MVT VT = Op.getSimpleValueType();
11788 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11789 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11790 DAG.getConstant(1, VT));
11791 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11794 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11796 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11797 SelectionDAG &DAG) {
11798 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11800 if (!Subtarget->hasSSE41())
11803 if (!Op->hasOneUse())
11806 SDNode *N = Op.getNode();
11809 SmallVector<SDValue, 8> Opnds;
11810 DenseMap<SDValue, unsigned> VecInMap;
11811 SmallVector<SDValue, 8> VecIns;
11812 EVT VT = MVT::Other;
11814 // Recognize a special case where a vector is casted into wide integer to
11816 Opnds.push_back(N->getOperand(0));
11817 Opnds.push_back(N->getOperand(1));
11819 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11820 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11821 // BFS traverse all OR'd operands.
11822 if (I->getOpcode() == ISD::OR) {
11823 Opnds.push_back(I->getOperand(0));
11824 Opnds.push_back(I->getOperand(1));
11825 // Re-evaluate the number of nodes to be traversed.
11826 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11830 // Quit if a non-EXTRACT_VECTOR_ELT
11831 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11834 // Quit if without a constant index.
11835 SDValue Idx = I->getOperand(1);
11836 if (!isa<ConstantSDNode>(Idx))
11839 SDValue ExtractedFromVec = I->getOperand(0);
11840 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11841 if (M == VecInMap.end()) {
11842 VT = ExtractedFromVec.getValueType();
11843 // Quit if not 128/256-bit vector.
11844 if (!VT.is128BitVector() && !VT.is256BitVector())
11846 // Quit if not the same type.
11847 if (VecInMap.begin() != VecInMap.end() &&
11848 VT != VecInMap.begin()->first.getValueType())
11850 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11851 VecIns.push_back(ExtractedFromVec);
11853 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11856 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11857 "Not extracted from 128-/256-bit vector.");
11859 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11861 for (DenseMap<SDValue, unsigned>::const_iterator
11862 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11863 // Quit if not all elements are used.
11864 if (I->second != FullMask)
11868 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11870 // Cast all vectors into TestVT for PTEST.
11871 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11872 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11874 // If more than one full vectors are evaluated, OR them first before PTEST.
11875 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11876 // Each iteration will OR 2 nodes and append the result until there is only
11877 // 1 node left, i.e. the final OR'd value of all vectors.
11878 SDValue LHS = VecIns[Slot];
11879 SDValue RHS = VecIns[Slot + 1];
11880 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11883 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11884 VecIns.back(), VecIns.back());
11887 /// \brief return true if \c Op has a use that doesn't just read flags.
11888 static bool hasNonFlagsUse(SDValue Op) {
11889 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11891 SDNode *User = *UI;
11892 unsigned UOpNo = UI.getOperandNo();
11893 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11894 // Look pass truncate.
11895 UOpNo = User->use_begin().getOperandNo();
11896 User = *User->use_begin();
11899 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11900 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11906 /// Emit nodes that will be selected as "test Op0,Op0", or something
11908 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11909 SelectionDAG &DAG) const {
11910 if (Op.getValueType() == MVT::i1)
11911 // KORTEST instruction should be selected
11912 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11913 DAG.getConstant(0, Op.getValueType()));
11915 // CF and OF aren't always set the way we want. Determine which
11916 // of these we need.
11917 bool NeedCF = false;
11918 bool NeedOF = false;
11921 case X86::COND_A: case X86::COND_AE:
11922 case X86::COND_B: case X86::COND_BE:
11925 case X86::COND_G: case X86::COND_GE:
11926 case X86::COND_L: case X86::COND_LE:
11927 case X86::COND_O: case X86::COND_NO: {
11928 // Check if we really need to set the
11929 // Overflow flag. If NoSignedWrap is present
11930 // that is not actually needed.
11931 switch (Op->getOpcode()) {
11936 const BinaryWithFlagsSDNode *BinNode =
11937 cast<BinaryWithFlagsSDNode>(Op.getNode());
11938 if (BinNode->hasNoSignedWrap())
11948 // See if we can use the EFLAGS value from the operand instead of
11949 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11950 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11951 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11952 // Emit a CMP with 0, which is the TEST pattern.
11953 //if (Op.getValueType() == MVT::i1)
11954 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11955 // DAG.getConstant(0, MVT::i1));
11956 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11957 DAG.getConstant(0, Op.getValueType()));
11959 unsigned Opcode = 0;
11960 unsigned NumOperands = 0;
11962 // Truncate operations may prevent the merge of the SETCC instruction
11963 // and the arithmetic instruction before it. Attempt to truncate the operands
11964 // of the arithmetic instruction and use a reduced bit-width instruction.
11965 bool NeedTruncation = false;
11966 SDValue ArithOp = Op;
11967 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11968 SDValue Arith = Op->getOperand(0);
11969 // Both the trunc and the arithmetic op need to have one user each.
11970 if (Arith->hasOneUse())
11971 switch (Arith.getOpcode()) {
11978 NeedTruncation = true;
11984 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11985 // which may be the result of a CAST. We use the variable 'Op', which is the
11986 // non-casted variable when we check for possible users.
11987 switch (ArithOp.getOpcode()) {
11989 // Due to an isel shortcoming, be conservative if this add is likely to be
11990 // selected as part of a load-modify-store instruction. When the root node
11991 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11992 // uses of other nodes in the match, such as the ADD in this case. This
11993 // leads to the ADD being left around and reselected, with the result being
11994 // two adds in the output. Alas, even if none our users are stores, that
11995 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11996 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11997 // climbing the DAG back to the root, and it doesn't seem to be worth the
11999 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12000 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12001 if (UI->getOpcode() != ISD::CopyToReg &&
12002 UI->getOpcode() != ISD::SETCC &&
12003 UI->getOpcode() != ISD::STORE)
12006 if (ConstantSDNode *C =
12007 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12008 // An add of one will be selected as an INC.
12009 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12010 Opcode = X86ISD::INC;
12015 // An add of negative one (subtract of one) will be selected as a DEC.
12016 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12017 Opcode = X86ISD::DEC;
12023 // Otherwise use a regular EFLAGS-setting add.
12024 Opcode = X86ISD::ADD;
12029 // If we have a constant logical shift that's only used in a comparison
12030 // against zero turn it into an equivalent AND. This allows turning it into
12031 // a TEST instruction later.
12032 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12033 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12034 EVT VT = Op.getValueType();
12035 unsigned BitWidth = VT.getSizeInBits();
12036 unsigned ShAmt = Op->getConstantOperandVal(1);
12037 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12039 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12040 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12041 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12042 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12044 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12045 DAG.getConstant(Mask, VT));
12046 DAG.ReplaceAllUsesWith(Op, New);
12052 // If the primary and result isn't used, don't bother using X86ISD::AND,
12053 // because a TEST instruction will be better.
12054 if (!hasNonFlagsUse(Op))
12060 // Due to the ISEL shortcoming noted above, be conservative if this op is
12061 // likely to be selected as part of a load-modify-store instruction.
12062 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12063 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12064 if (UI->getOpcode() == ISD::STORE)
12067 // Otherwise use a regular EFLAGS-setting instruction.
12068 switch (ArithOp.getOpcode()) {
12069 default: llvm_unreachable("unexpected operator!");
12070 case ISD::SUB: Opcode = X86ISD::SUB; break;
12071 case ISD::XOR: Opcode = X86ISD::XOR; break;
12072 case ISD::AND: Opcode = X86ISD::AND; break;
12074 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12075 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12076 if (EFLAGS.getNode())
12079 Opcode = X86ISD::OR;
12093 return SDValue(Op.getNode(), 1);
12099 // If we found that truncation is beneficial, perform the truncation and
12101 if (NeedTruncation) {
12102 EVT VT = Op.getValueType();
12103 SDValue WideVal = Op->getOperand(0);
12104 EVT WideVT = WideVal.getValueType();
12105 unsigned ConvertedOp = 0;
12106 // Use a target machine opcode to prevent further DAGCombine
12107 // optimizations that may separate the arithmetic operations
12108 // from the setcc node.
12109 switch (WideVal.getOpcode()) {
12111 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12112 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12113 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12114 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12115 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12119 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12120 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12121 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12122 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12123 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12129 // Emit a CMP with 0, which is the TEST pattern.
12130 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12131 DAG.getConstant(0, Op.getValueType()));
12133 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12134 SmallVector<SDValue, 4> Ops;
12135 for (unsigned i = 0; i != NumOperands; ++i)
12136 Ops.push_back(Op.getOperand(i));
12138 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12139 DAG.ReplaceAllUsesWith(Op, New);
12140 return SDValue(New.getNode(), 1);
12143 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12145 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12146 SDLoc dl, SelectionDAG &DAG) const {
12147 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12148 if (C->getAPIntValue() == 0)
12149 return EmitTest(Op0, X86CC, dl, DAG);
12151 if (Op0.getValueType() == MVT::i1)
12152 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12155 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12156 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12157 // Do the comparison at i32 if it's smaller, besides the Atom case.
12158 // This avoids subregister aliasing issues. Keep the smaller reference
12159 // if we're optimizing for size, however, as that'll allow better folding
12160 // of memory operations.
12161 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12162 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12163 AttributeSet::FunctionIndex, Attribute::MinSize) &&
12164 !Subtarget->isAtom()) {
12165 unsigned ExtendOp =
12166 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12167 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12168 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12170 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12171 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12172 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12174 return SDValue(Sub.getNode(), 1);
12176 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12179 /// Convert a comparison if required by the subtarget.
12180 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12181 SelectionDAG &DAG) const {
12182 // If the subtarget does not support the FUCOMI instruction, floating-point
12183 // comparisons have to be converted.
12184 if (Subtarget->hasCMov() ||
12185 Cmp.getOpcode() != X86ISD::CMP ||
12186 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12187 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12190 // The instruction selector will select an FUCOM instruction instead of
12191 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12192 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12193 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12195 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12196 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12197 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12198 DAG.getConstant(8, MVT::i8));
12199 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12200 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12203 static bool isAllOnes(SDValue V) {
12204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12205 return C && C->isAllOnesValue();
12208 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12209 /// if it's possible.
12210 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12211 SDLoc dl, SelectionDAG &DAG) const {
12212 SDValue Op0 = And.getOperand(0);
12213 SDValue Op1 = And.getOperand(1);
12214 if (Op0.getOpcode() == ISD::TRUNCATE)
12215 Op0 = Op0.getOperand(0);
12216 if (Op1.getOpcode() == ISD::TRUNCATE)
12217 Op1 = Op1.getOperand(0);
12220 if (Op1.getOpcode() == ISD::SHL)
12221 std::swap(Op0, Op1);
12222 if (Op0.getOpcode() == ISD::SHL) {
12223 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12224 if (And00C->getZExtValue() == 1) {
12225 // If we looked past a truncate, check that it's only truncating away
12227 unsigned BitWidth = Op0.getValueSizeInBits();
12228 unsigned AndBitWidth = And.getValueSizeInBits();
12229 if (BitWidth > AndBitWidth) {
12231 DAG.computeKnownBits(Op0, Zeros, Ones);
12232 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12236 RHS = Op0.getOperand(1);
12238 } else if (Op1.getOpcode() == ISD::Constant) {
12239 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12240 uint64_t AndRHSVal = AndRHS->getZExtValue();
12241 SDValue AndLHS = Op0;
12243 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12244 LHS = AndLHS.getOperand(0);
12245 RHS = AndLHS.getOperand(1);
12248 // Use BT if the immediate can't be encoded in a TEST instruction.
12249 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12251 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12255 if (LHS.getNode()) {
12256 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12257 // instruction. Since the shift amount is in-range-or-undefined, we know
12258 // that doing a bittest on the i32 value is ok. We extend to i32 because
12259 // the encoding for the i16 version is larger than the i32 version.
12260 // Also promote i16 to i32 for performance / code size reason.
12261 if (LHS.getValueType() == MVT::i8 ||
12262 LHS.getValueType() == MVT::i16)
12263 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12265 // If the operand types disagree, extend the shift amount to match. Since
12266 // BT ignores high bits (like shifts) we can use anyextend.
12267 if (LHS.getValueType() != RHS.getValueType())
12268 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12270 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12271 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12272 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12273 DAG.getConstant(Cond, MVT::i8), BT);
12279 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12281 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12286 // SSE Condition code mapping:
12295 switch (SetCCOpcode) {
12296 default: llvm_unreachable("Unexpected SETCC condition");
12298 case ISD::SETEQ: SSECC = 0; break;
12300 case ISD::SETGT: Swap = true; // Fallthrough
12302 case ISD::SETOLT: SSECC = 1; break;
12304 case ISD::SETGE: Swap = true; // Fallthrough
12306 case ISD::SETOLE: SSECC = 2; break;
12307 case ISD::SETUO: SSECC = 3; break;
12309 case ISD::SETNE: SSECC = 4; break;
12310 case ISD::SETULE: Swap = true; // Fallthrough
12311 case ISD::SETUGE: SSECC = 5; break;
12312 case ISD::SETULT: Swap = true; // Fallthrough
12313 case ISD::SETUGT: SSECC = 6; break;
12314 case ISD::SETO: SSECC = 7; break;
12316 case ISD::SETONE: SSECC = 8; break;
12319 std::swap(Op0, Op1);
12324 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12325 // ones, and then concatenate the result back.
12326 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12327 MVT VT = Op.getSimpleValueType();
12329 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12330 "Unsupported value type for operation");
12332 unsigned NumElems = VT.getVectorNumElements();
12334 SDValue CC = Op.getOperand(2);
12336 // Extract the LHS vectors
12337 SDValue LHS = Op.getOperand(0);
12338 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12339 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12341 // Extract the RHS vectors
12342 SDValue RHS = Op.getOperand(1);
12343 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12344 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12346 // Issue the operation on the smaller types and concatenate the result back
12347 MVT EltVT = VT.getVectorElementType();
12348 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12349 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12350 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12351 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12354 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12355 const X86Subtarget *Subtarget) {
12356 SDValue Op0 = Op.getOperand(0);
12357 SDValue Op1 = Op.getOperand(1);
12358 SDValue CC = Op.getOperand(2);
12359 MVT VT = Op.getSimpleValueType();
12362 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12363 Op.getValueType().getScalarType() == MVT::i1 &&
12364 "Cannot set masked compare for this operation");
12366 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12368 bool Unsigned = false;
12371 switch (SetCCOpcode) {
12372 default: llvm_unreachable("Unexpected SETCC condition");
12373 case ISD::SETNE: SSECC = 4; break;
12374 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12375 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12376 case ISD::SETLT: Swap = true; //fall-through
12377 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12378 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12379 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12380 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12381 case ISD::SETULE: Unsigned = true; //fall-through
12382 case ISD::SETLE: SSECC = 2; break;
12386 std::swap(Op0, Op1);
12388 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12389 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12390 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12391 DAG.getConstant(SSECC, MVT::i8));
12394 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12395 /// operand \p Op1. If non-trivial (for example because it's not constant)
12396 /// return an empty value.
12397 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12399 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12403 MVT VT = Op1.getSimpleValueType();
12404 MVT EVT = VT.getVectorElementType();
12405 unsigned n = VT.getVectorNumElements();
12406 SmallVector<SDValue, 8> ULTOp1;
12408 for (unsigned i = 0; i < n; ++i) {
12409 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12410 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12413 // Avoid underflow.
12414 APInt Val = Elt->getAPIntValue();
12418 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12421 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12424 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12425 SelectionDAG &DAG) {
12426 SDValue Op0 = Op.getOperand(0);
12427 SDValue Op1 = Op.getOperand(1);
12428 SDValue CC = Op.getOperand(2);
12429 MVT VT = Op.getSimpleValueType();
12430 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12431 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12436 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12437 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12440 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12441 unsigned Opc = X86ISD::CMPP;
12442 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12443 assert(VT.getVectorNumElements() <= 16);
12444 Opc = X86ISD::CMPM;
12446 // In the two special cases we can't handle, emit two comparisons.
12449 unsigned CombineOpc;
12450 if (SetCCOpcode == ISD::SETUEQ) {
12451 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12453 assert(SetCCOpcode == ISD::SETONE);
12454 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12457 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12458 DAG.getConstant(CC0, MVT::i8));
12459 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12460 DAG.getConstant(CC1, MVT::i8));
12461 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12463 // Handle all other FP comparisons here.
12464 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12465 DAG.getConstant(SSECC, MVT::i8));
12468 // Break 256-bit integer vector compare into smaller ones.
12469 if (VT.is256BitVector() && !Subtarget->hasInt256())
12470 return Lower256IntVSETCC(Op, DAG);
12472 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12473 EVT OpVT = Op1.getValueType();
12474 if (Subtarget->hasAVX512()) {
12475 if (Op1.getValueType().is512BitVector() ||
12476 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12477 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12479 // In AVX-512 architecture setcc returns mask with i1 elements,
12480 // But there is no compare instruction for i8 and i16 elements.
12481 // We are not talking about 512-bit operands in this case, these
12482 // types are illegal.
12484 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12485 OpVT.getVectorElementType().getSizeInBits() >= 8))
12486 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12487 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12490 // We are handling one of the integer comparisons here. Since SSE only has
12491 // GT and EQ comparisons for integer, swapping operands and multiple
12492 // operations may be required for some comparisons.
12494 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12495 bool Subus = false;
12497 switch (SetCCOpcode) {
12498 default: llvm_unreachable("Unexpected SETCC condition");
12499 case ISD::SETNE: Invert = true;
12500 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12501 case ISD::SETLT: Swap = true;
12502 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12503 case ISD::SETGE: Swap = true;
12504 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12505 Invert = true; break;
12506 case ISD::SETULT: Swap = true;
12507 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12508 FlipSigns = true; break;
12509 case ISD::SETUGE: Swap = true;
12510 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12511 FlipSigns = true; Invert = true; break;
12514 // Special case: Use min/max operations for SETULE/SETUGE
12515 MVT VET = VT.getVectorElementType();
12517 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12518 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12521 switch (SetCCOpcode) {
12523 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12524 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12527 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12530 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12531 if (!MinMax && hasSubus) {
12532 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12534 // t = psubus Op0, Op1
12535 // pcmpeq t, <0..0>
12536 switch (SetCCOpcode) {
12538 case ISD::SETULT: {
12539 // If the comparison is against a constant we can turn this into a
12540 // setule. With psubus, setule does not require a swap. This is
12541 // beneficial because the constant in the register is no longer
12542 // destructed as the destination so it can be hoisted out of a loop.
12543 // Only do this pre-AVX since vpcmp* is no longer destructive.
12544 if (Subtarget->hasAVX())
12546 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12547 if (ULEOp1.getNode()) {
12549 Subus = true; Invert = false; Swap = false;
12553 // Psubus is better than flip-sign because it requires no inversion.
12554 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12555 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12559 Opc = X86ISD::SUBUS;
12565 std::swap(Op0, Op1);
12567 // Check that the operation in question is available (most are plain SSE2,
12568 // but PCMPGTQ and PCMPEQQ have different requirements).
12569 if (VT == MVT::v2i64) {
12570 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12571 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12573 // First cast everything to the right type.
12574 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12575 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12577 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12578 // bits of the inputs before performing those operations. The lower
12579 // compare is always unsigned.
12582 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12584 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12585 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12586 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12587 Sign, Zero, Sign, Zero);
12589 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12590 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12592 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12593 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12594 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12596 // Create masks for only the low parts/high parts of the 64 bit integers.
12597 static const int MaskHi[] = { 1, 1, 3, 3 };
12598 static const int MaskLo[] = { 0, 0, 2, 2 };
12599 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12600 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12601 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12603 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12604 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12607 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12609 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12612 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12613 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12614 // pcmpeqd + pshufd + pand.
12615 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12617 // First cast everything to the right type.
12618 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12619 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12622 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12624 // Make sure the lower and upper halves are both all-ones.
12625 static const int Mask[] = { 1, 0, 3, 2 };
12626 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12627 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12630 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12632 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12636 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12637 // bits of the inputs before performing those operations.
12639 EVT EltVT = VT.getVectorElementType();
12640 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12641 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12642 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12645 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12647 // If the logical-not of the result is required, perform that now.
12649 Result = DAG.getNOT(dl, Result, VT);
12652 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12655 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12656 getZeroVector(VT, Subtarget, DAG, dl));
12661 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12663 MVT VT = Op.getSimpleValueType();
12665 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12667 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12668 && "SetCC type must be 8-bit or 1-bit integer");
12669 SDValue Op0 = Op.getOperand(0);
12670 SDValue Op1 = Op.getOperand(1);
12672 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12674 // Optimize to BT if possible.
12675 // Lower (X & (1 << N)) == 0 to BT(X, N).
12676 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12677 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12678 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12679 Op1.getOpcode() == ISD::Constant &&
12680 cast<ConstantSDNode>(Op1)->isNullValue() &&
12681 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12682 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12683 if (NewSetCC.getNode())
12687 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12689 if (Op1.getOpcode() == ISD::Constant &&
12690 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12691 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12692 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12694 // If the input is a setcc, then reuse the input setcc or use a new one with
12695 // the inverted condition.
12696 if (Op0.getOpcode() == X86ISD::SETCC) {
12697 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12698 bool Invert = (CC == ISD::SETNE) ^
12699 cast<ConstantSDNode>(Op1)->isNullValue();
12703 CCode = X86::GetOppositeBranchCondition(CCode);
12704 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12705 DAG.getConstant(CCode, MVT::i8),
12706 Op0.getOperand(1));
12708 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12712 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12713 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12714 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12716 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12717 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12720 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12721 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12722 if (X86CC == X86::COND_INVALID)
12725 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12726 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12727 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12728 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12730 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12734 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12735 static bool isX86LogicalCmp(SDValue Op) {
12736 unsigned Opc = Op.getNode()->getOpcode();
12737 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12738 Opc == X86ISD::SAHF)
12740 if (Op.getResNo() == 1 &&
12741 (Opc == X86ISD::ADD ||
12742 Opc == X86ISD::SUB ||
12743 Opc == X86ISD::ADC ||
12744 Opc == X86ISD::SBB ||
12745 Opc == X86ISD::SMUL ||
12746 Opc == X86ISD::UMUL ||
12747 Opc == X86ISD::INC ||
12748 Opc == X86ISD::DEC ||
12749 Opc == X86ISD::OR ||
12750 Opc == X86ISD::XOR ||
12751 Opc == X86ISD::AND))
12754 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12760 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12761 if (V.getOpcode() != ISD::TRUNCATE)
12764 SDValue VOp0 = V.getOperand(0);
12765 unsigned InBits = VOp0.getValueSizeInBits();
12766 unsigned Bits = V.getValueSizeInBits();
12767 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12770 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12771 bool addTest = true;
12772 SDValue Cond = Op.getOperand(0);
12773 SDValue Op1 = Op.getOperand(1);
12774 SDValue Op2 = Op.getOperand(2);
12776 EVT VT = Op1.getValueType();
12779 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12780 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12781 // sequence later on.
12782 if (Cond.getOpcode() == ISD::SETCC &&
12783 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12784 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12785 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12786 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12787 int SSECC = translateX86FSETCC(
12788 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12791 if (Subtarget->hasAVX512()) {
12792 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12793 DAG.getConstant(SSECC, MVT::i8));
12794 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12796 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12797 DAG.getConstant(SSECC, MVT::i8));
12798 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12799 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12800 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12804 if (Cond.getOpcode() == ISD::SETCC) {
12805 SDValue NewCond = LowerSETCC(Cond, DAG);
12806 if (NewCond.getNode())
12810 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12811 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12812 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12813 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12814 if (Cond.getOpcode() == X86ISD::SETCC &&
12815 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12816 isZero(Cond.getOperand(1).getOperand(1))) {
12817 SDValue Cmp = Cond.getOperand(1);
12819 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12821 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12822 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12823 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12825 SDValue CmpOp0 = Cmp.getOperand(0);
12826 // Apply further optimizations for special cases
12827 // (select (x != 0), -1, 0) -> neg & sbb
12828 // (select (x == 0), 0, -1) -> neg & sbb
12829 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12830 if (YC->isNullValue() &&
12831 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12832 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12833 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12834 DAG.getConstant(0, CmpOp0.getValueType()),
12836 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12837 DAG.getConstant(X86::COND_B, MVT::i8),
12838 SDValue(Neg.getNode(), 1));
12842 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12843 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12844 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12846 SDValue Res = // Res = 0 or -1.
12847 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12848 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12850 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12851 Res = DAG.getNOT(DL, Res, Res.getValueType());
12853 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12854 if (!N2C || !N2C->isNullValue())
12855 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12860 // Look past (and (setcc_carry (cmp ...)), 1).
12861 if (Cond.getOpcode() == ISD::AND &&
12862 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12863 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12864 if (C && C->getAPIntValue() == 1)
12865 Cond = Cond.getOperand(0);
12868 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12869 // setting operand in place of the X86ISD::SETCC.
12870 unsigned CondOpcode = Cond.getOpcode();
12871 if (CondOpcode == X86ISD::SETCC ||
12872 CondOpcode == X86ISD::SETCC_CARRY) {
12873 CC = Cond.getOperand(0);
12875 SDValue Cmp = Cond.getOperand(1);
12876 unsigned Opc = Cmp.getOpcode();
12877 MVT VT = Op.getSimpleValueType();
12879 bool IllegalFPCMov = false;
12880 if (VT.isFloatingPoint() && !VT.isVector() &&
12881 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12882 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12884 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12885 Opc == X86ISD::BT) { // FIXME
12889 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12890 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12891 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12892 Cond.getOperand(0).getValueType() != MVT::i8)) {
12893 SDValue LHS = Cond.getOperand(0);
12894 SDValue RHS = Cond.getOperand(1);
12895 unsigned X86Opcode;
12898 switch (CondOpcode) {
12899 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12900 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12901 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12902 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12903 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12904 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12905 default: llvm_unreachable("unexpected overflowing operator");
12907 if (CondOpcode == ISD::UMULO)
12908 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12911 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12913 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12915 if (CondOpcode == ISD::UMULO)
12916 Cond = X86Op.getValue(2);
12918 Cond = X86Op.getValue(1);
12920 CC = DAG.getConstant(X86Cond, MVT::i8);
12925 // Look pass the truncate if the high bits are known zero.
12926 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12927 Cond = Cond.getOperand(0);
12929 // We know the result of AND is compared against zero. Try to match
12931 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12932 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12933 if (NewSetCC.getNode()) {
12934 CC = NewSetCC.getOperand(0);
12935 Cond = NewSetCC.getOperand(1);
12942 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12943 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12946 // a < b ? -1 : 0 -> RES = ~setcc_carry
12947 // a < b ? 0 : -1 -> RES = setcc_carry
12948 // a >= b ? -1 : 0 -> RES = setcc_carry
12949 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12950 if (Cond.getOpcode() == X86ISD::SUB) {
12951 Cond = ConvertCmpIfNecessary(Cond, DAG);
12952 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12954 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12955 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12956 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12957 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12958 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12959 return DAG.getNOT(DL, Res, Res.getValueType());
12964 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12965 // widen the cmov and push the truncate through. This avoids introducing a new
12966 // branch during isel and doesn't add any extensions.
12967 if (Op.getValueType() == MVT::i8 &&
12968 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12969 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12970 if (T1.getValueType() == T2.getValueType() &&
12971 // Blacklist CopyFromReg to avoid partial register stalls.
12972 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12973 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12974 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12975 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12979 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12980 // condition is true.
12981 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12982 SDValue Ops[] = { Op2, Op1, CC, Cond };
12983 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12986 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12987 MVT VT = Op->getSimpleValueType(0);
12988 SDValue In = Op->getOperand(0);
12989 MVT InVT = In.getSimpleValueType();
12992 unsigned int NumElts = VT.getVectorNumElements();
12993 if (NumElts != 8 && NumElts != 16)
12996 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12997 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12999 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13000 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13002 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13003 Constant *C = ConstantInt::get(*DAG.getContext(),
13004 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13006 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13007 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13008 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13009 MachinePointerInfo::getConstantPool(),
13010 false, false, false, Alignment);
13011 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13012 if (VT.is512BitVector())
13014 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13017 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13018 SelectionDAG &DAG) {
13019 MVT VT = Op->getSimpleValueType(0);
13020 SDValue In = Op->getOperand(0);
13021 MVT InVT = In.getSimpleValueType();
13024 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13025 return LowerSIGN_EXTEND_AVX512(Op, DAG);
13027 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13028 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13029 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13032 if (Subtarget->hasInt256())
13033 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13035 // Optimize vectors in AVX mode
13036 // Sign extend v8i16 to v8i32 and
13039 // Divide input vector into two parts
13040 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13041 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13042 // concat the vectors to original VT
13044 unsigned NumElems = InVT.getVectorNumElements();
13045 SDValue Undef = DAG.getUNDEF(InVT);
13047 SmallVector<int,8> ShufMask1(NumElems, -1);
13048 for (unsigned i = 0; i != NumElems/2; ++i)
13051 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13053 SmallVector<int,8> ShufMask2(NumElems, -1);
13054 for (unsigned i = 0; i != NumElems/2; ++i)
13055 ShufMask2[i] = i + NumElems/2;
13057 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13059 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13060 VT.getVectorNumElements()/2);
13062 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13063 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13065 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13068 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13069 // may emit an illegal shuffle but the expansion is still better than scalar
13070 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13071 // we'll emit a shuffle and a arithmetic shift.
13072 // TODO: It is possible to support ZExt by zeroing the undef values during
13073 // the shuffle phase or after the shuffle.
13074 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13075 SelectionDAG &DAG) {
13076 MVT RegVT = Op.getSimpleValueType();
13077 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13078 assert(RegVT.isInteger() &&
13079 "We only custom lower integer vector sext loads.");
13081 // Nothing useful we can do without SSE2 shuffles.
13082 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13084 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13086 EVT MemVT = Ld->getMemoryVT();
13087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13088 unsigned RegSz = RegVT.getSizeInBits();
13090 ISD::LoadExtType Ext = Ld->getExtensionType();
13092 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13093 && "Only anyext and sext are currently implemented.");
13094 assert(MemVT != RegVT && "Cannot extend to the same type");
13095 assert(MemVT.isVector() && "Must load a vector from memory");
13097 unsigned NumElems = RegVT.getVectorNumElements();
13098 unsigned MemSz = MemVT.getSizeInBits();
13099 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13101 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13102 // The only way in which we have a legal 256-bit vector result but not the
13103 // integer 256-bit operations needed to directly lower a sextload is if we
13104 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13105 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13106 // correctly legalized. We do this late to allow the canonical form of
13107 // sextload to persist throughout the rest of the DAG combiner -- it wants
13108 // to fold together any extensions it can, and so will fuse a sign_extend
13109 // of an sextload into an sextload targeting a wider value.
13111 if (MemSz == 128) {
13112 // Just switch this to a normal load.
13113 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13114 "it must be a legal 128-bit vector "
13116 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13117 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13118 Ld->isInvariant(), Ld->getAlignment());
13120 assert(MemSz < 128 &&
13121 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13122 // Do an sext load to a 128-bit vector type. We want to use the same
13123 // number of elements, but elements half as wide. This will end up being
13124 // recursively lowered by this routine, but will succeed as we definitely
13125 // have all the necessary features if we're using AVX1.
13127 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13128 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13130 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13131 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13132 Ld->isNonTemporal(), Ld->isInvariant(),
13133 Ld->getAlignment());
13136 // Replace chain users with the new chain.
13137 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13138 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13140 // Finally, do a normal sign-extend to the desired register.
13141 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13144 // All sizes must be a power of two.
13145 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13146 "Non-power-of-two elements are not custom lowered!");
13148 // Attempt to load the original value using scalar loads.
13149 // Find the largest scalar type that divides the total loaded size.
13150 MVT SclrLoadTy = MVT::i8;
13151 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13152 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13153 MVT Tp = (MVT::SimpleValueType)tp;
13154 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13159 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13160 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13162 SclrLoadTy = MVT::f64;
13164 // Calculate the number of scalar loads that we need to perform
13165 // in order to load our vector from memory.
13166 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13168 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13169 "Can only lower sext loads with a single scalar load!");
13171 unsigned loadRegZize = RegSz;
13172 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13175 // Represent our vector as a sequence of elements which are the
13176 // largest scalar that we can load.
13177 EVT LoadUnitVecVT = EVT::getVectorVT(
13178 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13180 // Represent the data using the same element type that is stored in
13181 // memory. In practice, we ''widen'' MemVT.
13183 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13184 loadRegZize / MemVT.getScalarType().getSizeInBits());
13186 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13187 "Invalid vector type");
13189 // We can't shuffle using an illegal type.
13190 assert(TLI.isTypeLegal(WideVecVT) &&
13191 "We only lower types that form legal widened vector types");
13193 SmallVector<SDValue, 8> Chains;
13194 SDValue Ptr = Ld->getBasePtr();
13195 SDValue Increment =
13196 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13197 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13199 for (unsigned i = 0; i < NumLoads; ++i) {
13200 // Perform a single load.
13201 SDValue ScalarLoad =
13202 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13203 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13204 Ld->getAlignment());
13205 Chains.push_back(ScalarLoad.getValue(1));
13206 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13207 // another round of DAGCombining.
13209 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13211 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13212 ScalarLoad, DAG.getIntPtrConstant(i));
13214 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13217 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13219 // Bitcast the loaded value to a vector of the original element type, in
13220 // the size of the target vector type.
13221 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13222 unsigned SizeRatio = RegSz / MemSz;
13224 if (Ext == ISD::SEXTLOAD) {
13225 // If we have SSE4.1 we can directly emit a VSEXT node.
13226 if (Subtarget->hasSSE41()) {
13227 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13228 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13232 // Otherwise we'll shuffle the small elements in the high bits of the
13233 // larger type and perform an arithmetic shift. If the shift is not legal
13234 // it's better to scalarize.
13235 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13236 "We can't implement an sext load without a arithmetic right shift!");
13238 // Redistribute the loaded elements into the different locations.
13239 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13240 for (unsigned i = 0; i != NumElems; ++i)
13241 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13243 SDValue Shuff = DAG.getVectorShuffle(
13244 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13246 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13248 // Build the arithmetic shift.
13249 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13250 MemVT.getVectorElementType().getSizeInBits();
13252 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13254 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13258 // Redistribute the loaded elements into the different locations.
13259 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13260 for (unsigned i = 0; i != NumElems; ++i)
13261 ShuffleVec[i * SizeRatio] = i;
13263 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13264 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13266 // Bitcast to the requested type.
13267 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13268 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13272 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13273 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13274 // from the AND / OR.
13275 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13276 Opc = Op.getOpcode();
13277 if (Opc != ISD::OR && Opc != ISD::AND)
13279 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13280 Op.getOperand(0).hasOneUse() &&
13281 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13282 Op.getOperand(1).hasOneUse());
13285 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13286 // 1 and that the SETCC node has a single use.
13287 static bool isXor1OfSetCC(SDValue Op) {
13288 if (Op.getOpcode() != ISD::XOR)
13290 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13291 if (N1C && N1C->getAPIntValue() == 1) {
13292 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13293 Op.getOperand(0).hasOneUse();
13298 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13299 bool addTest = true;
13300 SDValue Chain = Op.getOperand(0);
13301 SDValue Cond = Op.getOperand(1);
13302 SDValue Dest = Op.getOperand(2);
13305 bool Inverted = false;
13307 if (Cond.getOpcode() == ISD::SETCC) {
13308 // Check for setcc([su]{add,sub,mul}o == 0).
13309 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13310 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13311 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13312 Cond.getOperand(0).getResNo() == 1 &&
13313 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13314 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13315 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13316 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13317 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13318 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13320 Cond = Cond.getOperand(0);
13322 SDValue NewCond = LowerSETCC(Cond, DAG);
13323 if (NewCond.getNode())
13328 // FIXME: LowerXALUO doesn't handle these!!
13329 else if (Cond.getOpcode() == X86ISD::ADD ||
13330 Cond.getOpcode() == X86ISD::SUB ||
13331 Cond.getOpcode() == X86ISD::SMUL ||
13332 Cond.getOpcode() == X86ISD::UMUL)
13333 Cond = LowerXALUO(Cond, DAG);
13336 // Look pass (and (setcc_carry (cmp ...)), 1).
13337 if (Cond.getOpcode() == ISD::AND &&
13338 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13339 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13340 if (C && C->getAPIntValue() == 1)
13341 Cond = Cond.getOperand(0);
13344 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13345 // setting operand in place of the X86ISD::SETCC.
13346 unsigned CondOpcode = Cond.getOpcode();
13347 if (CondOpcode == X86ISD::SETCC ||
13348 CondOpcode == X86ISD::SETCC_CARRY) {
13349 CC = Cond.getOperand(0);
13351 SDValue Cmp = Cond.getOperand(1);
13352 unsigned Opc = Cmp.getOpcode();
13353 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13354 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13358 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13362 // These can only come from an arithmetic instruction with overflow,
13363 // e.g. SADDO, UADDO.
13364 Cond = Cond.getNode()->getOperand(1);
13370 CondOpcode = Cond.getOpcode();
13371 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13372 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13373 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13374 Cond.getOperand(0).getValueType() != MVT::i8)) {
13375 SDValue LHS = Cond.getOperand(0);
13376 SDValue RHS = Cond.getOperand(1);
13377 unsigned X86Opcode;
13380 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13381 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13383 switch (CondOpcode) {
13384 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13388 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13391 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13392 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13396 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13399 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13400 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13401 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13402 default: llvm_unreachable("unexpected overflowing operator");
13405 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13406 if (CondOpcode == ISD::UMULO)
13407 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13410 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13412 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13414 if (CondOpcode == ISD::UMULO)
13415 Cond = X86Op.getValue(2);
13417 Cond = X86Op.getValue(1);
13419 CC = DAG.getConstant(X86Cond, MVT::i8);
13423 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13424 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13425 if (CondOpc == ISD::OR) {
13426 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13427 // two branches instead of an explicit OR instruction with a
13429 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13430 isX86LogicalCmp(Cmp)) {
13431 CC = Cond.getOperand(0).getOperand(0);
13432 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13433 Chain, Dest, CC, Cmp);
13434 CC = Cond.getOperand(1).getOperand(0);
13438 } else { // ISD::AND
13439 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13440 // two branches instead of an explicit AND instruction with a
13441 // separate test. However, we only do this if this block doesn't
13442 // have a fall-through edge, because this requires an explicit
13443 // jmp when the condition is false.
13444 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13445 isX86LogicalCmp(Cmp) &&
13446 Op.getNode()->hasOneUse()) {
13447 X86::CondCode CCode =
13448 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13449 CCode = X86::GetOppositeBranchCondition(CCode);
13450 CC = DAG.getConstant(CCode, MVT::i8);
13451 SDNode *User = *Op.getNode()->use_begin();
13452 // Look for an unconditional branch following this conditional branch.
13453 // We need this because we need to reverse the successors in order
13454 // to implement FCMP_OEQ.
13455 if (User->getOpcode() == ISD::BR) {
13456 SDValue FalseBB = User->getOperand(1);
13458 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13459 assert(NewBR == User);
13463 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13464 Chain, Dest, CC, Cmp);
13465 X86::CondCode CCode =
13466 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13467 CCode = X86::GetOppositeBranchCondition(CCode);
13468 CC = DAG.getConstant(CCode, MVT::i8);
13474 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13475 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13476 // It should be transformed during dag combiner except when the condition
13477 // is set by a arithmetics with overflow node.
13478 X86::CondCode CCode =
13479 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13480 CCode = X86::GetOppositeBranchCondition(CCode);
13481 CC = DAG.getConstant(CCode, MVT::i8);
13482 Cond = Cond.getOperand(0).getOperand(1);
13484 } else if (Cond.getOpcode() == ISD::SETCC &&
13485 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13486 // For FCMP_OEQ, we can emit
13487 // two branches instead of an explicit AND instruction with a
13488 // separate test. However, we only do this if this block doesn't
13489 // have a fall-through edge, because this requires an explicit
13490 // jmp when the condition is false.
13491 if (Op.getNode()->hasOneUse()) {
13492 SDNode *User = *Op.getNode()->use_begin();
13493 // Look for an unconditional branch following this conditional branch.
13494 // We need this because we need to reverse the successors in order
13495 // to implement FCMP_OEQ.
13496 if (User->getOpcode() == ISD::BR) {
13497 SDValue FalseBB = User->getOperand(1);
13499 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13500 assert(NewBR == User);
13504 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13505 Cond.getOperand(0), Cond.getOperand(1));
13506 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13507 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13508 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13509 Chain, Dest, CC, Cmp);
13510 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13515 } else if (Cond.getOpcode() == ISD::SETCC &&
13516 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13517 // For FCMP_UNE, we can emit
13518 // two branches instead of an explicit AND instruction with a
13519 // separate test. However, we only do this if this block doesn't
13520 // have a fall-through edge, because this requires an explicit
13521 // jmp when the condition is false.
13522 if (Op.getNode()->hasOneUse()) {
13523 SDNode *User = *Op.getNode()->use_begin();
13524 // Look for an unconditional branch following this conditional branch.
13525 // We need this because we need to reverse the successors in order
13526 // to implement FCMP_UNE.
13527 if (User->getOpcode() == ISD::BR) {
13528 SDValue FalseBB = User->getOperand(1);
13530 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13531 assert(NewBR == User);
13534 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13535 Cond.getOperand(0), Cond.getOperand(1));
13536 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13537 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13538 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13539 Chain, Dest, CC, Cmp);
13540 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13550 // Look pass the truncate if the high bits are known zero.
13551 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13552 Cond = Cond.getOperand(0);
13554 // We know the result of AND is compared against zero. Try to match
13556 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13557 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13558 if (NewSetCC.getNode()) {
13559 CC = NewSetCC.getOperand(0);
13560 Cond = NewSetCC.getOperand(1);
13567 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13568 CC = DAG.getConstant(X86Cond, MVT::i8);
13569 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13571 Cond = ConvertCmpIfNecessary(Cond, DAG);
13572 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13573 Chain, Dest, CC, Cond);
13576 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13577 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13578 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13579 // that the guard pages used by the OS virtual memory manager are allocated in
13580 // correct sequence.
13582 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13583 SelectionDAG &DAG) const {
13584 MachineFunction &MF = DAG.getMachineFunction();
13585 bool SplitStack = MF.shouldSplitStack();
13586 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13591 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13592 SDNode* Node = Op.getNode();
13594 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13595 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13596 " not tell us which reg is the stack pointer!");
13597 EVT VT = Node->getValueType(0);
13598 SDValue Tmp1 = SDValue(Node, 0);
13599 SDValue Tmp2 = SDValue(Node, 1);
13600 SDValue Tmp3 = Node->getOperand(2);
13601 SDValue Chain = Tmp1.getOperand(0);
13603 // Chain the dynamic stack allocation so that it doesn't modify the stack
13604 // pointer when other instructions are using the stack.
13605 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13608 SDValue Size = Tmp2.getOperand(1);
13609 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13610 Chain = SP.getValue(1);
13611 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13612 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
13613 unsigned StackAlign = TFI.getStackAlignment();
13614 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13615 if (Align > StackAlign)
13616 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13617 DAG.getConstant(-(uint64_t)Align, VT));
13618 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13620 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13621 DAG.getIntPtrConstant(0, true), SDValue(),
13624 SDValue Ops[2] = { Tmp1, Tmp2 };
13625 return DAG.getMergeValues(Ops, dl);
13629 SDValue Chain = Op.getOperand(0);
13630 SDValue Size = Op.getOperand(1);
13631 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13632 EVT VT = Op.getNode()->getValueType(0);
13634 bool Is64Bit = Subtarget->is64Bit();
13635 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13638 MachineRegisterInfo &MRI = MF.getRegInfo();
13641 // The 64 bit implementation of segmented stacks needs to clobber both r10
13642 // r11. This makes it impossible to use it along with nested parameters.
13643 const Function *F = MF.getFunction();
13645 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13647 if (I->hasNestAttr())
13648 report_fatal_error("Cannot use segmented stacks with functions that "
13649 "have nested arguments.");
13652 const TargetRegisterClass *AddrRegClass =
13653 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13654 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13655 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13656 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13657 DAG.getRegister(Vreg, SPTy));
13658 SDValue Ops1[2] = { Value, Chain };
13659 return DAG.getMergeValues(Ops1, dl);
13662 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13664 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13665 Flag = Chain.getValue(1);
13666 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13668 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13670 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
13671 DAG.getSubtarget().getRegisterInfo());
13672 unsigned SPReg = RegInfo->getStackRegister();
13673 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13674 Chain = SP.getValue(1);
13677 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13678 DAG.getConstant(-(uint64_t)Align, VT));
13679 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13682 SDValue Ops1[2] = { SP, Chain };
13683 return DAG.getMergeValues(Ops1, dl);
13687 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13688 MachineFunction &MF = DAG.getMachineFunction();
13689 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13691 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13694 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13695 // vastart just stores the address of the VarArgsFrameIndex slot into the
13696 // memory location argument.
13697 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13699 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13700 MachinePointerInfo(SV), false, false, 0);
13704 // gp_offset (0 - 6 * 8)
13705 // fp_offset (48 - 48 + 8 * 16)
13706 // overflow_arg_area (point to parameters coming in memory).
13708 SmallVector<SDValue, 8> MemOps;
13709 SDValue FIN = Op.getOperand(1);
13711 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13712 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13714 FIN, MachinePointerInfo(SV), false, false, 0);
13715 MemOps.push_back(Store);
13718 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13719 FIN, DAG.getIntPtrConstant(4));
13720 Store = DAG.getStore(Op.getOperand(0), DL,
13721 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13723 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13724 MemOps.push_back(Store);
13726 // Store ptr to overflow_arg_area
13727 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13728 FIN, DAG.getIntPtrConstant(4));
13729 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13731 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13732 MachinePointerInfo(SV, 8),
13734 MemOps.push_back(Store);
13736 // Store ptr to reg_save_area.
13737 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13738 FIN, DAG.getIntPtrConstant(8));
13739 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13741 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13742 MachinePointerInfo(SV, 16), false, false, 0);
13743 MemOps.push_back(Store);
13744 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13747 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13748 assert(Subtarget->is64Bit() &&
13749 "LowerVAARG only handles 64-bit va_arg!");
13750 assert((Subtarget->isTargetLinux() ||
13751 Subtarget->isTargetDarwin()) &&
13752 "Unhandled target in LowerVAARG");
13753 assert(Op.getNode()->getNumOperands() == 4);
13754 SDValue Chain = Op.getOperand(0);
13755 SDValue SrcPtr = Op.getOperand(1);
13756 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13757 unsigned Align = Op.getConstantOperandVal(3);
13760 EVT ArgVT = Op.getNode()->getValueType(0);
13761 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13762 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13765 // Decide which area this value should be read from.
13766 // TODO: Implement the AMD64 ABI in its entirety. This simple
13767 // selection mechanism works only for the basic types.
13768 if (ArgVT == MVT::f80) {
13769 llvm_unreachable("va_arg for f80 not yet implemented");
13770 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13771 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13772 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13773 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13775 llvm_unreachable("Unhandled argument type in LowerVAARG");
13778 if (ArgMode == 2) {
13779 // Sanity Check: Make sure using fp_offset makes sense.
13780 assert(!DAG.getTarget().Options.UseSoftFloat &&
13781 !(DAG.getMachineFunction()
13782 .getFunction()->getAttributes()
13783 .hasAttribute(AttributeSet::FunctionIndex,
13784 Attribute::NoImplicitFloat)) &&
13785 Subtarget->hasSSE1());
13788 // Insert VAARG_64 node into the DAG
13789 // VAARG_64 returns two values: Variable Argument Address, Chain
13790 SmallVector<SDValue, 11> InstOps;
13791 InstOps.push_back(Chain);
13792 InstOps.push_back(SrcPtr);
13793 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13794 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13795 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13796 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13797 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13798 VTs, InstOps, MVT::i64,
13799 MachinePointerInfo(SV),
13801 /*Volatile=*/false,
13803 /*WriteMem=*/true);
13804 Chain = VAARG.getValue(1);
13806 // Load the next argument and return it
13807 return DAG.getLoad(ArgVT, dl,
13810 MachinePointerInfo(),
13811 false, false, false, 0);
13814 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13815 SelectionDAG &DAG) {
13816 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13817 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13818 SDValue Chain = Op.getOperand(0);
13819 SDValue DstPtr = Op.getOperand(1);
13820 SDValue SrcPtr = Op.getOperand(2);
13821 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13822 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13825 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13826 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13828 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13831 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13832 // amount is a constant. Takes immediate version of shift as input.
13833 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13834 SDValue SrcOp, uint64_t ShiftAmt,
13835 SelectionDAG &DAG) {
13836 MVT ElementType = VT.getVectorElementType();
13838 // Fold this packed shift into its first operand if ShiftAmt is 0.
13842 // Check for ShiftAmt >= element width
13843 if (ShiftAmt >= ElementType.getSizeInBits()) {
13844 if (Opc == X86ISD::VSRAI)
13845 ShiftAmt = ElementType.getSizeInBits() - 1;
13847 return DAG.getConstant(0, VT);
13850 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13851 && "Unknown target vector shift-by-constant node");
13853 // Fold this packed vector shift into a build vector if SrcOp is a
13854 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13855 if (VT == SrcOp.getSimpleValueType() &&
13856 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13857 SmallVector<SDValue, 8> Elts;
13858 unsigned NumElts = SrcOp->getNumOperands();
13859 ConstantSDNode *ND;
13862 default: llvm_unreachable(nullptr);
13863 case X86ISD::VSHLI:
13864 for (unsigned i=0; i!=NumElts; ++i) {
13865 SDValue CurrentOp = SrcOp->getOperand(i);
13866 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13867 Elts.push_back(CurrentOp);
13870 ND = cast<ConstantSDNode>(CurrentOp);
13871 const APInt &C = ND->getAPIntValue();
13872 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13875 case X86ISD::VSRLI:
13876 for (unsigned i=0; i!=NumElts; ++i) {
13877 SDValue CurrentOp = SrcOp->getOperand(i);
13878 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13879 Elts.push_back(CurrentOp);
13882 ND = cast<ConstantSDNode>(CurrentOp);
13883 const APInt &C = ND->getAPIntValue();
13884 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13887 case X86ISD::VSRAI:
13888 for (unsigned i=0; i!=NumElts; ++i) {
13889 SDValue CurrentOp = SrcOp->getOperand(i);
13890 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13891 Elts.push_back(CurrentOp);
13894 ND = cast<ConstantSDNode>(CurrentOp);
13895 const APInt &C = ND->getAPIntValue();
13896 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13901 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13904 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13907 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13908 // may or may not be a constant. Takes immediate version of shift as input.
13909 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13910 SDValue SrcOp, SDValue ShAmt,
13911 SelectionDAG &DAG) {
13912 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13914 // Catch shift-by-constant.
13915 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13916 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13917 CShAmt->getZExtValue(), DAG);
13919 // Change opcode to non-immediate version
13921 default: llvm_unreachable("Unknown target vector shift node");
13922 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13923 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13924 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13927 // Need to build a vector containing shift amount
13928 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13931 ShOps[1] = DAG.getConstant(0, MVT::i32);
13932 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13933 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13935 // The return type has to be a 128-bit type with the same element
13936 // type as the input type.
13937 MVT EltVT = VT.getVectorElementType();
13938 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13940 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13941 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13944 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13946 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13948 default: return SDValue(); // Don't custom lower most intrinsics.
13949 // Comparison intrinsics.
13950 case Intrinsic::x86_sse_comieq_ss:
13951 case Intrinsic::x86_sse_comilt_ss:
13952 case Intrinsic::x86_sse_comile_ss:
13953 case Intrinsic::x86_sse_comigt_ss:
13954 case Intrinsic::x86_sse_comige_ss:
13955 case Intrinsic::x86_sse_comineq_ss:
13956 case Intrinsic::x86_sse_ucomieq_ss:
13957 case Intrinsic::x86_sse_ucomilt_ss:
13958 case Intrinsic::x86_sse_ucomile_ss:
13959 case Intrinsic::x86_sse_ucomigt_ss:
13960 case Intrinsic::x86_sse_ucomige_ss:
13961 case Intrinsic::x86_sse_ucomineq_ss:
13962 case Intrinsic::x86_sse2_comieq_sd:
13963 case Intrinsic::x86_sse2_comilt_sd:
13964 case Intrinsic::x86_sse2_comile_sd:
13965 case Intrinsic::x86_sse2_comigt_sd:
13966 case Intrinsic::x86_sse2_comige_sd:
13967 case Intrinsic::x86_sse2_comineq_sd:
13968 case Intrinsic::x86_sse2_ucomieq_sd:
13969 case Intrinsic::x86_sse2_ucomilt_sd:
13970 case Intrinsic::x86_sse2_ucomile_sd:
13971 case Intrinsic::x86_sse2_ucomigt_sd:
13972 case Intrinsic::x86_sse2_ucomige_sd:
13973 case Intrinsic::x86_sse2_ucomineq_sd: {
13977 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13978 case Intrinsic::x86_sse_comieq_ss:
13979 case Intrinsic::x86_sse2_comieq_sd:
13980 Opc = X86ISD::COMI;
13983 case Intrinsic::x86_sse_comilt_ss:
13984 case Intrinsic::x86_sse2_comilt_sd:
13985 Opc = X86ISD::COMI;
13988 case Intrinsic::x86_sse_comile_ss:
13989 case Intrinsic::x86_sse2_comile_sd:
13990 Opc = X86ISD::COMI;
13993 case Intrinsic::x86_sse_comigt_ss:
13994 case Intrinsic::x86_sse2_comigt_sd:
13995 Opc = X86ISD::COMI;
13998 case Intrinsic::x86_sse_comige_ss:
13999 case Intrinsic::x86_sse2_comige_sd:
14000 Opc = X86ISD::COMI;
14003 case Intrinsic::x86_sse_comineq_ss:
14004 case Intrinsic::x86_sse2_comineq_sd:
14005 Opc = X86ISD::COMI;
14008 case Intrinsic::x86_sse_ucomieq_ss:
14009 case Intrinsic::x86_sse2_ucomieq_sd:
14010 Opc = X86ISD::UCOMI;
14013 case Intrinsic::x86_sse_ucomilt_ss:
14014 case Intrinsic::x86_sse2_ucomilt_sd:
14015 Opc = X86ISD::UCOMI;
14018 case Intrinsic::x86_sse_ucomile_ss:
14019 case Intrinsic::x86_sse2_ucomile_sd:
14020 Opc = X86ISD::UCOMI;
14023 case Intrinsic::x86_sse_ucomigt_ss:
14024 case Intrinsic::x86_sse2_ucomigt_sd:
14025 Opc = X86ISD::UCOMI;
14028 case Intrinsic::x86_sse_ucomige_ss:
14029 case Intrinsic::x86_sse2_ucomige_sd:
14030 Opc = X86ISD::UCOMI;
14033 case Intrinsic::x86_sse_ucomineq_ss:
14034 case Intrinsic::x86_sse2_ucomineq_sd:
14035 Opc = X86ISD::UCOMI;
14040 SDValue LHS = Op.getOperand(1);
14041 SDValue RHS = Op.getOperand(2);
14042 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14043 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14044 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14045 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14046 DAG.getConstant(X86CC, MVT::i8), Cond);
14047 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14050 // Arithmetic intrinsics.
14051 case Intrinsic::x86_sse2_pmulu_dq:
14052 case Intrinsic::x86_avx2_pmulu_dq:
14053 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14054 Op.getOperand(1), Op.getOperand(2));
14056 case Intrinsic::x86_sse41_pmuldq:
14057 case Intrinsic::x86_avx2_pmul_dq:
14058 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14059 Op.getOperand(1), Op.getOperand(2));
14061 case Intrinsic::x86_sse2_pmulhu_w:
14062 case Intrinsic::x86_avx2_pmulhu_w:
14063 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14064 Op.getOperand(1), Op.getOperand(2));
14066 case Intrinsic::x86_sse2_pmulh_w:
14067 case Intrinsic::x86_avx2_pmulh_w:
14068 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14069 Op.getOperand(1), Op.getOperand(2));
14071 // SSE2/AVX2 sub with unsigned saturation intrinsics
14072 case Intrinsic::x86_sse2_psubus_b:
14073 case Intrinsic::x86_sse2_psubus_w:
14074 case Intrinsic::x86_avx2_psubus_b:
14075 case Intrinsic::x86_avx2_psubus_w:
14076 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14077 Op.getOperand(1), Op.getOperand(2));
14079 // SSE3/AVX horizontal add/sub intrinsics
14080 case Intrinsic::x86_sse3_hadd_ps:
14081 case Intrinsic::x86_sse3_hadd_pd:
14082 case Intrinsic::x86_avx_hadd_ps_256:
14083 case Intrinsic::x86_avx_hadd_pd_256:
14084 case Intrinsic::x86_sse3_hsub_ps:
14085 case Intrinsic::x86_sse3_hsub_pd:
14086 case Intrinsic::x86_avx_hsub_ps_256:
14087 case Intrinsic::x86_avx_hsub_pd_256:
14088 case Intrinsic::x86_ssse3_phadd_w_128:
14089 case Intrinsic::x86_ssse3_phadd_d_128:
14090 case Intrinsic::x86_avx2_phadd_w:
14091 case Intrinsic::x86_avx2_phadd_d:
14092 case Intrinsic::x86_ssse3_phsub_w_128:
14093 case Intrinsic::x86_ssse3_phsub_d_128:
14094 case Intrinsic::x86_avx2_phsub_w:
14095 case Intrinsic::x86_avx2_phsub_d: {
14098 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14099 case Intrinsic::x86_sse3_hadd_ps:
14100 case Intrinsic::x86_sse3_hadd_pd:
14101 case Intrinsic::x86_avx_hadd_ps_256:
14102 case Intrinsic::x86_avx_hadd_pd_256:
14103 Opcode = X86ISD::FHADD;
14105 case Intrinsic::x86_sse3_hsub_ps:
14106 case Intrinsic::x86_sse3_hsub_pd:
14107 case Intrinsic::x86_avx_hsub_ps_256:
14108 case Intrinsic::x86_avx_hsub_pd_256:
14109 Opcode = X86ISD::FHSUB;
14111 case Intrinsic::x86_ssse3_phadd_w_128:
14112 case Intrinsic::x86_ssse3_phadd_d_128:
14113 case Intrinsic::x86_avx2_phadd_w:
14114 case Intrinsic::x86_avx2_phadd_d:
14115 Opcode = X86ISD::HADD;
14117 case Intrinsic::x86_ssse3_phsub_w_128:
14118 case Intrinsic::x86_ssse3_phsub_d_128:
14119 case Intrinsic::x86_avx2_phsub_w:
14120 case Intrinsic::x86_avx2_phsub_d:
14121 Opcode = X86ISD::HSUB;
14124 return DAG.getNode(Opcode, dl, Op.getValueType(),
14125 Op.getOperand(1), Op.getOperand(2));
14128 // SSE2/SSE41/AVX2 integer max/min intrinsics.
14129 case Intrinsic::x86_sse2_pmaxu_b:
14130 case Intrinsic::x86_sse41_pmaxuw:
14131 case Intrinsic::x86_sse41_pmaxud:
14132 case Intrinsic::x86_avx2_pmaxu_b:
14133 case Intrinsic::x86_avx2_pmaxu_w:
14134 case Intrinsic::x86_avx2_pmaxu_d:
14135 case Intrinsic::x86_sse2_pminu_b:
14136 case Intrinsic::x86_sse41_pminuw:
14137 case Intrinsic::x86_sse41_pminud:
14138 case Intrinsic::x86_avx2_pminu_b:
14139 case Intrinsic::x86_avx2_pminu_w:
14140 case Intrinsic::x86_avx2_pminu_d:
14141 case Intrinsic::x86_sse41_pmaxsb:
14142 case Intrinsic::x86_sse2_pmaxs_w:
14143 case Intrinsic::x86_sse41_pmaxsd:
14144 case Intrinsic::x86_avx2_pmaxs_b:
14145 case Intrinsic::x86_avx2_pmaxs_w:
14146 case Intrinsic::x86_avx2_pmaxs_d:
14147 case Intrinsic::x86_sse41_pminsb:
14148 case Intrinsic::x86_sse2_pmins_w:
14149 case Intrinsic::x86_sse41_pminsd:
14150 case Intrinsic::x86_avx2_pmins_b:
14151 case Intrinsic::x86_avx2_pmins_w:
14152 case Intrinsic::x86_avx2_pmins_d: {
14155 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14156 case Intrinsic::x86_sse2_pmaxu_b:
14157 case Intrinsic::x86_sse41_pmaxuw:
14158 case Intrinsic::x86_sse41_pmaxud:
14159 case Intrinsic::x86_avx2_pmaxu_b:
14160 case Intrinsic::x86_avx2_pmaxu_w:
14161 case Intrinsic::x86_avx2_pmaxu_d:
14162 Opcode = X86ISD::UMAX;
14164 case Intrinsic::x86_sse2_pminu_b:
14165 case Intrinsic::x86_sse41_pminuw:
14166 case Intrinsic::x86_sse41_pminud:
14167 case Intrinsic::x86_avx2_pminu_b:
14168 case Intrinsic::x86_avx2_pminu_w:
14169 case Intrinsic::x86_avx2_pminu_d:
14170 Opcode = X86ISD::UMIN;
14172 case Intrinsic::x86_sse41_pmaxsb:
14173 case Intrinsic::x86_sse2_pmaxs_w:
14174 case Intrinsic::x86_sse41_pmaxsd:
14175 case Intrinsic::x86_avx2_pmaxs_b:
14176 case Intrinsic::x86_avx2_pmaxs_w:
14177 case Intrinsic::x86_avx2_pmaxs_d:
14178 Opcode = X86ISD::SMAX;
14180 case Intrinsic::x86_sse41_pminsb:
14181 case Intrinsic::x86_sse2_pmins_w:
14182 case Intrinsic::x86_sse41_pminsd:
14183 case Intrinsic::x86_avx2_pmins_b:
14184 case Intrinsic::x86_avx2_pmins_w:
14185 case Intrinsic::x86_avx2_pmins_d:
14186 Opcode = X86ISD::SMIN;
14189 return DAG.getNode(Opcode, dl, Op.getValueType(),
14190 Op.getOperand(1), Op.getOperand(2));
14193 // SSE/SSE2/AVX floating point max/min intrinsics.
14194 case Intrinsic::x86_sse_max_ps:
14195 case Intrinsic::x86_sse2_max_pd:
14196 case Intrinsic::x86_avx_max_ps_256:
14197 case Intrinsic::x86_avx_max_pd_256:
14198 case Intrinsic::x86_sse_min_ps:
14199 case Intrinsic::x86_sse2_min_pd:
14200 case Intrinsic::x86_avx_min_ps_256:
14201 case Intrinsic::x86_avx_min_pd_256: {
14204 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14205 case Intrinsic::x86_sse_max_ps:
14206 case Intrinsic::x86_sse2_max_pd:
14207 case Intrinsic::x86_avx_max_ps_256:
14208 case Intrinsic::x86_avx_max_pd_256:
14209 Opcode = X86ISD::FMAX;
14211 case Intrinsic::x86_sse_min_ps:
14212 case Intrinsic::x86_sse2_min_pd:
14213 case Intrinsic::x86_avx_min_ps_256:
14214 case Intrinsic::x86_avx_min_pd_256:
14215 Opcode = X86ISD::FMIN;
14218 return DAG.getNode(Opcode, dl, Op.getValueType(),
14219 Op.getOperand(1), Op.getOperand(2));
14222 // AVX2 variable shift intrinsics
14223 case Intrinsic::x86_avx2_psllv_d:
14224 case Intrinsic::x86_avx2_psllv_q:
14225 case Intrinsic::x86_avx2_psllv_d_256:
14226 case Intrinsic::x86_avx2_psllv_q_256:
14227 case Intrinsic::x86_avx2_psrlv_d:
14228 case Intrinsic::x86_avx2_psrlv_q:
14229 case Intrinsic::x86_avx2_psrlv_d_256:
14230 case Intrinsic::x86_avx2_psrlv_q_256:
14231 case Intrinsic::x86_avx2_psrav_d:
14232 case Intrinsic::x86_avx2_psrav_d_256: {
14235 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14236 case Intrinsic::x86_avx2_psllv_d:
14237 case Intrinsic::x86_avx2_psllv_q:
14238 case Intrinsic::x86_avx2_psllv_d_256:
14239 case Intrinsic::x86_avx2_psllv_q_256:
14242 case Intrinsic::x86_avx2_psrlv_d:
14243 case Intrinsic::x86_avx2_psrlv_q:
14244 case Intrinsic::x86_avx2_psrlv_d_256:
14245 case Intrinsic::x86_avx2_psrlv_q_256:
14248 case Intrinsic::x86_avx2_psrav_d:
14249 case Intrinsic::x86_avx2_psrav_d_256:
14253 return DAG.getNode(Opcode, dl, Op.getValueType(),
14254 Op.getOperand(1), Op.getOperand(2));
14257 case Intrinsic::x86_sse2_packssdw_128:
14258 case Intrinsic::x86_sse2_packsswb_128:
14259 case Intrinsic::x86_avx2_packssdw:
14260 case Intrinsic::x86_avx2_packsswb:
14261 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14262 Op.getOperand(1), Op.getOperand(2));
14264 case Intrinsic::x86_sse2_packuswb_128:
14265 case Intrinsic::x86_sse41_packusdw:
14266 case Intrinsic::x86_avx2_packuswb:
14267 case Intrinsic::x86_avx2_packusdw:
14268 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14269 Op.getOperand(1), Op.getOperand(2));
14271 case Intrinsic::x86_ssse3_pshuf_b_128:
14272 case Intrinsic::x86_avx2_pshuf_b:
14273 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14274 Op.getOperand(1), Op.getOperand(2));
14276 case Intrinsic::x86_sse2_pshuf_d:
14277 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14278 Op.getOperand(1), Op.getOperand(2));
14280 case Intrinsic::x86_sse2_pshufl_w:
14281 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14282 Op.getOperand(1), Op.getOperand(2));
14284 case Intrinsic::x86_sse2_pshufh_w:
14285 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14286 Op.getOperand(1), Op.getOperand(2));
14288 case Intrinsic::x86_ssse3_psign_b_128:
14289 case Intrinsic::x86_ssse3_psign_w_128:
14290 case Intrinsic::x86_ssse3_psign_d_128:
14291 case Intrinsic::x86_avx2_psign_b:
14292 case Intrinsic::x86_avx2_psign_w:
14293 case Intrinsic::x86_avx2_psign_d:
14294 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14295 Op.getOperand(1), Op.getOperand(2));
14297 case Intrinsic::x86_sse41_insertps:
14298 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14299 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14301 case Intrinsic::x86_avx_vperm2f128_ps_256:
14302 case Intrinsic::x86_avx_vperm2f128_pd_256:
14303 case Intrinsic::x86_avx_vperm2f128_si_256:
14304 case Intrinsic::x86_avx2_vperm2i128:
14305 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14306 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14308 case Intrinsic::x86_avx2_permd:
14309 case Intrinsic::x86_avx2_permps:
14310 // Operands intentionally swapped. Mask is last operand to intrinsic,
14311 // but second operand for node/instruction.
14312 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14313 Op.getOperand(2), Op.getOperand(1));
14315 case Intrinsic::x86_sse_sqrt_ps:
14316 case Intrinsic::x86_sse2_sqrt_pd:
14317 case Intrinsic::x86_avx_sqrt_ps_256:
14318 case Intrinsic::x86_avx_sqrt_pd_256:
14319 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14321 // ptest and testp intrinsics. The intrinsic these come from are designed to
14322 // return an integer value, not just an instruction so lower it to the ptest
14323 // or testp pattern and a setcc for the result.
14324 case Intrinsic::x86_sse41_ptestz:
14325 case Intrinsic::x86_sse41_ptestc:
14326 case Intrinsic::x86_sse41_ptestnzc:
14327 case Intrinsic::x86_avx_ptestz_256:
14328 case Intrinsic::x86_avx_ptestc_256:
14329 case Intrinsic::x86_avx_ptestnzc_256:
14330 case Intrinsic::x86_avx_vtestz_ps:
14331 case Intrinsic::x86_avx_vtestc_ps:
14332 case Intrinsic::x86_avx_vtestnzc_ps:
14333 case Intrinsic::x86_avx_vtestz_pd:
14334 case Intrinsic::x86_avx_vtestc_pd:
14335 case Intrinsic::x86_avx_vtestnzc_pd:
14336 case Intrinsic::x86_avx_vtestz_ps_256:
14337 case Intrinsic::x86_avx_vtestc_ps_256:
14338 case Intrinsic::x86_avx_vtestnzc_ps_256:
14339 case Intrinsic::x86_avx_vtestz_pd_256:
14340 case Intrinsic::x86_avx_vtestc_pd_256:
14341 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14342 bool IsTestPacked = false;
14345 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14346 case Intrinsic::x86_avx_vtestz_ps:
14347 case Intrinsic::x86_avx_vtestz_pd:
14348 case Intrinsic::x86_avx_vtestz_ps_256:
14349 case Intrinsic::x86_avx_vtestz_pd_256:
14350 IsTestPacked = true; // Fallthrough
14351 case Intrinsic::x86_sse41_ptestz:
14352 case Intrinsic::x86_avx_ptestz_256:
14354 X86CC = X86::COND_E;
14356 case Intrinsic::x86_avx_vtestc_ps:
14357 case Intrinsic::x86_avx_vtestc_pd:
14358 case Intrinsic::x86_avx_vtestc_ps_256:
14359 case Intrinsic::x86_avx_vtestc_pd_256:
14360 IsTestPacked = true; // Fallthrough
14361 case Intrinsic::x86_sse41_ptestc:
14362 case Intrinsic::x86_avx_ptestc_256:
14364 X86CC = X86::COND_B;
14366 case Intrinsic::x86_avx_vtestnzc_ps:
14367 case Intrinsic::x86_avx_vtestnzc_pd:
14368 case Intrinsic::x86_avx_vtestnzc_ps_256:
14369 case Intrinsic::x86_avx_vtestnzc_pd_256:
14370 IsTestPacked = true; // Fallthrough
14371 case Intrinsic::x86_sse41_ptestnzc:
14372 case Intrinsic::x86_avx_ptestnzc_256:
14374 X86CC = X86::COND_A;
14378 SDValue LHS = Op.getOperand(1);
14379 SDValue RHS = Op.getOperand(2);
14380 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14381 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14382 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14383 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14384 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14386 case Intrinsic::x86_avx512_kortestz_w:
14387 case Intrinsic::x86_avx512_kortestc_w: {
14388 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14389 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14390 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14391 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14392 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14393 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14394 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14397 // SSE/AVX shift intrinsics
14398 case Intrinsic::x86_sse2_psll_w:
14399 case Intrinsic::x86_sse2_psll_d:
14400 case Intrinsic::x86_sse2_psll_q:
14401 case Intrinsic::x86_avx2_psll_w:
14402 case Intrinsic::x86_avx2_psll_d:
14403 case Intrinsic::x86_avx2_psll_q:
14404 case Intrinsic::x86_sse2_psrl_w:
14405 case Intrinsic::x86_sse2_psrl_d:
14406 case Intrinsic::x86_sse2_psrl_q:
14407 case Intrinsic::x86_avx2_psrl_w:
14408 case Intrinsic::x86_avx2_psrl_d:
14409 case Intrinsic::x86_avx2_psrl_q:
14410 case Intrinsic::x86_sse2_psra_w:
14411 case Intrinsic::x86_sse2_psra_d:
14412 case Intrinsic::x86_avx2_psra_w:
14413 case Intrinsic::x86_avx2_psra_d: {
14416 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14417 case Intrinsic::x86_sse2_psll_w:
14418 case Intrinsic::x86_sse2_psll_d:
14419 case Intrinsic::x86_sse2_psll_q:
14420 case Intrinsic::x86_avx2_psll_w:
14421 case Intrinsic::x86_avx2_psll_d:
14422 case Intrinsic::x86_avx2_psll_q:
14423 Opcode = X86ISD::VSHL;
14425 case Intrinsic::x86_sse2_psrl_w:
14426 case Intrinsic::x86_sse2_psrl_d:
14427 case Intrinsic::x86_sse2_psrl_q:
14428 case Intrinsic::x86_avx2_psrl_w:
14429 case Intrinsic::x86_avx2_psrl_d:
14430 case Intrinsic::x86_avx2_psrl_q:
14431 Opcode = X86ISD::VSRL;
14433 case Intrinsic::x86_sse2_psra_w:
14434 case Intrinsic::x86_sse2_psra_d:
14435 case Intrinsic::x86_avx2_psra_w:
14436 case Intrinsic::x86_avx2_psra_d:
14437 Opcode = X86ISD::VSRA;
14440 return DAG.getNode(Opcode, dl, Op.getValueType(),
14441 Op.getOperand(1), Op.getOperand(2));
14444 // SSE/AVX immediate shift intrinsics
14445 case Intrinsic::x86_sse2_pslli_w:
14446 case Intrinsic::x86_sse2_pslli_d:
14447 case Intrinsic::x86_sse2_pslli_q:
14448 case Intrinsic::x86_avx2_pslli_w:
14449 case Intrinsic::x86_avx2_pslli_d:
14450 case Intrinsic::x86_avx2_pslli_q:
14451 case Intrinsic::x86_sse2_psrli_w:
14452 case Intrinsic::x86_sse2_psrli_d:
14453 case Intrinsic::x86_sse2_psrli_q:
14454 case Intrinsic::x86_avx2_psrli_w:
14455 case Intrinsic::x86_avx2_psrli_d:
14456 case Intrinsic::x86_avx2_psrli_q:
14457 case Intrinsic::x86_sse2_psrai_w:
14458 case Intrinsic::x86_sse2_psrai_d:
14459 case Intrinsic::x86_avx2_psrai_w:
14460 case Intrinsic::x86_avx2_psrai_d: {
14463 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14464 case Intrinsic::x86_sse2_pslli_w:
14465 case Intrinsic::x86_sse2_pslli_d:
14466 case Intrinsic::x86_sse2_pslli_q:
14467 case Intrinsic::x86_avx2_pslli_w:
14468 case Intrinsic::x86_avx2_pslli_d:
14469 case Intrinsic::x86_avx2_pslli_q:
14470 Opcode = X86ISD::VSHLI;
14472 case Intrinsic::x86_sse2_psrli_w:
14473 case Intrinsic::x86_sse2_psrli_d:
14474 case Intrinsic::x86_sse2_psrli_q:
14475 case Intrinsic::x86_avx2_psrli_w:
14476 case Intrinsic::x86_avx2_psrli_d:
14477 case Intrinsic::x86_avx2_psrli_q:
14478 Opcode = X86ISD::VSRLI;
14480 case Intrinsic::x86_sse2_psrai_w:
14481 case Intrinsic::x86_sse2_psrai_d:
14482 case Intrinsic::x86_avx2_psrai_w:
14483 case Intrinsic::x86_avx2_psrai_d:
14484 Opcode = X86ISD::VSRAI;
14487 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14488 Op.getOperand(1), Op.getOperand(2), DAG);
14491 case Intrinsic::x86_sse42_pcmpistria128:
14492 case Intrinsic::x86_sse42_pcmpestria128:
14493 case Intrinsic::x86_sse42_pcmpistric128:
14494 case Intrinsic::x86_sse42_pcmpestric128:
14495 case Intrinsic::x86_sse42_pcmpistrio128:
14496 case Intrinsic::x86_sse42_pcmpestrio128:
14497 case Intrinsic::x86_sse42_pcmpistris128:
14498 case Intrinsic::x86_sse42_pcmpestris128:
14499 case Intrinsic::x86_sse42_pcmpistriz128:
14500 case Intrinsic::x86_sse42_pcmpestriz128: {
14504 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14505 case Intrinsic::x86_sse42_pcmpistria128:
14506 Opcode = X86ISD::PCMPISTRI;
14507 X86CC = X86::COND_A;
14509 case Intrinsic::x86_sse42_pcmpestria128:
14510 Opcode = X86ISD::PCMPESTRI;
14511 X86CC = X86::COND_A;
14513 case Intrinsic::x86_sse42_pcmpistric128:
14514 Opcode = X86ISD::PCMPISTRI;
14515 X86CC = X86::COND_B;
14517 case Intrinsic::x86_sse42_pcmpestric128:
14518 Opcode = X86ISD::PCMPESTRI;
14519 X86CC = X86::COND_B;
14521 case Intrinsic::x86_sse42_pcmpistrio128:
14522 Opcode = X86ISD::PCMPISTRI;
14523 X86CC = X86::COND_O;
14525 case Intrinsic::x86_sse42_pcmpestrio128:
14526 Opcode = X86ISD::PCMPESTRI;
14527 X86CC = X86::COND_O;
14529 case Intrinsic::x86_sse42_pcmpistris128:
14530 Opcode = X86ISD::PCMPISTRI;
14531 X86CC = X86::COND_S;
14533 case Intrinsic::x86_sse42_pcmpestris128:
14534 Opcode = X86ISD::PCMPESTRI;
14535 X86CC = X86::COND_S;
14537 case Intrinsic::x86_sse42_pcmpistriz128:
14538 Opcode = X86ISD::PCMPISTRI;
14539 X86CC = X86::COND_E;
14541 case Intrinsic::x86_sse42_pcmpestriz128:
14542 Opcode = X86ISD::PCMPESTRI;
14543 X86CC = X86::COND_E;
14546 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14547 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14548 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14549 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14550 DAG.getConstant(X86CC, MVT::i8),
14551 SDValue(PCMP.getNode(), 1));
14552 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14555 case Intrinsic::x86_sse42_pcmpistri128:
14556 case Intrinsic::x86_sse42_pcmpestri128: {
14558 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14559 Opcode = X86ISD::PCMPISTRI;
14561 Opcode = X86ISD::PCMPESTRI;
14563 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14564 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14565 return DAG.getNode(Opcode, dl, VTs, NewOps);
14567 case Intrinsic::x86_fma_vfmadd_ps:
14568 case Intrinsic::x86_fma_vfmadd_pd:
14569 case Intrinsic::x86_fma_vfmsub_ps:
14570 case Intrinsic::x86_fma_vfmsub_pd:
14571 case Intrinsic::x86_fma_vfnmadd_ps:
14572 case Intrinsic::x86_fma_vfnmadd_pd:
14573 case Intrinsic::x86_fma_vfnmsub_ps:
14574 case Intrinsic::x86_fma_vfnmsub_pd:
14575 case Intrinsic::x86_fma_vfmaddsub_ps:
14576 case Intrinsic::x86_fma_vfmaddsub_pd:
14577 case Intrinsic::x86_fma_vfmsubadd_ps:
14578 case Intrinsic::x86_fma_vfmsubadd_pd:
14579 case Intrinsic::x86_fma_vfmadd_ps_256:
14580 case Intrinsic::x86_fma_vfmadd_pd_256:
14581 case Intrinsic::x86_fma_vfmsub_ps_256:
14582 case Intrinsic::x86_fma_vfmsub_pd_256:
14583 case Intrinsic::x86_fma_vfnmadd_ps_256:
14584 case Intrinsic::x86_fma_vfnmadd_pd_256:
14585 case Intrinsic::x86_fma_vfnmsub_ps_256:
14586 case Intrinsic::x86_fma_vfnmsub_pd_256:
14587 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14588 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14589 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14590 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14591 case Intrinsic::x86_fma_vfmadd_ps_512:
14592 case Intrinsic::x86_fma_vfmadd_pd_512:
14593 case Intrinsic::x86_fma_vfmsub_ps_512:
14594 case Intrinsic::x86_fma_vfmsub_pd_512:
14595 case Intrinsic::x86_fma_vfnmadd_ps_512:
14596 case Intrinsic::x86_fma_vfnmadd_pd_512:
14597 case Intrinsic::x86_fma_vfnmsub_ps_512:
14598 case Intrinsic::x86_fma_vfnmsub_pd_512:
14599 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14600 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14601 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14602 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14605 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14606 case Intrinsic::x86_fma_vfmadd_ps:
14607 case Intrinsic::x86_fma_vfmadd_pd:
14608 case Intrinsic::x86_fma_vfmadd_ps_256:
14609 case Intrinsic::x86_fma_vfmadd_pd_256:
14610 case Intrinsic::x86_fma_vfmadd_ps_512:
14611 case Intrinsic::x86_fma_vfmadd_pd_512:
14612 Opc = X86ISD::FMADD;
14614 case Intrinsic::x86_fma_vfmsub_ps:
14615 case Intrinsic::x86_fma_vfmsub_pd:
14616 case Intrinsic::x86_fma_vfmsub_ps_256:
14617 case Intrinsic::x86_fma_vfmsub_pd_256:
14618 case Intrinsic::x86_fma_vfmsub_ps_512:
14619 case Intrinsic::x86_fma_vfmsub_pd_512:
14620 Opc = X86ISD::FMSUB;
14622 case Intrinsic::x86_fma_vfnmadd_ps:
14623 case Intrinsic::x86_fma_vfnmadd_pd:
14624 case Intrinsic::x86_fma_vfnmadd_ps_256:
14625 case Intrinsic::x86_fma_vfnmadd_pd_256:
14626 case Intrinsic::x86_fma_vfnmadd_ps_512:
14627 case Intrinsic::x86_fma_vfnmadd_pd_512:
14628 Opc = X86ISD::FNMADD;
14630 case Intrinsic::x86_fma_vfnmsub_ps:
14631 case Intrinsic::x86_fma_vfnmsub_pd:
14632 case Intrinsic::x86_fma_vfnmsub_ps_256:
14633 case Intrinsic::x86_fma_vfnmsub_pd_256:
14634 case Intrinsic::x86_fma_vfnmsub_ps_512:
14635 case Intrinsic::x86_fma_vfnmsub_pd_512:
14636 Opc = X86ISD::FNMSUB;
14638 case Intrinsic::x86_fma_vfmaddsub_ps:
14639 case Intrinsic::x86_fma_vfmaddsub_pd:
14640 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14641 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14642 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14643 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14644 Opc = X86ISD::FMADDSUB;
14646 case Intrinsic::x86_fma_vfmsubadd_ps:
14647 case Intrinsic::x86_fma_vfmsubadd_pd:
14648 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14649 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14650 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14651 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14652 Opc = X86ISD::FMSUBADD;
14656 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14657 Op.getOperand(2), Op.getOperand(3));
14662 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14663 SDValue Src, SDValue Mask, SDValue Base,
14664 SDValue Index, SDValue ScaleOp, SDValue Chain,
14665 const X86Subtarget * Subtarget) {
14667 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14668 assert(C && "Invalid scale type");
14669 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14670 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14671 Index.getSimpleValueType().getVectorNumElements());
14673 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14675 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14677 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14678 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14679 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14680 SDValue Segment = DAG.getRegister(0, MVT::i32);
14681 if (Src.getOpcode() == ISD::UNDEF)
14682 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14683 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14684 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14685 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14686 return DAG.getMergeValues(RetOps, dl);
14689 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14690 SDValue Src, SDValue Mask, SDValue Base,
14691 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14693 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14694 assert(C && "Invalid scale type");
14695 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14696 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14697 SDValue Segment = DAG.getRegister(0, MVT::i32);
14698 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14699 Index.getSimpleValueType().getVectorNumElements());
14701 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14703 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14705 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14706 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14707 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14708 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14709 return SDValue(Res, 1);
14712 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14713 SDValue Mask, SDValue Base, SDValue Index,
14714 SDValue ScaleOp, SDValue Chain) {
14716 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14717 assert(C && "Invalid scale type");
14718 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14719 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14720 SDValue Segment = DAG.getRegister(0, MVT::i32);
14722 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14724 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14726 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14728 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14729 //SDVTList VTs = DAG.getVTList(MVT::Other);
14730 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14731 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14732 return SDValue(Res, 0);
14735 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14736 // read performance monitor counters (x86_rdpmc).
14737 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14738 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14739 SmallVectorImpl<SDValue> &Results) {
14740 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14741 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14744 // The ECX register is used to select the index of the performance counter
14746 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14748 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14750 // Reads the content of a 64-bit performance counter and returns it in the
14751 // registers EDX:EAX.
14752 if (Subtarget->is64Bit()) {
14753 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14754 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14757 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14758 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14761 Chain = HI.getValue(1);
14763 if (Subtarget->is64Bit()) {
14764 // The EAX register is loaded with the low-order 32 bits. The EDX register
14765 // is loaded with the supported high-order bits of the counter.
14766 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14767 DAG.getConstant(32, MVT::i8));
14768 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14769 Results.push_back(Chain);
14773 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14774 SDValue Ops[] = { LO, HI };
14775 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14776 Results.push_back(Pair);
14777 Results.push_back(Chain);
14780 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14781 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14782 // also used to custom lower READCYCLECOUNTER nodes.
14783 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14784 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14785 SmallVectorImpl<SDValue> &Results) {
14786 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14787 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14790 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14791 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14792 // and the EAX register is loaded with the low-order 32 bits.
14793 if (Subtarget->is64Bit()) {
14794 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14795 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14798 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14799 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14802 SDValue Chain = HI.getValue(1);
14804 if (Opcode == X86ISD::RDTSCP_DAG) {
14805 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14807 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14808 // the ECX register. Add 'ecx' explicitly to the chain.
14809 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14811 // Explicitly store the content of ECX at the location passed in input
14812 // to the 'rdtscp' intrinsic.
14813 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14814 MachinePointerInfo(), false, false, 0);
14817 if (Subtarget->is64Bit()) {
14818 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14819 // the EAX register is loaded with the low-order 32 bits.
14820 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14821 DAG.getConstant(32, MVT::i8));
14822 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14823 Results.push_back(Chain);
14827 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14828 SDValue Ops[] = { LO, HI };
14829 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14830 Results.push_back(Pair);
14831 Results.push_back(Chain);
14834 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14835 SelectionDAG &DAG) {
14836 SmallVector<SDValue, 2> Results;
14838 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14840 return DAG.getMergeValues(Results, DL);
14843 enum IntrinsicType {
14844 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14847 struct IntrinsicData {
14848 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14849 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14850 IntrinsicType Type;
14855 std::map < unsigned, IntrinsicData> IntrMap;
14856 static void InitIntinsicsMap() {
14857 static bool Initialized = false;
14860 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14861 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14862 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14863 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14864 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14865 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14866 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14867 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14868 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14869 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14870 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14871 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14872 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14873 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14874 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14875 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14876 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14877 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14879 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14880 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14881 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14882 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14883 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14884 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14885 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14886 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14887 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14888 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14889 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14890 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14891 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14892 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14893 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14894 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14896 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14897 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14898 X86::VGATHERPF1QPSm)));
14899 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14900 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14901 X86::VGATHERPF1QPDm)));
14902 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14903 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14904 X86::VGATHERPF1DPDm)));
14905 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14906 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14907 X86::VGATHERPF1DPSm)));
14908 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14909 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14910 X86::VSCATTERPF1QPSm)));
14911 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14912 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14913 X86::VSCATTERPF1QPDm)));
14914 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14915 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14916 X86::VSCATTERPF1DPDm)));
14917 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14918 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14919 X86::VSCATTERPF1DPSm)));
14920 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14921 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14922 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14923 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14924 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14925 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14926 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14927 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14928 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14929 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14930 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14931 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14932 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14933 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14934 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14935 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14936 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14937 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14938 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14939 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14940 Initialized = true;
14943 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14944 SelectionDAG &DAG) {
14945 InitIntinsicsMap();
14946 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14947 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14948 if (itr == IntrMap.end())
14952 IntrinsicData Intr = itr->second;
14953 switch(Intr.Type) {
14956 // Emit the node with the right value type.
14957 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14958 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14960 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14961 // Otherwise return the value from Rand, which is always 0, casted to i32.
14962 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14963 DAG.getConstant(1, Op->getValueType(1)),
14964 DAG.getConstant(X86::COND_B, MVT::i32),
14965 SDValue(Result.getNode(), 1) };
14966 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14967 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14970 // Return { result, isValid, chain }.
14971 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14972 SDValue(Result.getNode(), 2));
14975 //gather(v1, mask, index, base, scale);
14976 SDValue Chain = Op.getOperand(0);
14977 SDValue Src = Op.getOperand(2);
14978 SDValue Base = Op.getOperand(3);
14979 SDValue Index = Op.getOperand(4);
14980 SDValue Mask = Op.getOperand(5);
14981 SDValue Scale = Op.getOperand(6);
14982 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14986 //scatter(base, mask, index, v1, scale);
14987 SDValue Chain = Op.getOperand(0);
14988 SDValue Base = Op.getOperand(2);
14989 SDValue Mask = Op.getOperand(3);
14990 SDValue Index = Op.getOperand(4);
14991 SDValue Src = Op.getOperand(5);
14992 SDValue Scale = Op.getOperand(6);
14993 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14996 SDValue Hint = Op.getOperand(6);
14998 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14999 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15000 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15001 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15002 SDValue Chain = Op.getOperand(0);
15003 SDValue Mask = Op.getOperand(2);
15004 SDValue Index = Op.getOperand(3);
15005 SDValue Base = Op.getOperand(4);
15006 SDValue Scale = Op.getOperand(5);
15007 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15009 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15011 SmallVector<SDValue, 2> Results;
15012 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15013 return DAG.getMergeValues(Results, dl);
15015 // Read Performance Monitoring Counters.
15017 SmallVector<SDValue, 2> Results;
15018 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15019 return DAG.getMergeValues(Results, dl);
15021 // XTEST intrinsics.
15023 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15024 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15025 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15026 DAG.getConstant(X86::COND_NE, MVT::i8),
15028 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15029 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15030 Ret, SDValue(InTrans.getNode(), 1));
15033 llvm_unreachable("Unknown Intrinsic Type");
15036 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15037 SelectionDAG &DAG) const {
15038 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15039 MFI->setReturnAddressIsTaken(true);
15041 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15044 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15046 EVT PtrVT = getPointerTy();
15049 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15050 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15051 DAG.getSubtarget().getRegisterInfo());
15052 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15053 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15054 DAG.getNode(ISD::ADD, dl, PtrVT,
15055 FrameAddr, Offset),
15056 MachinePointerInfo(), false, false, false, 0);
15059 // Just load the return address.
15060 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15061 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15062 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15065 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15066 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15067 MFI->setFrameAddressIsTaken(true);
15069 EVT VT = Op.getValueType();
15070 SDLoc dl(Op); // FIXME probably not meaningful
15071 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15072 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15073 DAG.getSubtarget().getRegisterInfo());
15074 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15075 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15076 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15077 "Invalid Frame Register!");
15078 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15080 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15081 MachinePointerInfo(),
15082 false, false, false, 0);
15086 // FIXME? Maybe this could be a TableGen attribute on some registers and
15087 // this table could be generated automatically from RegInfo.
15088 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15090 unsigned Reg = StringSwitch<unsigned>(RegName)
15091 .Case("esp", X86::ESP)
15092 .Case("rsp", X86::RSP)
15096 report_fatal_error("Invalid register name global variable");
15099 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15100 SelectionDAG &DAG) const {
15101 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15102 DAG.getSubtarget().getRegisterInfo());
15103 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15106 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15107 SDValue Chain = Op.getOperand(0);
15108 SDValue Offset = Op.getOperand(1);
15109 SDValue Handler = Op.getOperand(2);
15112 EVT PtrVT = getPointerTy();
15113 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15114 DAG.getSubtarget().getRegisterInfo());
15115 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15116 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15117 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15118 "Invalid Frame Register!");
15119 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15120 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15122 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15123 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15124 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15125 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15127 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15129 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15130 DAG.getRegister(StoreAddrReg, PtrVT));
15133 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15134 SelectionDAG &DAG) const {
15136 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15137 DAG.getVTList(MVT::i32, MVT::Other),
15138 Op.getOperand(0), Op.getOperand(1));
15141 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15142 SelectionDAG &DAG) const {
15144 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15145 Op.getOperand(0), Op.getOperand(1));
15148 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15149 return Op.getOperand(0);
15152 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15153 SelectionDAG &DAG) const {
15154 SDValue Root = Op.getOperand(0);
15155 SDValue Trmp = Op.getOperand(1); // trampoline
15156 SDValue FPtr = Op.getOperand(2); // nested function
15157 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15160 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15161 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15163 if (Subtarget->is64Bit()) {
15164 SDValue OutChains[6];
15166 // Large code-model.
15167 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15168 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15170 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15171 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15173 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15175 // Load the pointer to the nested function into R11.
15176 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15177 SDValue Addr = Trmp;
15178 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15179 Addr, MachinePointerInfo(TrmpAddr),
15182 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15183 DAG.getConstant(2, MVT::i64));
15184 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15185 MachinePointerInfo(TrmpAddr, 2),
15188 // Load the 'nest' parameter value into R10.
15189 // R10 is specified in X86CallingConv.td
15190 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15191 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15192 DAG.getConstant(10, MVT::i64));
15193 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15194 Addr, MachinePointerInfo(TrmpAddr, 10),
15197 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15198 DAG.getConstant(12, MVT::i64));
15199 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15200 MachinePointerInfo(TrmpAddr, 12),
15203 // Jump to the nested function.
15204 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15205 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15206 DAG.getConstant(20, MVT::i64));
15207 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15208 Addr, MachinePointerInfo(TrmpAddr, 20),
15211 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15212 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15213 DAG.getConstant(22, MVT::i64));
15214 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15215 MachinePointerInfo(TrmpAddr, 22),
15218 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15220 const Function *Func =
15221 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15222 CallingConv::ID CC = Func->getCallingConv();
15227 llvm_unreachable("Unsupported calling convention");
15228 case CallingConv::C:
15229 case CallingConv::X86_StdCall: {
15230 // Pass 'nest' parameter in ECX.
15231 // Must be kept in sync with X86CallingConv.td
15232 NestReg = X86::ECX;
15234 // Check that ECX wasn't needed by an 'inreg' parameter.
15235 FunctionType *FTy = Func->getFunctionType();
15236 const AttributeSet &Attrs = Func->getAttributes();
15238 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15239 unsigned InRegCount = 0;
15242 for (FunctionType::param_iterator I = FTy->param_begin(),
15243 E = FTy->param_end(); I != E; ++I, ++Idx)
15244 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15245 // FIXME: should only count parameters that are lowered to integers.
15246 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15248 if (InRegCount > 2) {
15249 report_fatal_error("Nest register in use - reduce number of inreg"
15255 case CallingConv::X86_FastCall:
15256 case CallingConv::X86_ThisCall:
15257 case CallingConv::Fast:
15258 // Pass 'nest' parameter in EAX.
15259 // Must be kept in sync with X86CallingConv.td
15260 NestReg = X86::EAX;
15264 SDValue OutChains[4];
15265 SDValue Addr, Disp;
15267 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15268 DAG.getConstant(10, MVT::i32));
15269 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15271 // This is storing the opcode for MOV32ri.
15272 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15273 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15274 OutChains[0] = DAG.getStore(Root, dl,
15275 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15276 Trmp, MachinePointerInfo(TrmpAddr),
15279 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15280 DAG.getConstant(1, MVT::i32));
15281 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15282 MachinePointerInfo(TrmpAddr, 1),
15285 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15286 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15287 DAG.getConstant(5, MVT::i32));
15288 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15289 MachinePointerInfo(TrmpAddr, 5),
15292 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15293 DAG.getConstant(6, MVT::i32));
15294 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15295 MachinePointerInfo(TrmpAddr, 6),
15298 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15302 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15303 SelectionDAG &DAG) const {
15305 The rounding mode is in bits 11:10 of FPSR, and has the following
15307 00 Round to nearest
15312 FLT_ROUNDS, on the other hand, expects the following:
15319 To perform the conversion, we do:
15320 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15323 MachineFunction &MF = DAG.getMachineFunction();
15324 const TargetMachine &TM = MF.getTarget();
15325 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15326 unsigned StackAlignment = TFI.getStackAlignment();
15327 MVT VT = Op.getSimpleValueType();
15330 // Save FP Control Word to stack slot
15331 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15332 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15334 MachineMemOperand *MMO =
15335 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15336 MachineMemOperand::MOStore, 2, 2);
15338 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15339 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15340 DAG.getVTList(MVT::Other),
15341 Ops, MVT::i16, MMO);
15343 // Load FP Control Word from stack slot
15344 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15345 MachinePointerInfo(), false, false, false, 0);
15347 // Transform as necessary
15349 DAG.getNode(ISD::SRL, DL, MVT::i16,
15350 DAG.getNode(ISD::AND, DL, MVT::i16,
15351 CWD, DAG.getConstant(0x800, MVT::i16)),
15352 DAG.getConstant(11, MVT::i8));
15354 DAG.getNode(ISD::SRL, DL, MVT::i16,
15355 DAG.getNode(ISD::AND, DL, MVT::i16,
15356 CWD, DAG.getConstant(0x400, MVT::i16)),
15357 DAG.getConstant(9, MVT::i8));
15360 DAG.getNode(ISD::AND, DL, MVT::i16,
15361 DAG.getNode(ISD::ADD, DL, MVT::i16,
15362 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15363 DAG.getConstant(1, MVT::i16)),
15364 DAG.getConstant(3, MVT::i16));
15366 return DAG.getNode((VT.getSizeInBits() < 16 ?
15367 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15370 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15371 MVT VT = Op.getSimpleValueType();
15373 unsigned NumBits = VT.getSizeInBits();
15376 Op = Op.getOperand(0);
15377 if (VT == MVT::i8) {
15378 // Zero extend to i32 since there is not an i8 bsr.
15380 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15383 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15384 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15385 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15387 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15390 DAG.getConstant(NumBits+NumBits-1, OpVT),
15391 DAG.getConstant(X86::COND_E, MVT::i8),
15394 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15396 // Finally xor with NumBits-1.
15397 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15400 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15404 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15405 MVT VT = Op.getSimpleValueType();
15407 unsigned NumBits = VT.getSizeInBits();
15410 Op = Op.getOperand(0);
15411 if (VT == MVT::i8) {
15412 // Zero extend to i32 since there is not an i8 bsr.
15414 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15417 // Issue a bsr (scan bits in reverse).
15418 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15419 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15421 // And xor with NumBits-1.
15422 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15425 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15429 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15430 MVT VT = Op.getSimpleValueType();
15431 unsigned NumBits = VT.getSizeInBits();
15433 Op = Op.getOperand(0);
15435 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15436 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15437 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15439 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15442 DAG.getConstant(NumBits, VT),
15443 DAG.getConstant(X86::COND_E, MVT::i8),
15446 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15449 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15450 // ones, and then concatenate the result back.
15451 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15452 MVT VT = Op.getSimpleValueType();
15454 assert(VT.is256BitVector() && VT.isInteger() &&
15455 "Unsupported value type for operation");
15457 unsigned NumElems = VT.getVectorNumElements();
15460 // Extract the LHS vectors
15461 SDValue LHS = Op.getOperand(0);
15462 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15463 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15465 // Extract the RHS vectors
15466 SDValue RHS = Op.getOperand(1);
15467 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15468 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15470 MVT EltVT = VT.getVectorElementType();
15471 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15473 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15474 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15475 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15478 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15479 assert(Op.getSimpleValueType().is256BitVector() &&
15480 Op.getSimpleValueType().isInteger() &&
15481 "Only handle AVX 256-bit vector integer operation");
15482 return Lower256IntArith(Op, DAG);
15485 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15486 assert(Op.getSimpleValueType().is256BitVector() &&
15487 Op.getSimpleValueType().isInteger() &&
15488 "Only handle AVX 256-bit vector integer operation");
15489 return Lower256IntArith(Op, DAG);
15492 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15493 SelectionDAG &DAG) {
15495 MVT VT = Op.getSimpleValueType();
15497 // Decompose 256-bit ops into smaller 128-bit ops.
15498 if (VT.is256BitVector() && !Subtarget->hasInt256())
15499 return Lower256IntArith(Op, DAG);
15501 SDValue A = Op.getOperand(0);
15502 SDValue B = Op.getOperand(1);
15504 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15505 if (VT == MVT::v4i32) {
15506 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15507 "Should not custom lower when pmuldq is available!");
15509 // Extract the odd parts.
15510 static const int UnpackMask[] = { 1, -1, 3, -1 };
15511 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15512 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15514 // Multiply the even parts.
15515 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15516 // Now multiply odd parts.
15517 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15519 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15520 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15522 // Merge the two vectors back together with a shuffle. This expands into 2
15524 static const int ShufMask[] = { 0, 4, 2, 6 };
15525 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15528 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15529 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15531 // Ahi = psrlqi(a, 32);
15532 // Bhi = psrlqi(b, 32);
15534 // AloBlo = pmuludq(a, b);
15535 // AloBhi = pmuludq(a, Bhi);
15536 // AhiBlo = pmuludq(Ahi, b);
15538 // AloBhi = psllqi(AloBhi, 32);
15539 // AhiBlo = psllqi(AhiBlo, 32);
15540 // return AloBlo + AloBhi + AhiBlo;
15542 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15543 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15545 // Bit cast to 32-bit vectors for MULUDQ
15546 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15547 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15548 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15549 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15550 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15551 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15553 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15554 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15555 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15557 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15558 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15560 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15561 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15564 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15565 assert(Subtarget->isTargetWin64() && "Unexpected target");
15566 EVT VT = Op.getValueType();
15567 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15568 "Unexpected return type for lowering");
15572 switch (Op->getOpcode()) {
15573 default: llvm_unreachable("Unexpected request for libcall!");
15574 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15575 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15576 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15577 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15578 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15579 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15583 SDValue InChain = DAG.getEntryNode();
15585 TargetLowering::ArgListTy Args;
15586 TargetLowering::ArgListEntry Entry;
15587 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15588 EVT ArgVT = Op->getOperand(i).getValueType();
15589 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15590 "Unexpected argument type for lowering");
15591 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15592 Entry.Node = StackPtr;
15593 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15595 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15596 Entry.Ty = PointerType::get(ArgTy,0);
15597 Entry.isSExt = false;
15598 Entry.isZExt = false;
15599 Args.push_back(Entry);
15602 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15605 TargetLowering::CallLoweringInfo CLI(DAG);
15606 CLI.setDebugLoc(dl).setChain(InChain)
15607 .setCallee(getLibcallCallingConv(LC),
15608 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15609 Callee, std::move(Args), 0)
15610 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15612 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15613 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15616 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15617 SelectionDAG &DAG) {
15618 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15619 EVT VT = Op0.getValueType();
15622 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15623 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15625 // PMULxD operations multiply each even value (starting at 0) of LHS with
15626 // the related value of RHS and produce a widen result.
15627 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15628 // => <2 x i64> <ae|cg>
15630 // In other word, to have all the results, we need to perform two PMULxD:
15631 // 1. one with the even values.
15632 // 2. one with the odd values.
15633 // To achieve #2, with need to place the odd values at an even position.
15635 // Place the odd value at an even position (basically, shift all values 1
15636 // step to the left):
15637 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15638 // <a|b|c|d> => <b|undef|d|undef>
15639 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15640 // <e|f|g|h> => <f|undef|h|undef>
15641 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15643 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15645 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15646 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15648 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15649 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15650 // => <2 x i64> <ae|cg>
15651 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15652 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15653 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15654 // => <2 x i64> <bf|dh>
15655 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15656 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15658 // Shuffle it back into the right order.
15659 SDValue Highs, Lows;
15660 if (VT == MVT::v8i32) {
15661 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15662 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15663 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15664 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15666 const int HighMask[] = {1, 5, 3, 7};
15667 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15668 const int LowMask[] = {1, 4, 2, 6};
15669 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15672 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15673 // unsigned multiply.
15674 if (IsSigned && !Subtarget->hasSSE41()) {
15676 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15677 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15678 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15679 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15680 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15682 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15683 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15686 // The first result of MUL_LOHI is actually the low value, followed by the
15688 SDValue Ops[] = {Lows, Highs};
15689 return DAG.getMergeValues(Ops, dl);
15692 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15693 const X86Subtarget *Subtarget) {
15694 MVT VT = Op.getSimpleValueType();
15696 SDValue R = Op.getOperand(0);
15697 SDValue Amt = Op.getOperand(1);
15699 // Optimize shl/srl/sra with constant shift amount.
15700 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15701 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15702 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15704 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15705 (Subtarget->hasInt256() &&
15706 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15707 (Subtarget->hasAVX512() &&
15708 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15709 if (Op.getOpcode() == ISD::SHL)
15710 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15712 if (Op.getOpcode() == ISD::SRL)
15713 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15715 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15716 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15720 if (VT == MVT::v16i8) {
15721 if (Op.getOpcode() == ISD::SHL) {
15722 // Make a large shift.
15723 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15724 MVT::v8i16, R, ShiftAmt,
15726 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15727 // Zero out the rightmost bits.
15728 SmallVector<SDValue, 16> V(16,
15729 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15731 return DAG.getNode(ISD::AND, dl, VT, SHL,
15732 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15734 if (Op.getOpcode() == ISD::SRL) {
15735 // Make a large shift.
15736 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15737 MVT::v8i16, R, ShiftAmt,
15739 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15740 // Zero out the leftmost bits.
15741 SmallVector<SDValue, 16> V(16,
15742 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15744 return DAG.getNode(ISD::AND, dl, VT, SRL,
15745 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15747 if (Op.getOpcode() == ISD::SRA) {
15748 if (ShiftAmt == 7) {
15749 // R s>> 7 === R s< 0
15750 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15751 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15754 // R s>> a === ((R u>> a) ^ m) - m
15755 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15756 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15758 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15759 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15760 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15763 llvm_unreachable("Unknown shift opcode.");
15766 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15767 if (Op.getOpcode() == ISD::SHL) {
15768 // Make a large shift.
15769 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15770 MVT::v16i16, R, ShiftAmt,
15772 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15773 // Zero out the rightmost bits.
15774 SmallVector<SDValue, 32> V(32,
15775 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15777 return DAG.getNode(ISD::AND, dl, VT, SHL,
15778 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15780 if (Op.getOpcode() == ISD::SRL) {
15781 // Make a large shift.
15782 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15783 MVT::v16i16, R, ShiftAmt,
15785 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15786 // Zero out the leftmost bits.
15787 SmallVector<SDValue, 32> V(32,
15788 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15790 return DAG.getNode(ISD::AND, dl, VT, SRL,
15791 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15793 if (Op.getOpcode() == ISD::SRA) {
15794 if (ShiftAmt == 7) {
15795 // R s>> 7 === R s< 0
15796 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15797 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15800 // R s>> a === ((R u>> a) ^ m) - m
15801 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15802 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15804 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15805 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15806 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15809 llvm_unreachable("Unknown shift opcode.");
15814 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15815 if (!Subtarget->is64Bit() &&
15816 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15817 Amt.getOpcode() == ISD::BITCAST &&
15818 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15819 Amt = Amt.getOperand(0);
15820 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15821 VT.getVectorNumElements();
15822 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15823 uint64_t ShiftAmt = 0;
15824 for (unsigned i = 0; i != Ratio; ++i) {
15825 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15829 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15831 // Check remaining shift amounts.
15832 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15833 uint64_t ShAmt = 0;
15834 for (unsigned j = 0; j != Ratio; ++j) {
15835 ConstantSDNode *C =
15836 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15840 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15842 if (ShAmt != ShiftAmt)
15845 switch (Op.getOpcode()) {
15847 llvm_unreachable("Unknown shift opcode!");
15849 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15852 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15855 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15863 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15864 const X86Subtarget* Subtarget) {
15865 MVT VT = Op.getSimpleValueType();
15867 SDValue R = Op.getOperand(0);
15868 SDValue Amt = Op.getOperand(1);
15870 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15871 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15872 (Subtarget->hasInt256() &&
15873 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15874 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15875 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15877 EVT EltVT = VT.getVectorElementType();
15879 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15880 unsigned NumElts = VT.getVectorNumElements();
15882 for (i = 0; i != NumElts; ++i) {
15883 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15887 for (j = i; j != NumElts; ++j) {
15888 SDValue Arg = Amt.getOperand(j);
15889 if (Arg.getOpcode() == ISD::UNDEF) continue;
15890 if (Arg != Amt.getOperand(i))
15893 if (i != NumElts && j == NumElts)
15894 BaseShAmt = Amt.getOperand(i);
15896 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15897 Amt = Amt.getOperand(0);
15898 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15899 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15900 SDValue InVec = Amt.getOperand(0);
15901 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15902 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15904 for (; i != NumElts; ++i) {
15905 SDValue Arg = InVec.getOperand(i);
15906 if (Arg.getOpcode() == ISD::UNDEF) continue;
15910 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15911 if (ConstantSDNode *C =
15912 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15913 unsigned SplatIdx =
15914 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15915 if (C->getZExtValue() == SplatIdx)
15916 BaseShAmt = InVec.getOperand(1);
15919 if (!BaseShAmt.getNode())
15920 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15921 DAG.getIntPtrConstant(0));
15925 if (BaseShAmt.getNode()) {
15926 if (EltVT.bitsGT(MVT::i32))
15927 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15928 else if (EltVT.bitsLT(MVT::i32))
15929 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15931 switch (Op.getOpcode()) {
15933 llvm_unreachable("Unknown shift opcode!");
15935 switch (VT.SimpleTy) {
15936 default: return SDValue();
15945 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15948 switch (VT.SimpleTy) {
15949 default: return SDValue();
15956 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15959 switch (VT.SimpleTy) {
15960 default: return SDValue();
15969 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15975 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15976 if (!Subtarget->is64Bit() &&
15977 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15978 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15979 Amt.getOpcode() == ISD::BITCAST &&
15980 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15981 Amt = Amt.getOperand(0);
15982 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15983 VT.getVectorNumElements();
15984 std::vector<SDValue> Vals(Ratio);
15985 for (unsigned i = 0; i != Ratio; ++i)
15986 Vals[i] = Amt.getOperand(i);
15987 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15988 for (unsigned j = 0; j != Ratio; ++j)
15989 if (Vals[j] != Amt.getOperand(i + j))
15992 switch (Op.getOpcode()) {
15994 llvm_unreachable("Unknown shift opcode!");
15996 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15998 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16000 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16007 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16008 SelectionDAG &DAG) {
16009 MVT VT = Op.getSimpleValueType();
16011 SDValue R = Op.getOperand(0);
16012 SDValue Amt = Op.getOperand(1);
16015 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16016 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16018 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16022 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16026 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16028 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16029 if (Subtarget->hasInt256()) {
16030 if (Op.getOpcode() == ISD::SRL &&
16031 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16032 VT == MVT::v4i64 || VT == MVT::v8i32))
16034 if (Op.getOpcode() == ISD::SHL &&
16035 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16036 VT == MVT::v4i64 || VT == MVT::v8i32))
16038 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16042 // If possible, lower this packed shift into a vector multiply instead of
16043 // expanding it into a sequence of scalar shifts.
16044 // Do this only if the vector shift count is a constant build_vector.
16045 if (Op.getOpcode() == ISD::SHL &&
16046 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16047 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16048 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16049 SmallVector<SDValue, 8> Elts;
16050 EVT SVT = VT.getScalarType();
16051 unsigned SVTBits = SVT.getSizeInBits();
16052 const APInt &One = APInt(SVTBits, 1);
16053 unsigned NumElems = VT.getVectorNumElements();
16055 for (unsigned i=0; i !=NumElems; ++i) {
16056 SDValue Op = Amt->getOperand(i);
16057 if (Op->getOpcode() == ISD::UNDEF) {
16058 Elts.push_back(Op);
16062 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16063 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16064 uint64_t ShAmt = C.getZExtValue();
16065 if (ShAmt >= SVTBits) {
16066 Elts.push_back(DAG.getUNDEF(SVT));
16069 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16071 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16072 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16075 // Lower SHL with variable shift amount.
16076 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16077 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16079 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16080 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16081 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16082 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16085 // If possible, lower this shift as a sequence of two shifts by
16086 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16088 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16090 // Could be rewritten as:
16091 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16093 // The advantage is that the two shifts from the example would be
16094 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16095 // the vector shift into four scalar shifts plus four pairs of vector
16097 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16098 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16099 unsigned TargetOpcode = X86ISD::MOVSS;
16100 bool CanBeSimplified;
16101 // The splat value for the first packed shift (the 'X' from the example).
16102 SDValue Amt1 = Amt->getOperand(0);
16103 // The splat value for the second packed shift (the 'Y' from the example).
16104 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16105 Amt->getOperand(2);
16107 // See if it is possible to replace this node with a sequence of
16108 // two shifts followed by a MOVSS/MOVSD
16109 if (VT == MVT::v4i32) {
16110 // Check if it is legal to use a MOVSS.
16111 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16112 Amt2 == Amt->getOperand(3);
16113 if (!CanBeSimplified) {
16114 // Otherwise, check if we can still simplify this node using a MOVSD.
16115 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16116 Amt->getOperand(2) == Amt->getOperand(3);
16117 TargetOpcode = X86ISD::MOVSD;
16118 Amt2 = Amt->getOperand(2);
16121 // Do similar checks for the case where the machine value type
16123 CanBeSimplified = Amt1 == Amt->getOperand(1);
16124 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16125 CanBeSimplified = Amt2 == Amt->getOperand(i);
16127 if (!CanBeSimplified) {
16128 TargetOpcode = X86ISD::MOVSD;
16129 CanBeSimplified = true;
16130 Amt2 = Amt->getOperand(4);
16131 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16132 CanBeSimplified = Amt1 == Amt->getOperand(i);
16133 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16134 CanBeSimplified = Amt2 == Amt->getOperand(j);
16138 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16139 isa<ConstantSDNode>(Amt2)) {
16140 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16141 EVT CastVT = MVT::v4i32;
16143 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16144 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16146 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16147 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16148 if (TargetOpcode == X86ISD::MOVSD)
16149 CastVT = MVT::v2i64;
16150 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16151 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16152 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16154 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16158 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16159 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16162 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16163 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16165 // Turn 'a' into a mask suitable for VSELECT
16166 SDValue VSelM = DAG.getConstant(0x80, VT);
16167 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16168 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16170 SDValue CM1 = DAG.getConstant(0x0f, VT);
16171 SDValue CM2 = DAG.getConstant(0x3f, VT);
16173 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16174 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16175 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16176 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16177 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16180 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16181 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16182 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16184 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16185 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16186 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16187 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16188 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16191 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16192 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16193 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16195 // return VSELECT(r, r+r, a);
16196 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16197 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16201 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16202 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16203 // solution better.
16204 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16205 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16207 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16208 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16209 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16210 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16211 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16214 // Decompose 256-bit shifts into smaller 128-bit shifts.
16215 if (VT.is256BitVector()) {
16216 unsigned NumElems = VT.getVectorNumElements();
16217 MVT EltVT = VT.getVectorElementType();
16218 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16220 // Extract the two vectors
16221 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16222 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16224 // Recreate the shift amount vectors
16225 SDValue Amt1, Amt2;
16226 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16227 // Constant shift amount
16228 SmallVector<SDValue, 4> Amt1Csts;
16229 SmallVector<SDValue, 4> Amt2Csts;
16230 for (unsigned i = 0; i != NumElems/2; ++i)
16231 Amt1Csts.push_back(Amt->getOperand(i));
16232 for (unsigned i = NumElems/2; i != NumElems; ++i)
16233 Amt2Csts.push_back(Amt->getOperand(i));
16235 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16236 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16238 // Variable shift amount
16239 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16240 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16243 // Issue new vector shifts for the smaller types
16244 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16245 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16247 // Concatenate the result back
16248 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16254 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16255 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16256 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16257 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16258 // has only one use.
16259 SDNode *N = Op.getNode();
16260 SDValue LHS = N->getOperand(0);
16261 SDValue RHS = N->getOperand(1);
16262 unsigned BaseOp = 0;
16265 switch (Op.getOpcode()) {
16266 default: llvm_unreachable("Unknown ovf instruction!");
16268 // A subtract of one will be selected as a INC. Note that INC doesn't
16269 // set CF, so we can't do this for UADDO.
16270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16272 BaseOp = X86ISD::INC;
16273 Cond = X86::COND_O;
16276 BaseOp = X86ISD::ADD;
16277 Cond = X86::COND_O;
16280 BaseOp = X86ISD::ADD;
16281 Cond = X86::COND_B;
16284 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16285 // set CF, so we can't do this for USUBO.
16286 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16288 BaseOp = X86ISD::DEC;
16289 Cond = X86::COND_O;
16292 BaseOp = X86ISD::SUB;
16293 Cond = X86::COND_O;
16296 BaseOp = X86ISD::SUB;
16297 Cond = X86::COND_B;
16300 BaseOp = X86ISD::SMUL;
16301 Cond = X86::COND_O;
16303 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16304 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16306 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16309 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16310 DAG.getConstant(X86::COND_O, MVT::i32),
16311 SDValue(Sum.getNode(), 2));
16313 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16317 // Also sets EFLAGS.
16318 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16319 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16322 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16323 DAG.getConstant(Cond, MVT::i32),
16324 SDValue(Sum.getNode(), 1));
16326 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16329 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16330 SelectionDAG &DAG) const {
16332 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16333 MVT VT = Op.getSimpleValueType();
16335 if (!Subtarget->hasSSE2() || !VT.isVector())
16338 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16339 ExtraVT.getScalarType().getSizeInBits();
16341 switch (VT.SimpleTy) {
16342 default: return SDValue();
16345 if (!Subtarget->hasFp256())
16347 if (!Subtarget->hasInt256()) {
16348 // needs to be split
16349 unsigned NumElems = VT.getVectorNumElements();
16351 // Extract the LHS vectors
16352 SDValue LHS = Op.getOperand(0);
16353 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16354 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16356 MVT EltVT = VT.getVectorElementType();
16357 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16359 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16360 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16361 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16363 SDValue Extra = DAG.getValueType(ExtraVT);
16365 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16366 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16368 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16373 SDValue Op0 = Op.getOperand(0);
16374 SDValue Op00 = Op0.getOperand(0);
16376 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16377 if (Op0.getOpcode() == ISD::BITCAST &&
16378 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16379 // (sext (vzext x)) -> (vsext x)
16380 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16381 if (Tmp1.getNode()) {
16382 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16383 // This folding is only valid when the in-reg type is a vector of i8,
16385 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16386 ExtraEltVT == MVT::i32) {
16387 SDValue Tmp1Op0 = Tmp1.getOperand(0);
16388 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16389 "This optimization is invalid without a VZEXT.");
16390 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16396 // If the above didn't work, then just use Shift-Left + Shift-Right.
16397 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16399 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16405 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16406 SelectionDAG &DAG) {
16408 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16409 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16410 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16411 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16413 // The only fence that needs an instruction is a sequentially-consistent
16414 // cross-thread fence.
16415 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16416 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16417 // no-sse2). There isn't any reason to disable it if the target processor
16419 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16420 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16422 SDValue Chain = Op.getOperand(0);
16423 SDValue Zero = DAG.getConstant(0, MVT::i32);
16425 DAG.getRegister(X86::ESP, MVT::i32), // Base
16426 DAG.getTargetConstant(1, MVT::i8), // Scale
16427 DAG.getRegister(0, MVT::i32), // Index
16428 DAG.getTargetConstant(0, MVT::i32), // Disp
16429 DAG.getRegister(0, MVT::i32), // Segment.
16433 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16434 return SDValue(Res, 0);
16437 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16438 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16441 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16442 SelectionDAG &DAG) {
16443 MVT T = Op.getSimpleValueType();
16447 switch(T.SimpleTy) {
16448 default: llvm_unreachable("Invalid value type!");
16449 case MVT::i8: Reg = X86::AL; size = 1; break;
16450 case MVT::i16: Reg = X86::AX; size = 2; break;
16451 case MVT::i32: Reg = X86::EAX; size = 4; break;
16453 assert(Subtarget->is64Bit() && "Node not type legal!");
16454 Reg = X86::RAX; size = 8;
16457 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16458 Op.getOperand(2), SDValue());
16459 SDValue Ops[] = { cpIn.getValue(0),
16462 DAG.getTargetConstant(size, MVT::i8),
16463 cpIn.getValue(1) };
16464 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16465 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16466 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16470 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16471 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16472 MVT::i32, cpOut.getValue(2));
16473 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16474 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16476 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16477 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16478 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16482 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16483 SelectionDAG &DAG) {
16484 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16485 MVT DstVT = Op.getSimpleValueType();
16487 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16488 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16489 if (DstVT != MVT::f64)
16490 // This conversion needs to be expanded.
16493 SDValue InVec = Op->getOperand(0);
16495 unsigned NumElts = SrcVT.getVectorNumElements();
16496 EVT SVT = SrcVT.getVectorElementType();
16498 // Widen the vector in input in the case of MVT::v2i32.
16499 // Example: from MVT::v2i32 to MVT::v4i32.
16500 SmallVector<SDValue, 16> Elts;
16501 for (unsigned i = 0, e = NumElts; i != e; ++i)
16502 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16503 DAG.getIntPtrConstant(i)));
16505 // Explicitly mark the extra elements as Undef.
16506 SDValue Undef = DAG.getUNDEF(SVT);
16507 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16508 Elts.push_back(Undef);
16510 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16511 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16512 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16513 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16514 DAG.getIntPtrConstant(0));
16517 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16518 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16519 assert((DstVT == MVT::i64 ||
16520 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16521 "Unexpected custom BITCAST");
16522 // i64 <=> MMX conversions are Legal.
16523 if (SrcVT==MVT::i64 && DstVT.isVector())
16525 if (DstVT==MVT::i64 && SrcVT.isVector())
16527 // MMX <=> MMX conversions are Legal.
16528 if (SrcVT.isVector() && DstVT.isVector())
16530 // All other conversions need to be expanded.
16534 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16535 SDNode *Node = Op.getNode();
16537 EVT T = Node->getValueType(0);
16538 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16539 DAG.getConstant(0, T), Node->getOperand(2));
16540 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16541 cast<AtomicSDNode>(Node)->getMemoryVT(),
16542 Node->getOperand(0),
16543 Node->getOperand(1), negOp,
16544 cast<AtomicSDNode>(Node)->getMemOperand(),
16545 cast<AtomicSDNode>(Node)->getOrdering(),
16546 cast<AtomicSDNode>(Node)->getSynchScope());
16549 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16550 SDNode *Node = Op.getNode();
16552 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16554 // Convert seq_cst store -> xchg
16555 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16556 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16557 // (The only way to get a 16-byte store is cmpxchg16b)
16558 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16559 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16560 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16561 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16562 cast<AtomicSDNode>(Node)->getMemoryVT(),
16563 Node->getOperand(0),
16564 Node->getOperand(1), Node->getOperand(2),
16565 cast<AtomicSDNode>(Node)->getMemOperand(),
16566 cast<AtomicSDNode>(Node)->getOrdering(),
16567 cast<AtomicSDNode>(Node)->getSynchScope());
16568 return Swap.getValue(1);
16570 // Other atomic stores have a simple pattern.
16574 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16575 EVT VT = Op.getNode()->getSimpleValueType(0);
16577 // Let legalize expand this if it isn't a legal type yet.
16578 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16581 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16584 bool ExtraOp = false;
16585 switch (Op.getOpcode()) {
16586 default: llvm_unreachable("Invalid code");
16587 case ISD::ADDC: Opc = X86ISD::ADD; break;
16588 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16589 case ISD::SUBC: Opc = X86ISD::SUB; break;
16590 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16594 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16596 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16597 Op.getOperand(1), Op.getOperand(2));
16600 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16601 SelectionDAG &DAG) {
16602 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16604 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16605 // which returns the values as { float, float } (in XMM0) or
16606 // { double, double } (which is returned in XMM0, XMM1).
16608 SDValue Arg = Op.getOperand(0);
16609 EVT ArgVT = Arg.getValueType();
16610 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16612 TargetLowering::ArgListTy Args;
16613 TargetLowering::ArgListEntry Entry;
16617 Entry.isSExt = false;
16618 Entry.isZExt = false;
16619 Args.push_back(Entry);
16621 bool isF64 = ArgVT == MVT::f64;
16622 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16623 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16624 // the results are returned via SRet in memory.
16625 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16626 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16627 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16629 Type *RetTy = isF64
16630 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16631 : (Type*)VectorType::get(ArgTy, 4);
16633 TargetLowering::CallLoweringInfo CLI(DAG);
16634 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16635 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16637 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16640 // Returned in xmm0 and xmm1.
16641 return CallResult.first;
16643 // Returned in bits 0:31 and 32:64 xmm0.
16644 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16645 CallResult.first, DAG.getIntPtrConstant(0));
16646 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16647 CallResult.first, DAG.getIntPtrConstant(1));
16648 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16649 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16652 /// LowerOperation - Provide custom lowering hooks for some operations.
16654 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16655 switch (Op.getOpcode()) {
16656 default: llvm_unreachable("Should not custom lower this!");
16657 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16658 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16659 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16660 return LowerCMP_SWAP(Op, Subtarget, DAG);
16661 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16662 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16663 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16664 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16665 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16666 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16667 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16668 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16669 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16670 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16671 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16672 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16673 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16674 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16675 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16676 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16677 case ISD::SHL_PARTS:
16678 case ISD::SRA_PARTS:
16679 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16680 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16681 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16682 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16683 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16684 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16685 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16686 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16687 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16688 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16689 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16690 case ISD::FABS: return LowerFABS(Op, DAG);
16691 case ISD::FNEG: return LowerFNEG(Op, DAG);
16692 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16693 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16694 case ISD::SETCC: return LowerSETCC(Op, DAG);
16695 case ISD::SELECT: return LowerSELECT(Op, DAG);
16696 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16697 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16698 case ISD::VASTART: return LowerVASTART(Op, DAG);
16699 case ISD::VAARG: return LowerVAARG(Op, DAG);
16700 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16701 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16702 case ISD::INTRINSIC_VOID:
16703 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16704 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16705 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16706 case ISD::FRAME_TO_ARGS_OFFSET:
16707 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16708 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16709 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16710 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16711 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16712 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16713 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16714 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16715 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16716 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16717 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16718 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16719 case ISD::UMUL_LOHI:
16720 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16723 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16729 case ISD::UMULO: return LowerXALUO(Op, DAG);
16730 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16731 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16735 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16736 case ISD::ADD: return LowerADD(Op, DAG);
16737 case ISD::SUB: return LowerSUB(Op, DAG);
16738 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16742 static void ReplaceATOMIC_LOAD(SDNode *Node,
16743 SmallVectorImpl<SDValue> &Results,
16744 SelectionDAG &DAG) {
16746 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16748 // Convert wide load -> cmpxchg8b/cmpxchg16b
16749 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16750 // (The only way to get a 16-byte load is cmpxchg16b)
16751 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16752 SDValue Zero = DAG.getConstant(0, VT);
16753 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16755 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16756 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16757 cast<AtomicSDNode>(Node)->getMemOperand(),
16758 cast<AtomicSDNode>(Node)->getOrdering(),
16759 cast<AtomicSDNode>(Node)->getOrdering(),
16760 cast<AtomicSDNode>(Node)->getSynchScope());
16761 Results.push_back(Swap.getValue(0));
16762 Results.push_back(Swap.getValue(2));
16765 /// ReplaceNodeResults - Replace a node with an illegal result type
16766 /// with a new node built out of custom code.
16767 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16768 SmallVectorImpl<SDValue>&Results,
16769 SelectionDAG &DAG) const {
16771 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16772 switch (N->getOpcode()) {
16774 llvm_unreachable("Do not know how to custom type legalize this operation!");
16775 case ISD::SIGN_EXTEND_INREG:
16780 // We don't want to expand or promote these.
16787 case ISD::UDIVREM: {
16788 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16789 Results.push_back(V);
16792 case ISD::FP_TO_SINT:
16793 case ISD::FP_TO_UINT: {
16794 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16796 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16799 std::pair<SDValue,SDValue> Vals =
16800 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16801 SDValue FIST = Vals.first, StackSlot = Vals.second;
16802 if (FIST.getNode()) {
16803 EVT VT = N->getValueType(0);
16804 // Return a load from the stack slot.
16805 if (StackSlot.getNode())
16806 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16807 MachinePointerInfo(),
16808 false, false, false, 0));
16810 Results.push_back(FIST);
16814 case ISD::UINT_TO_FP: {
16815 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16816 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16817 N->getValueType(0) != MVT::v2f32)
16819 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16821 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16823 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16824 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16825 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16826 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16827 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16828 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16831 case ISD::FP_ROUND: {
16832 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16834 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16835 Results.push_back(V);
16838 case ISD::INTRINSIC_W_CHAIN: {
16839 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16841 default : llvm_unreachable("Do not know how to custom type "
16842 "legalize this intrinsic operation!");
16843 case Intrinsic::x86_rdtsc:
16844 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16846 case Intrinsic::x86_rdtscp:
16847 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16849 case Intrinsic::x86_rdpmc:
16850 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16853 case ISD::READCYCLECOUNTER: {
16854 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16857 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16858 EVT T = N->getValueType(0);
16859 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16860 bool Regs64bit = T == MVT::i128;
16861 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16862 SDValue cpInL, cpInH;
16863 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16864 DAG.getConstant(0, HalfT));
16865 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16866 DAG.getConstant(1, HalfT));
16867 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16868 Regs64bit ? X86::RAX : X86::EAX,
16870 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16871 Regs64bit ? X86::RDX : X86::EDX,
16872 cpInH, cpInL.getValue(1));
16873 SDValue swapInL, swapInH;
16874 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16875 DAG.getConstant(0, HalfT));
16876 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16877 DAG.getConstant(1, HalfT));
16878 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16879 Regs64bit ? X86::RBX : X86::EBX,
16880 swapInL, cpInH.getValue(1));
16881 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16882 Regs64bit ? X86::RCX : X86::ECX,
16883 swapInH, swapInL.getValue(1));
16884 SDValue Ops[] = { swapInH.getValue(0),
16886 swapInH.getValue(1) };
16887 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16888 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16889 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16890 X86ISD::LCMPXCHG8_DAG;
16891 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16892 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16893 Regs64bit ? X86::RAX : X86::EAX,
16894 HalfT, Result.getValue(1));
16895 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16896 Regs64bit ? X86::RDX : X86::EDX,
16897 HalfT, cpOutL.getValue(2));
16898 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16900 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16901 MVT::i32, cpOutH.getValue(2));
16903 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16904 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16905 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16907 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16908 Results.push_back(Success);
16909 Results.push_back(EFLAGS.getValue(1));
16912 case ISD::ATOMIC_SWAP:
16913 case ISD::ATOMIC_LOAD_ADD:
16914 case ISD::ATOMIC_LOAD_SUB:
16915 case ISD::ATOMIC_LOAD_AND:
16916 case ISD::ATOMIC_LOAD_OR:
16917 case ISD::ATOMIC_LOAD_XOR:
16918 case ISD::ATOMIC_LOAD_NAND:
16919 case ISD::ATOMIC_LOAD_MIN:
16920 case ISD::ATOMIC_LOAD_MAX:
16921 case ISD::ATOMIC_LOAD_UMIN:
16922 case ISD::ATOMIC_LOAD_UMAX:
16923 // Delegate to generic TypeLegalization. Situations we can really handle
16924 // should have already been dealt with by X86AtomicExpand.cpp.
16926 case ISD::ATOMIC_LOAD: {
16927 ReplaceATOMIC_LOAD(N, Results, DAG);
16930 case ISD::BITCAST: {
16931 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16932 EVT DstVT = N->getValueType(0);
16933 EVT SrcVT = N->getOperand(0)->getValueType(0);
16935 if (SrcVT != MVT::f64 ||
16936 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16939 unsigned NumElts = DstVT.getVectorNumElements();
16940 EVT SVT = DstVT.getVectorElementType();
16941 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16942 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16943 MVT::v2f64, N->getOperand(0));
16944 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16946 if (ExperimentalVectorWideningLegalization) {
16947 // If we are legalizing vectors by widening, we already have the desired
16948 // legal vector type, just return it.
16949 Results.push_back(ToVecInt);
16953 SmallVector<SDValue, 8> Elts;
16954 for (unsigned i = 0, e = NumElts; i != e; ++i)
16955 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16956 ToVecInt, DAG.getIntPtrConstant(i)));
16958 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16963 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16965 default: return nullptr;
16966 case X86ISD::BSF: return "X86ISD::BSF";
16967 case X86ISD::BSR: return "X86ISD::BSR";
16968 case X86ISD::SHLD: return "X86ISD::SHLD";
16969 case X86ISD::SHRD: return "X86ISD::SHRD";
16970 case X86ISD::FAND: return "X86ISD::FAND";
16971 case X86ISD::FANDN: return "X86ISD::FANDN";
16972 case X86ISD::FOR: return "X86ISD::FOR";
16973 case X86ISD::FXOR: return "X86ISD::FXOR";
16974 case X86ISD::FSRL: return "X86ISD::FSRL";
16975 case X86ISD::FILD: return "X86ISD::FILD";
16976 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16977 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16978 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16979 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16980 case X86ISD::FLD: return "X86ISD::FLD";
16981 case X86ISD::FST: return "X86ISD::FST";
16982 case X86ISD::CALL: return "X86ISD::CALL";
16983 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16984 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16985 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16986 case X86ISD::BT: return "X86ISD::BT";
16987 case X86ISD::CMP: return "X86ISD::CMP";
16988 case X86ISD::COMI: return "X86ISD::COMI";
16989 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16990 case X86ISD::CMPM: return "X86ISD::CMPM";
16991 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16992 case X86ISD::SETCC: return "X86ISD::SETCC";
16993 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16994 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16995 case X86ISD::CMOV: return "X86ISD::CMOV";
16996 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16997 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16998 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16999 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17000 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17001 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17002 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17003 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17004 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17005 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17006 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17007 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17008 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17009 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17010 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17011 case X86ISD::BLENDV: return "X86ISD::BLENDV";
17012 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17013 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17014 case X86ISD::HADD: return "X86ISD::HADD";
17015 case X86ISD::HSUB: return "X86ISD::HSUB";
17016 case X86ISD::FHADD: return "X86ISD::FHADD";
17017 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17018 case X86ISD::UMAX: return "X86ISD::UMAX";
17019 case X86ISD::UMIN: return "X86ISD::UMIN";
17020 case X86ISD::SMAX: return "X86ISD::SMAX";
17021 case X86ISD::SMIN: return "X86ISD::SMIN";
17022 case X86ISD::FMAX: return "X86ISD::FMAX";
17023 case X86ISD::FMIN: return "X86ISD::FMIN";
17024 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17025 case X86ISD::FMINC: return "X86ISD::FMINC";
17026 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17027 case X86ISD::FRCP: return "X86ISD::FRCP";
17028 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17029 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17030 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17031 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17032 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17033 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17034 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17035 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17036 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17037 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17038 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17039 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17040 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17041 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17042 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17043 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17044 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17045 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17046 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17047 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17048 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17049 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17050 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17051 case X86ISD::VSHL: return "X86ISD::VSHL";
17052 case X86ISD::VSRL: return "X86ISD::VSRL";
17053 case X86ISD::VSRA: return "X86ISD::VSRA";
17054 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17055 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17056 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17057 case X86ISD::CMPP: return "X86ISD::CMPP";
17058 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17059 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17060 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17061 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17062 case X86ISD::ADD: return "X86ISD::ADD";
17063 case X86ISD::SUB: return "X86ISD::SUB";
17064 case X86ISD::ADC: return "X86ISD::ADC";
17065 case X86ISD::SBB: return "X86ISD::SBB";
17066 case X86ISD::SMUL: return "X86ISD::SMUL";
17067 case X86ISD::UMUL: return "X86ISD::UMUL";
17068 case X86ISD::INC: return "X86ISD::INC";
17069 case X86ISD::DEC: return "X86ISD::DEC";
17070 case X86ISD::OR: return "X86ISD::OR";
17071 case X86ISD::XOR: return "X86ISD::XOR";
17072 case X86ISD::AND: return "X86ISD::AND";
17073 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17074 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17075 case X86ISD::PTEST: return "X86ISD::PTEST";
17076 case X86ISD::TESTP: return "X86ISD::TESTP";
17077 case X86ISD::TESTM: return "X86ISD::TESTM";
17078 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17079 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17080 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17081 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17082 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17083 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17084 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17085 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17086 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17087 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17088 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17089 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17090 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17091 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17092 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17093 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17094 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17095 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17096 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17097 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17098 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17099 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17100 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17101 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17102 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
17103 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17104 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17105 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17106 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17107 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17108 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17109 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17110 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17111 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17112 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17113 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17114 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17115 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17116 case X86ISD::SAHF: return "X86ISD::SAHF";
17117 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17118 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17119 case X86ISD::FMADD: return "X86ISD::FMADD";
17120 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17121 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17122 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17123 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17124 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17125 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17126 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17127 case X86ISD::XTEST: return "X86ISD::XTEST";
17131 // isLegalAddressingMode - Return true if the addressing mode represented
17132 // by AM is legal for this target, for a load/store of the specified type.
17133 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17135 // X86 supports extremely general addressing modes.
17136 CodeModel::Model M = getTargetMachine().getCodeModel();
17137 Reloc::Model R = getTargetMachine().getRelocationModel();
17139 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17140 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17145 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17147 // If a reference to this global requires an extra load, we can't fold it.
17148 if (isGlobalStubReference(GVFlags))
17151 // If BaseGV requires a register for the PIC base, we cannot also have a
17152 // BaseReg specified.
17153 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17156 // If lower 4G is not available, then we must use rip-relative addressing.
17157 if ((M != CodeModel::Small || R != Reloc::Static) &&
17158 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17162 switch (AM.Scale) {
17168 // These scales always work.
17173 // These scales are formed with basereg+scalereg. Only accept if there is
17178 default: // Other stuff never works.
17185 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17186 unsigned Bits = Ty->getScalarSizeInBits();
17188 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17189 // particularly cheaper than those without.
17193 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17194 // variable shifts just as cheap as scalar ones.
17195 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17198 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17199 // fully general vector.
17203 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17204 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17206 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17207 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17208 return NumBits1 > NumBits2;
17211 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17212 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17215 if (!isTypeLegal(EVT::getEVT(Ty1)))
17218 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17220 // Assuming the caller doesn't have a zeroext or signext return parameter,
17221 // truncation all the way down to i1 is valid.
17225 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17226 return isInt<32>(Imm);
17229 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17230 // Can also use sub to handle negated immediates.
17231 return isInt<32>(Imm);
17234 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17235 if (!VT1.isInteger() || !VT2.isInteger())
17237 unsigned NumBits1 = VT1.getSizeInBits();
17238 unsigned NumBits2 = VT2.getSizeInBits();
17239 return NumBits1 > NumBits2;
17242 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17243 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17244 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17247 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17248 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17249 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17252 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17253 EVT VT1 = Val.getValueType();
17254 if (isZExtFree(VT1, VT2))
17257 if (Val.getOpcode() != ISD::LOAD)
17260 if (!VT1.isSimple() || !VT1.isInteger() ||
17261 !VT2.isSimple() || !VT2.isInteger())
17264 switch (VT1.getSimpleVT().SimpleTy) {
17269 // X86 has 8, 16, and 32-bit zero-extending loads.
17277 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17278 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17281 VT = VT.getScalarType();
17283 if (!VT.isSimple())
17286 switch (VT.getSimpleVT().SimpleTy) {
17297 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17298 // i16 instructions are longer (0x66 prefix) and potentially slower.
17299 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17302 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17303 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17304 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17305 /// are assumed to be legal.
17307 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17309 if (!VT.isSimple())
17312 MVT SVT = VT.getSimpleVT();
17314 // Very little shuffling can be done for 64-bit vectors right now.
17315 if (VT.getSizeInBits() == 64)
17318 // If this is a single-input shuffle with no 128 bit lane crossings we can
17319 // lower it into pshufb.
17320 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17321 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17322 bool isLegal = true;
17323 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17324 if (M[I] >= (int)SVT.getVectorNumElements() ||
17325 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17334 // FIXME: blends, shifts.
17335 return (SVT.getVectorNumElements() == 2 ||
17336 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17337 isMOVLMask(M, SVT) ||
17338 isMOVHLPSMask(M, SVT) ||
17339 isSHUFPMask(M, SVT) ||
17340 isPSHUFDMask(M, SVT) ||
17341 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17342 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17343 isPALIGNRMask(M, SVT, Subtarget) ||
17344 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17345 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17346 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17347 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17348 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17352 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17354 if (!VT.isSimple())
17357 MVT SVT = VT.getSimpleVT();
17358 unsigned NumElts = SVT.getVectorNumElements();
17359 // FIXME: This collection of masks seems suspect.
17362 if (NumElts == 4 && SVT.is128BitVector()) {
17363 return (isMOVLMask(Mask, SVT) ||
17364 isCommutedMOVLMask(Mask, SVT, true) ||
17365 isSHUFPMask(Mask, SVT) ||
17366 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17371 //===----------------------------------------------------------------------===//
17372 // X86 Scheduler Hooks
17373 //===----------------------------------------------------------------------===//
17375 /// Utility function to emit xbegin specifying the start of an RTM region.
17376 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17377 const TargetInstrInfo *TII) {
17378 DebugLoc DL = MI->getDebugLoc();
17380 const BasicBlock *BB = MBB->getBasicBlock();
17381 MachineFunction::iterator I = MBB;
17384 // For the v = xbegin(), we generate
17395 MachineBasicBlock *thisMBB = MBB;
17396 MachineFunction *MF = MBB->getParent();
17397 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17398 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17399 MF->insert(I, mainMBB);
17400 MF->insert(I, sinkMBB);
17402 // Transfer the remainder of BB and its successor edges to sinkMBB.
17403 sinkMBB->splice(sinkMBB->begin(), MBB,
17404 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17405 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17409 // # fallthrough to mainMBB
17410 // # abortion to sinkMBB
17411 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17412 thisMBB->addSuccessor(mainMBB);
17413 thisMBB->addSuccessor(sinkMBB);
17417 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17418 mainMBB->addSuccessor(sinkMBB);
17421 // EAX is live into the sinkMBB
17422 sinkMBB->addLiveIn(X86::EAX);
17423 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17424 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17427 MI->eraseFromParent();
17431 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17432 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17433 // in the .td file.
17434 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17435 const TargetInstrInfo *TII) {
17437 switch (MI->getOpcode()) {
17438 default: llvm_unreachable("illegal opcode!");
17439 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17440 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17441 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17442 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17443 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17444 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17445 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17446 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17449 DebugLoc dl = MI->getDebugLoc();
17450 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17452 unsigned NumArgs = MI->getNumOperands();
17453 for (unsigned i = 1; i < NumArgs; ++i) {
17454 MachineOperand &Op = MI->getOperand(i);
17455 if (!(Op.isReg() && Op.isImplicit()))
17456 MIB.addOperand(Op);
17458 if (MI->hasOneMemOperand())
17459 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17461 BuildMI(*BB, MI, dl,
17462 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17463 .addReg(X86::XMM0);
17465 MI->eraseFromParent();
17469 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17470 // defs in an instruction pattern
17471 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17472 const TargetInstrInfo *TII) {
17474 switch (MI->getOpcode()) {
17475 default: llvm_unreachable("illegal opcode!");
17476 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17477 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17478 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17479 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17480 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17481 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17482 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17483 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17486 DebugLoc dl = MI->getDebugLoc();
17487 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17489 unsigned NumArgs = MI->getNumOperands(); // remove the results
17490 for (unsigned i = 1; i < NumArgs; ++i) {
17491 MachineOperand &Op = MI->getOperand(i);
17492 if (!(Op.isReg() && Op.isImplicit()))
17493 MIB.addOperand(Op);
17495 if (MI->hasOneMemOperand())
17496 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17498 BuildMI(*BB, MI, dl,
17499 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17502 MI->eraseFromParent();
17506 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17507 const TargetInstrInfo *TII,
17508 const X86Subtarget* Subtarget) {
17509 DebugLoc dl = MI->getDebugLoc();
17511 // Address into RAX/EAX, other two args into ECX, EDX.
17512 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17513 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17514 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17515 for (int i = 0; i < X86::AddrNumOperands; ++i)
17516 MIB.addOperand(MI->getOperand(i));
17518 unsigned ValOps = X86::AddrNumOperands;
17519 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17520 .addReg(MI->getOperand(ValOps).getReg());
17521 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17522 .addReg(MI->getOperand(ValOps+1).getReg());
17524 // The instruction doesn't actually take any operands though.
17525 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17527 MI->eraseFromParent(); // The pseudo is gone now.
17531 MachineBasicBlock *
17532 X86TargetLowering::EmitVAARG64WithCustomInserter(
17534 MachineBasicBlock *MBB) const {
17535 // Emit va_arg instruction on X86-64.
17537 // Operands to this pseudo-instruction:
17538 // 0 ) Output : destination address (reg)
17539 // 1-5) Input : va_list address (addr, i64mem)
17540 // 6 ) ArgSize : Size (in bytes) of vararg type
17541 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17542 // 8 ) Align : Alignment of type
17543 // 9 ) EFLAGS (implicit-def)
17545 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17546 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17548 unsigned DestReg = MI->getOperand(0).getReg();
17549 MachineOperand &Base = MI->getOperand(1);
17550 MachineOperand &Scale = MI->getOperand(2);
17551 MachineOperand &Index = MI->getOperand(3);
17552 MachineOperand &Disp = MI->getOperand(4);
17553 MachineOperand &Segment = MI->getOperand(5);
17554 unsigned ArgSize = MI->getOperand(6).getImm();
17555 unsigned ArgMode = MI->getOperand(7).getImm();
17556 unsigned Align = MI->getOperand(8).getImm();
17558 // Memory Reference
17559 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17560 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17561 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17563 // Machine Information
17564 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17565 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17566 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17567 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17568 DebugLoc DL = MI->getDebugLoc();
17570 // struct va_list {
17573 // i64 overflow_area (address)
17574 // i64 reg_save_area (address)
17576 // sizeof(va_list) = 24
17577 // alignment(va_list) = 8
17579 unsigned TotalNumIntRegs = 6;
17580 unsigned TotalNumXMMRegs = 8;
17581 bool UseGPOffset = (ArgMode == 1);
17582 bool UseFPOffset = (ArgMode == 2);
17583 unsigned MaxOffset = TotalNumIntRegs * 8 +
17584 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17586 /* Align ArgSize to a multiple of 8 */
17587 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17588 bool NeedsAlign = (Align > 8);
17590 MachineBasicBlock *thisMBB = MBB;
17591 MachineBasicBlock *overflowMBB;
17592 MachineBasicBlock *offsetMBB;
17593 MachineBasicBlock *endMBB;
17595 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17596 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17597 unsigned OffsetReg = 0;
17599 if (!UseGPOffset && !UseFPOffset) {
17600 // If we only pull from the overflow region, we don't create a branch.
17601 // We don't need to alter control flow.
17602 OffsetDestReg = 0; // unused
17603 OverflowDestReg = DestReg;
17605 offsetMBB = nullptr;
17606 overflowMBB = thisMBB;
17609 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17610 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17611 // If not, pull from overflow_area. (branch to overflowMBB)
17616 // offsetMBB overflowMBB
17621 // Registers for the PHI in endMBB
17622 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17623 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17625 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17626 MachineFunction *MF = MBB->getParent();
17627 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17628 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17629 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17631 MachineFunction::iterator MBBIter = MBB;
17634 // Insert the new basic blocks
17635 MF->insert(MBBIter, offsetMBB);
17636 MF->insert(MBBIter, overflowMBB);
17637 MF->insert(MBBIter, endMBB);
17639 // Transfer the remainder of MBB and its successor edges to endMBB.
17640 endMBB->splice(endMBB->begin(), thisMBB,
17641 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17642 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17644 // Make offsetMBB and overflowMBB successors of thisMBB
17645 thisMBB->addSuccessor(offsetMBB);
17646 thisMBB->addSuccessor(overflowMBB);
17648 // endMBB is a successor of both offsetMBB and overflowMBB
17649 offsetMBB->addSuccessor(endMBB);
17650 overflowMBB->addSuccessor(endMBB);
17652 // Load the offset value into a register
17653 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17654 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17658 .addDisp(Disp, UseFPOffset ? 4 : 0)
17659 .addOperand(Segment)
17660 .setMemRefs(MMOBegin, MMOEnd);
17662 // Check if there is enough room left to pull this argument.
17663 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17665 .addImm(MaxOffset + 8 - ArgSizeA8);
17667 // Branch to "overflowMBB" if offset >= max
17668 // Fall through to "offsetMBB" otherwise
17669 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17670 .addMBB(overflowMBB);
17673 // In offsetMBB, emit code to use the reg_save_area.
17675 assert(OffsetReg != 0);
17677 // Read the reg_save_area address.
17678 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17679 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17684 .addOperand(Segment)
17685 .setMemRefs(MMOBegin, MMOEnd);
17687 // Zero-extend the offset
17688 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17689 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17692 .addImm(X86::sub_32bit);
17694 // Add the offset to the reg_save_area to get the final address.
17695 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17696 .addReg(OffsetReg64)
17697 .addReg(RegSaveReg);
17699 // Compute the offset for the next argument
17700 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17701 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17703 .addImm(UseFPOffset ? 16 : 8);
17705 // Store it back into the va_list.
17706 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17710 .addDisp(Disp, UseFPOffset ? 4 : 0)
17711 .addOperand(Segment)
17712 .addReg(NextOffsetReg)
17713 .setMemRefs(MMOBegin, MMOEnd);
17716 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17721 // Emit code to use overflow area
17724 // Load the overflow_area address into a register.
17725 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17726 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17731 .addOperand(Segment)
17732 .setMemRefs(MMOBegin, MMOEnd);
17734 // If we need to align it, do so. Otherwise, just copy the address
17735 // to OverflowDestReg.
17737 // Align the overflow address
17738 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17739 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17741 // aligned_addr = (addr + (align-1)) & ~(align-1)
17742 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17743 .addReg(OverflowAddrReg)
17746 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17748 .addImm(~(uint64_t)(Align-1));
17750 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17751 .addReg(OverflowAddrReg);
17754 // Compute the next overflow address after this argument.
17755 // (the overflow address should be kept 8-byte aligned)
17756 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17757 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17758 .addReg(OverflowDestReg)
17759 .addImm(ArgSizeA8);
17761 // Store the new overflow address.
17762 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17767 .addOperand(Segment)
17768 .addReg(NextAddrReg)
17769 .setMemRefs(MMOBegin, MMOEnd);
17771 // If we branched, emit the PHI to the front of endMBB.
17773 BuildMI(*endMBB, endMBB->begin(), DL,
17774 TII->get(X86::PHI), DestReg)
17775 .addReg(OffsetDestReg).addMBB(offsetMBB)
17776 .addReg(OverflowDestReg).addMBB(overflowMBB);
17779 // Erase the pseudo instruction
17780 MI->eraseFromParent();
17785 MachineBasicBlock *
17786 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17788 MachineBasicBlock *MBB) const {
17789 // Emit code to save XMM registers to the stack. The ABI says that the
17790 // number of registers to save is given in %al, so it's theoretically
17791 // possible to do an indirect jump trick to avoid saving all of them,
17792 // however this code takes a simpler approach and just executes all
17793 // of the stores if %al is non-zero. It's less code, and it's probably
17794 // easier on the hardware branch predictor, and stores aren't all that
17795 // expensive anyway.
17797 // Create the new basic blocks. One block contains all the XMM stores,
17798 // and one block is the final destination regardless of whether any
17799 // stores were performed.
17800 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17801 MachineFunction *F = MBB->getParent();
17802 MachineFunction::iterator MBBIter = MBB;
17804 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17805 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17806 F->insert(MBBIter, XMMSaveMBB);
17807 F->insert(MBBIter, EndMBB);
17809 // Transfer the remainder of MBB and its successor edges to EndMBB.
17810 EndMBB->splice(EndMBB->begin(), MBB,
17811 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17812 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17814 // The original block will now fall through to the XMM save block.
17815 MBB->addSuccessor(XMMSaveMBB);
17816 // The XMMSaveMBB will fall through to the end block.
17817 XMMSaveMBB->addSuccessor(EndMBB);
17819 // Now add the instructions.
17820 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17821 DebugLoc DL = MI->getDebugLoc();
17823 unsigned CountReg = MI->getOperand(0).getReg();
17824 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17825 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17827 if (!Subtarget->isTargetWin64()) {
17828 // If %al is 0, branch around the XMM save block.
17829 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17830 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17831 MBB->addSuccessor(EndMBB);
17834 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17835 // that was just emitted, but clearly shouldn't be "saved".
17836 assert((MI->getNumOperands() <= 3 ||
17837 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17838 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17839 && "Expected last argument to be EFLAGS");
17840 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17841 // In the XMM save block, save all the XMM argument registers.
17842 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17843 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17844 MachineMemOperand *MMO =
17845 F->getMachineMemOperand(
17846 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17847 MachineMemOperand::MOStore,
17848 /*Size=*/16, /*Align=*/16);
17849 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17850 .addFrameIndex(RegSaveFrameIndex)
17851 .addImm(/*Scale=*/1)
17852 .addReg(/*IndexReg=*/0)
17853 .addImm(/*Disp=*/Offset)
17854 .addReg(/*Segment=*/0)
17855 .addReg(MI->getOperand(i).getReg())
17856 .addMemOperand(MMO);
17859 MI->eraseFromParent(); // The pseudo instruction is gone now.
17864 // The EFLAGS operand of SelectItr might be missing a kill marker
17865 // because there were multiple uses of EFLAGS, and ISel didn't know
17866 // which to mark. Figure out whether SelectItr should have had a
17867 // kill marker, and set it if it should. Returns the correct kill
17869 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17870 MachineBasicBlock* BB,
17871 const TargetRegisterInfo* TRI) {
17872 // Scan forward through BB for a use/def of EFLAGS.
17873 MachineBasicBlock::iterator miI(std::next(SelectItr));
17874 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17875 const MachineInstr& mi = *miI;
17876 if (mi.readsRegister(X86::EFLAGS))
17878 if (mi.definesRegister(X86::EFLAGS))
17879 break; // Should have kill-flag - update below.
17882 // If we hit the end of the block, check whether EFLAGS is live into a
17884 if (miI == BB->end()) {
17885 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17886 sEnd = BB->succ_end();
17887 sItr != sEnd; ++sItr) {
17888 MachineBasicBlock* succ = *sItr;
17889 if (succ->isLiveIn(X86::EFLAGS))
17894 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17895 // out. SelectMI should have a kill flag on EFLAGS.
17896 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17900 MachineBasicBlock *
17901 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17902 MachineBasicBlock *BB) const {
17903 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
17904 DebugLoc DL = MI->getDebugLoc();
17906 // To "insert" a SELECT_CC instruction, we actually have to insert the
17907 // diamond control-flow pattern. The incoming instruction knows the
17908 // destination vreg to set, the condition code register to branch on, the
17909 // true/false values to select between, and a branch opcode to use.
17910 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17911 MachineFunction::iterator It = BB;
17917 // cmpTY ccX, r1, r2
17919 // fallthrough --> copy0MBB
17920 MachineBasicBlock *thisMBB = BB;
17921 MachineFunction *F = BB->getParent();
17922 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17923 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17924 F->insert(It, copy0MBB);
17925 F->insert(It, sinkMBB);
17927 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17928 // live into the sink and copy blocks.
17929 const TargetRegisterInfo *TRI =
17930 BB->getParent()->getSubtarget().getRegisterInfo();
17931 if (!MI->killsRegister(X86::EFLAGS) &&
17932 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17933 copy0MBB->addLiveIn(X86::EFLAGS);
17934 sinkMBB->addLiveIn(X86::EFLAGS);
17937 // Transfer the remainder of BB and its successor edges to sinkMBB.
17938 sinkMBB->splice(sinkMBB->begin(), BB,
17939 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17940 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17942 // Add the true and fallthrough blocks as its successors.
17943 BB->addSuccessor(copy0MBB);
17944 BB->addSuccessor(sinkMBB);
17946 // Create the conditional branch instruction.
17948 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17949 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17952 // %FalseValue = ...
17953 // # fallthrough to sinkMBB
17954 copy0MBB->addSuccessor(sinkMBB);
17957 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17959 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17960 TII->get(X86::PHI), MI->getOperand(0).getReg())
17961 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17962 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17964 MI->eraseFromParent(); // The pseudo instruction is gone now.
17968 MachineBasicBlock *
17969 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17970 bool Is64Bit) const {
17971 MachineFunction *MF = BB->getParent();
17972 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
17973 DebugLoc DL = MI->getDebugLoc();
17974 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17976 assert(MF->shouldSplitStack());
17978 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17979 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17982 // ... [Till the alloca]
17983 // If stacklet is not large enough, jump to mallocMBB
17986 // Allocate by subtracting from RSP
17987 // Jump to continueMBB
17990 // Allocate by call to runtime
17994 // [rest of original BB]
17997 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17998 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17999 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18001 MachineRegisterInfo &MRI = MF->getRegInfo();
18002 const TargetRegisterClass *AddrRegClass =
18003 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18005 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18006 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18007 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18008 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18009 sizeVReg = MI->getOperand(1).getReg(),
18010 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18012 MachineFunction::iterator MBBIter = BB;
18015 MF->insert(MBBIter, bumpMBB);
18016 MF->insert(MBBIter, mallocMBB);
18017 MF->insert(MBBIter, continueMBB);
18019 continueMBB->splice(continueMBB->begin(), BB,
18020 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18021 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18023 // Add code to the main basic block to check if the stack limit has been hit,
18024 // and if so, jump to mallocMBB otherwise to bumpMBB.
18025 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18026 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18027 .addReg(tmpSPVReg).addReg(sizeVReg);
18028 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18029 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18030 .addReg(SPLimitVReg);
18031 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18033 // bumpMBB simply decreases the stack pointer, since we know the current
18034 // stacklet has enough space.
18035 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18036 .addReg(SPLimitVReg);
18037 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18038 .addReg(SPLimitVReg);
18039 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18041 // Calls into a routine in libgcc to allocate more space from the heap.
18042 const uint32_t *RegMask = MF->getTarget()
18043 .getSubtargetImpl()
18044 ->getRegisterInfo()
18045 ->getCallPreservedMask(CallingConv::C);
18047 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18049 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18050 .addExternalSymbol("__morestack_allocate_stack_space")
18051 .addRegMask(RegMask)
18052 .addReg(X86::RDI, RegState::Implicit)
18053 .addReg(X86::RAX, RegState::ImplicitDefine);
18055 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18057 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18058 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18059 .addExternalSymbol("__morestack_allocate_stack_space")
18060 .addRegMask(RegMask)
18061 .addReg(X86::EAX, RegState::ImplicitDefine);
18065 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18068 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18069 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18070 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18072 // Set up the CFG correctly.
18073 BB->addSuccessor(bumpMBB);
18074 BB->addSuccessor(mallocMBB);
18075 mallocMBB->addSuccessor(continueMBB);
18076 bumpMBB->addSuccessor(continueMBB);
18078 // Take care of the PHI nodes.
18079 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18080 MI->getOperand(0).getReg())
18081 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18082 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18084 // Delete the original pseudo instruction.
18085 MI->eraseFromParent();
18088 return continueMBB;
18091 MachineBasicBlock *
18092 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18093 MachineBasicBlock *BB) const {
18094 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18095 DebugLoc DL = MI->getDebugLoc();
18097 assert(!Subtarget->isTargetMacho());
18099 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18100 // non-trivial part is impdef of ESP.
18102 if (Subtarget->isTargetWin64()) {
18103 if (Subtarget->isTargetCygMing()) {
18104 // ___chkstk(Mingw64):
18105 // Clobbers R10, R11, RAX and EFLAGS.
18107 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18108 .addExternalSymbol("___chkstk")
18109 .addReg(X86::RAX, RegState::Implicit)
18110 .addReg(X86::RSP, RegState::Implicit)
18111 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18112 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18113 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18115 // __chkstk(MSVCRT): does not update stack pointer.
18116 // Clobbers R10, R11 and EFLAGS.
18117 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18118 .addExternalSymbol("__chkstk")
18119 .addReg(X86::RAX, RegState::Implicit)
18120 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18121 // RAX has the offset to be subtracted from RSP.
18122 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18127 const char *StackProbeSymbol =
18128 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18130 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18131 .addExternalSymbol(StackProbeSymbol)
18132 .addReg(X86::EAX, RegState::Implicit)
18133 .addReg(X86::ESP, RegState::Implicit)
18134 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18135 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18136 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18139 MI->eraseFromParent(); // The pseudo instruction is gone now.
18143 MachineBasicBlock *
18144 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18145 MachineBasicBlock *BB) const {
18146 // This is pretty easy. We're taking the value that we received from
18147 // our load from the relocation, sticking it in either RDI (x86-64)
18148 // or EAX and doing an indirect call. The return value will then
18149 // be in the normal return register.
18150 MachineFunction *F = BB->getParent();
18151 const X86InstrInfo *TII =
18152 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18153 DebugLoc DL = MI->getDebugLoc();
18155 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18156 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18158 // Get a register mask for the lowered call.
18159 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18160 // proper register mask.
18161 const uint32_t *RegMask = F->getTarget()
18162 .getSubtargetImpl()
18163 ->getRegisterInfo()
18164 ->getCallPreservedMask(CallingConv::C);
18165 if (Subtarget->is64Bit()) {
18166 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18167 TII->get(X86::MOV64rm), X86::RDI)
18169 .addImm(0).addReg(0)
18170 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18171 MI->getOperand(3).getTargetFlags())
18173 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18174 addDirectMem(MIB, X86::RDI);
18175 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18176 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18177 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18178 TII->get(X86::MOV32rm), X86::EAX)
18180 .addImm(0).addReg(0)
18181 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18182 MI->getOperand(3).getTargetFlags())
18184 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18185 addDirectMem(MIB, X86::EAX);
18186 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18188 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18189 TII->get(X86::MOV32rm), X86::EAX)
18190 .addReg(TII->getGlobalBaseReg(F))
18191 .addImm(0).addReg(0)
18192 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18193 MI->getOperand(3).getTargetFlags())
18195 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18196 addDirectMem(MIB, X86::EAX);
18197 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18200 MI->eraseFromParent(); // The pseudo instruction is gone now.
18204 MachineBasicBlock *
18205 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18206 MachineBasicBlock *MBB) const {
18207 DebugLoc DL = MI->getDebugLoc();
18208 MachineFunction *MF = MBB->getParent();
18209 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18210 MachineRegisterInfo &MRI = MF->getRegInfo();
18212 const BasicBlock *BB = MBB->getBasicBlock();
18213 MachineFunction::iterator I = MBB;
18216 // Memory Reference
18217 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18218 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18221 unsigned MemOpndSlot = 0;
18223 unsigned CurOp = 0;
18225 DstReg = MI->getOperand(CurOp++).getReg();
18226 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18227 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18228 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18229 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18231 MemOpndSlot = CurOp;
18233 MVT PVT = getPointerTy();
18234 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18235 "Invalid Pointer Size!");
18237 // For v = setjmp(buf), we generate
18240 // buf[LabelOffset] = restoreMBB
18241 // SjLjSetup restoreMBB
18247 // v = phi(main, restore)
18252 MachineBasicBlock *thisMBB = MBB;
18253 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18254 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18255 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18256 MF->insert(I, mainMBB);
18257 MF->insert(I, sinkMBB);
18258 MF->push_back(restoreMBB);
18260 MachineInstrBuilder MIB;
18262 // Transfer the remainder of BB and its successor edges to sinkMBB.
18263 sinkMBB->splice(sinkMBB->begin(), MBB,
18264 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18265 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18268 unsigned PtrStoreOpc = 0;
18269 unsigned LabelReg = 0;
18270 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18271 Reloc::Model RM = MF->getTarget().getRelocationModel();
18272 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18273 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18275 // Prepare IP either in reg or imm.
18276 if (!UseImmLabel) {
18277 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18278 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18279 LabelReg = MRI.createVirtualRegister(PtrRC);
18280 if (Subtarget->is64Bit()) {
18281 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18285 .addMBB(restoreMBB)
18288 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18289 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18290 .addReg(XII->getGlobalBaseReg(MF))
18293 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18297 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18299 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18300 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18301 if (i == X86::AddrDisp)
18302 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18304 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18307 MIB.addReg(LabelReg);
18309 MIB.addMBB(restoreMBB);
18310 MIB.setMemRefs(MMOBegin, MMOEnd);
18312 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18313 .addMBB(restoreMBB);
18315 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18316 MF->getSubtarget().getRegisterInfo());
18317 MIB.addRegMask(RegInfo->getNoPreservedMask());
18318 thisMBB->addSuccessor(mainMBB);
18319 thisMBB->addSuccessor(restoreMBB);
18323 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18324 mainMBB->addSuccessor(sinkMBB);
18327 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18328 TII->get(X86::PHI), DstReg)
18329 .addReg(mainDstReg).addMBB(mainMBB)
18330 .addReg(restoreDstReg).addMBB(restoreMBB);
18333 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18334 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18335 restoreMBB->addSuccessor(sinkMBB);
18337 MI->eraseFromParent();
18341 MachineBasicBlock *
18342 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18343 MachineBasicBlock *MBB) const {
18344 DebugLoc DL = MI->getDebugLoc();
18345 MachineFunction *MF = MBB->getParent();
18346 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18347 MachineRegisterInfo &MRI = MF->getRegInfo();
18349 // Memory Reference
18350 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18351 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18353 MVT PVT = getPointerTy();
18354 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18355 "Invalid Pointer Size!");
18357 const TargetRegisterClass *RC =
18358 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18359 unsigned Tmp = MRI.createVirtualRegister(RC);
18360 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18361 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18362 MF->getSubtarget().getRegisterInfo());
18363 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18364 unsigned SP = RegInfo->getStackRegister();
18366 MachineInstrBuilder MIB;
18368 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18369 const int64_t SPOffset = 2 * PVT.getStoreSize();
18371 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18372 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18375 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18376 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18377 MIB.addOperand(MI->getOperand(i));
18378 MIB.setMemRefs(MMOBegin, MMOEnd);
18380 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18381 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18382 if (i == X86::AddrDisp)
18383 MIB.addDisp(MI->getOperand(i), LabelOffset);
18385 MIB.addOperand(MI->getOperand(i));
18387 MIB.setMemRefs(MMOBegin, MMOEnd);
18389 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18390 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18391 if (i == X86::AddrDisp)
18392 MIB.addDisp(MI->getOperand(i), SPOffset);
18394 MIB.addOperand(MI->getOperand(i));
18396 MIB.setMemRefs(MMOBegin, MMOEnd);
18398 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18400 MI->eraseFromParent();
18404 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18405 // accumulator loops. Writing back to the accumulator allows the coalescer
18406 // to remove extra copies in the loop.
18407 MachineBasicBlock *
18408 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18409 MachineBasicBlock *MBB) const {
18410 MachineOperand &AddendOp = MI->getOperand(3);
18412 // Bail out early if the addend isn't a register - we can't switch these.
18413 if (!AddendOp.isReg())
18416 MachineFunction &MF = *MBB->getParent();
18417 MachineRegisterInfo &MRI = MF.getRegInfo();
18419 // Check whether the addend is defined by a PHI:
18420 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18421 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18422 if (!AddendDef.isPHI())
18425 // Look for the following pattern:
18427 // %addend = phi [%entry, 0], [%loop, %result]
18429 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18433 // %addend = phi [%entry, 0], [%loop, %result]
18435 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18437 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18438 assert(AddendDef.getOperand(i).isReg());
18439 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18440 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18441 if (&PHISrcInst == MI) {
18442 // Found a matching instruction.
18443 unsigned NewFMAOpc = 0;
18444 switch (MI->getOpcode()) {
18445 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18446 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18447 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18448 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18449 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18450 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18451 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18452 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18453 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18454 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18455 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18456 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18457 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18458 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18459 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18460 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18461 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18462 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18463 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18464 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18465 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18466 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18467 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18468 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18469 default: llvm_unreachable("Unrecognized FMA variant.");
18472 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18473 MachineInstrBuilder MIB =
18474 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18475 .addOperand(MI->getOperand(0))
18476 .addOperand(MI->getOperand(3))
18477 .addOperand(MI->getOperand(2))
18478 .addOperand(MI->getOperand(1));
18479 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18480 MI->eraseFromParent();
18487 MachineBasicBlock *
18488 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18489 MachineBasicBlock *BB) const {
18490 switch (MI->getOpcode()) {
18491 default: llvm_unreachable("Unexpected instr type to insert");
18492 case X86::TAILJMPd64:
18493 case X86::TAILJMPr64:
18494 case X86::TAILJMPm64:
18495 llvm_unreachable("TAILJMP64 would not be touched here.");
18496 case X86::TCRETURNdi64:
18497 case X86::TCRETURNri64:
18498 case X86::TCRETURNmi64:
18500 case X86::WIN_ALLOCA:
18501 return EmitLoweredWinAlloca(MI, BB);
18502 case X86::SEG_ALLOCA_32:
18503 return EmitLoweredSegAlloca(MI, BB, false);
18504 case X86::SEG_ALLOCA_64:
18505 return EmitLoweredSegAlloca(MI, BB, true);
18506 case X86::TLSCall_32:
18507 case X86::TLSCall_64:
18508 return EmitLoweredTLSCall(MI, BB);
18509 case X86::CMOV_GR8:
18510 case X86::CMOV_FR32:
18511 case X86::CMOV_FR64:
18512 case X86::CMOV_V4F32:
18513 case X86::CMOV_V2F64:
18514 case X86::CMOV_V2I64:
18515 case X86::CMOV_V8F32:
18516 case X86::CMOV_V4F64:
18517 case X86::CMOV_V4I64:
18518 case X86::CMOV_V16F32:
18519 case X86::CMOV_V8F64:
18520 case X86::CMOV_V8I64:
18521 case X86::CMOV_GR16:
18522 case X86::CMOV_GR32:
18523 case X86::CMOV_RFP32:
18524 case X86::CMOV_RFP64:
18525 case X86::CMOV_RFP80:
18526 return EmitLoweredSelect(MI, BB);
18528 case X86::FP32_TO_INT16_IN_MEM:
18529 case X86::FP32_TO_INT32_IN_MEM:
18530 case X86::FP32_TO_INT64_IN_MEM:
18531 case X86::FP64_TO_INT16_IN_MEM:
18532 case X86::FP64_TO_INT32_IN_MEM:
18533 case X86::FP64_TO_INT64_IN_MEM:
18534 case X86::FP80_TO_INT16_IN_MEM:
18535 case X86::FP80_TO_INT32_IN_MEM:
18536 case X86::FP80_TO_INT64_IN_MEM: {
18537 MachineFunction *F = BB->getParent();
18538 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18539 DebugLoc DL = MI->getDebugLoc();
18541 // Change the floating point control register to use "round towards zero"
18542 // mode when truncating to an integer value.
18543 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18544 addFrameReference(BuildMI(*BB, MI, DL,
18545 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18547 // Load the old value of the high byte of the control word...
18549 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18550 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18553 // Set the high part to be round to zero...
18554 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18557 // Reload the modified control word now...
18558 addFrameReference(BuildMI(*BB, MI, DL,
18559 TII->get(X86::FLDCW16m)), CWFrameIdx);
18561 // Restore the memory image of control word to original value
18562 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18565 // Get the X86 opcode to use.
18567 switch (MI->getOpcode()) {
18568 default: llvm_unreachable("illegal opcode!");
18569 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18570 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18571 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18572 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18573 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18574 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18575 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18576 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18577 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18581 MachineOperand &Op = MI->getOperand(0);
18583 AM.BaseType = X86AddressMode::RegBase;
18584 AM.Base.Reg = Op.getReg();
18586 AM.BaseType = X86AddressMode::FrameIndexBase;
18587 AM.Base.FrameIndex = Op.getIndex();
18589 Op = MI->getOperand(1);
18591 AM.Scale = Op.getImm();
18592 Op = MI->getOperand(2);
18594 AM.IndexReg = Op.getImm();
18595 Op = MI->getOperand(3);
18596 if (Op.isGlobal()) {
18597 AM.GV = Op.getGlobal();
18599 AM.Disp = Op.getImm();
18601 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18602 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18604 // Reload the original control word now.
18605 addFrameReference(BuildMI(*BB, MI, DL,
18606 TII->get(X86::FLDCW16m)), CWFrameIdx);
18608 MI->eraseFromParent(); // The pseudo instruction is gone now.
18611 // String/text processing lowering.
18612 case X86::PCMPISTRM128REG:
18613 case X86::VPCMPISTRM128REG:
18614 case X86::PCMPISTRM128MEM:
18615 case X86::VPCMPISTRM128MEM:
18616 case X86::PCMPESTRM128REG:
18617 case X86::VPCMPESTRM128REG:
18618 case X86::PCMPESTRM128MEM:
18619 case X86::VPCMPESTRM128MEM:
18620 assert(Subtarget->hasSSE42() &&
18621 "Target must have SSE4.2 or AVX features enabled");
18622 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18624 // String/text processing lowering.
18625 case X86::PCMPISTRIREG:
18626 case X86::VPCMPISTRIREG:
18627 case X86::PCMPISTRIMEM:
18628 case X86::VPCMPISTRIMEM:
18629 case X86::PCMPESTRIREG:
18630 case X86::VPCMPESTRIREG:
18631 case X86::PCMPESTRIMEM:
18632 case X86::VPCMPESTRIMEM:
18633 assert(Subtarget->hasSSE42() &&
18634 "Target must have SSE4.2 or AVX features enabled");
18635 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18637 // Thread synchronization.
18639 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18644 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18646 case X86::VASTART_SAVE_XMM_REGS:
18647 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18649 case X86::VAARG_64:
18650 return EmitVAARG64WithCustomInserter(MI, BB);
18652 case X86::EH_SjLj_SetJmp32:
18653 case X86::EH_SjLj_SetJmp64:
18654 return emitEHSjLjSetJmp(MI, BB);
18656 case X86::EH_SjLj_LongJmp32:
18657 case X86::EH_SjLj_LongJmp64:
18658 return emitEHSjLjLongJmp(MI, BB);
18660 case TargetOpcode::STACKMAP:
18661 case TargetOpcode::PATCHPOINT:
18662 return emitPatchPoint(MI, BB);
18664 case X86::VFMADDPDr213r:
18665 case X86::VFMADDPSr213r:
18666 case X86::VFMADDSDr213r:
18667 case X86::VFMADDSSr213r:
18668 case X86::VFMSUBPDr213r:
18669 case X86::VFMSUBPSr213r:
18670 case X86::VFMSUBSDr213r:
18671 case X86::VFMSUBSSr213r:
18672 case X86::VFNMADDPDr213r:
18673 case X86::VFNMADDPSr213r:
18674 case X86::VFNMADDSDr213r:
18675 case X86::VFNMADDSSr213r:
18676 case X86::VFNMSUBPDr213r:
18677 case X86::VFNMSUBPSr213r:
18678 case X86::VFNMSUBSDr213r:
18679 case X86::VFNMSUBSSr213r:
18680 case X86::VFMADDPDr213rY:
18681 case X86::VFMADDPSr213rY:
18682 case X86::VFMSUBPDr213rY:
18683 case X86::VFMSUBPSr213rY:
18684 case X86::VFNMADDPDr213rY:
18685 case X86::VFNMADDPSr213rY:
18686 case X86::VFNMSUBPDr213rY:
18687 case X86::VFNMSUBPSr213rY:
18688 return emitFMA3Instr(MI, BB);
18692 //===----------------------------------------------------------------------===//
18693 // X86 Optimization Hooks
18694 //===----------------------------------------------------------------------===//
18696 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18699 const SelectionDAG &DAG,
18700 unsigned Depth) const {
18701 unsigned BitWidth = KnownZero.getBitWidth();
18702 unsigned Opc = Op.getOpcode();
18703 assert((Opc >= ISD::BUILTIN_OP_END ||
18704 Opc == ISD::INTRINSIC_WO_CHAIN ||
18705 Opc == ISD::INTRINSIC_W_CHAIN ||
18706 Opc == ISD::INTRINSIC_VOID) &&
18707 "Should use MaskedValueIsZero if you don't know whether Op"
18708 " is a target node!");
18710 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18724 // These nodes' second result is a boolean.
18725 if (Op.getResNo() == 0)
18728 case X86ISD::SETCC:
18729 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18731 case ISD::INTRINSIC_WO_CHAIN: {
18732 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18733 unsigned NumLoBits = 0;
18736 case Intrinsic::x86_sse_movmsk_ps:
18737 case Intrinsic::x86_avx_movmsk_ps_256:
18738 case Intrinsic::x86_sse2_movmsk_pd:
18739 case Intrinsic::x86_avx_movmsk_pd_256:
18740 case Intrinsic::x86_mmx_pmovmskb:
18741 case Intrinsic::x86_sse2_pmovmskb_128:
18742 case Intrinsic::x86_avx2_pmovmskb: {
18743 // High bits of movmskp{s|d}, pmovmskb are known zero.
18745 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18746 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18747 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18748 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18749 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18750 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18751 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18752 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18754 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18763 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18765 const SelectionDAG &,
18766 unsigned Depth) const {
18767 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18768 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18769 return Op.getValueType().getScalarType().getSizeInBits();
18775 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18776 /// node is a GlobalAddress + offset.
18777 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18778 const GlobalValue* &GA,
18779 int64_t &Offset) const {
18780 if (N->getOpcode() == X86ISD::Wrapper) {
18781 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18782 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18783 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18787 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18790 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18791 /// same as extracting the high 128-bit part of 256-bit vector and then
18792 /// inserting the result into the low part of a new 256-bit vector
18793 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18794 EVT VT = SVOp->getValueType(0);
18795 unsigned NumElems = VT.getVectorNumElements();
18797 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18798 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18799 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18800 SVOp->getMaskElt(j) >= 0)
18806 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18807 /// same as extracting the low 128-bit part of 256-bit vector and then
18808 /// inserting the result into the high part of a new 256-bit vector
18809 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18810 EVT VT = SVOp->getValueType(0);
18811 unsigned NumElems = VT.getVectorNumElements();
18813 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18814 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18815 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18816 SVOp->getMaskElt(j) >= 0)
18822 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18823 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18824 TargetLowering::DAGCombinerInfo &DCI,
18825 const X86Subtarget* Subtarget) {
18827 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18828 SDValue V1 = SVOp->getOperand(0);
18829 SDValue V2 = SVOp->getOperand(1);
18830 EVT VT = SVOp->getValueType(0);
18831 unsigned NumElems = VT.getVectorNumElements();
18833 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18834 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18838 // V UNDEF BUILD_VECTOR UNDEF
18840 // CONCAT_VECTOR CONCAT_VECTOR
18843 // RESULT: V + zero extended
18845 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18846 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18847 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18850 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18853 // To match the shuffle mask, the first half of the mask should
18854 // be exactly the first vector, and all the rest a splat with the
18855 // first element of the second one.
18856 for (unsigned i = 0; i != NumElems/2; ++i)
18857 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18858 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18861 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18862 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18863 if (Ld->hasNUsesOfValue(1, 0)) {
18864 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18865 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18867 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18869 Ld->getPointerInfo(),
18870 Ld->getAlignment(),
18871 false/*isVolatile*/, true/*ReadMem*/,
18872 false/*WriteMem*/);
18874 // Make sure the newly-created LOAD is in the same position as Ld in
18875 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18876 // and update uses of Ld's output chain to use the TokenFactor.
18877 if (Ld->hasAnyUseOfValue(1)) {
18878 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18879 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18880 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18881 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18882 SDValue(ResNode.getNode(), 1));
18885 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18889 // Emit a zeroed vector and insert the desired subvector on its
18891 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18892 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18893 return DCI.CombineTo(N, InsV);
18896 //===--------------------------------------------------------------------===//
18897 // Combine some shuffles into subvector extracts and inserts:
18900 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18901 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18902 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18903 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18904 return DCI.CombineTo(N, InsV);
18907 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18908 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18909 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18910 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18911 return DCI.CombineTo(N, InsV);
18917 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18920 /// This is the leaf of the recursive combinine below. When we have found some
18921 /// chain of single-use x86 shuffle instructions and accumulated the combined
18922 /// shuffle mask represented by them, this will try to pattern match that mask
18923 /// into either a single instruction if there is a special purpose instruction
18924 /// for this operation, or into a PSHUFB instruction which is a fully general
18925 /// instruction but should only be used to replace chains over a certain depth.
18926 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18927 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
18928 TargetLowering::DAGCombinerInfo &DCI,
18929 const X86Subtarget *Subtarget) {
18930 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18932 // Find the operand that enters the chain. Note that multiple uses are OK
18933 // here, we're not going to remove the operand we find.
18934 SDValue Input = Op.getOperand(0);
18935 while (Input.getOpcode() == ISD::BITCAST)
18936 Input = Input.getOperand(0);
18938 MVT VT = Input.getSimpleValueType();
18939 MVT RootVT = Root.getSimpleValueType();
18942 // Just remove no-op shuffle masks.
18943 if (Mask.size() == 1) {
18944 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18949 // Use the float domain if the operand type is a floating point type.
18950 bool FloatDomain = VT.isFloatingPoint();
18952 // If we don't have access to VEX encodings, the generic PSHUF instructions
18953 // are preferable to some of the specialized forms despite requiring one more
18954 // byte to encode because they can implicitly copy.
18956 // IF we *do* have VEX encodings, than we can use shorter, more specific
18957 // shuffle instructions freely as they can copy due to the extra register
18959 if (Subtarget->hasAVX()) {
18960 // We have both floating point and integer variants of shuffles that dup
18961 // either the low or high half of the vector.
18962 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
18963 bool Lo = Mask.equals(0, 0);
18964 unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
18965 : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
18966 if (Depth == 1 && Root->getOpcode() == Shuffle)
18967 return false; // Nothing to do!
18968 MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
18969 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18970 DCI.AddToWorklist(Op.getNode());
18971 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
18972 DCI.AddToWorklist(Op.getNode());
18973 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18978 // FIXME: We should match UNPCKLPS and UNPCKHPS here.
18980 // For the integer domain we have specialized instructions for duplicating
18981 // any element size from the low or high half.
18982 if (!FloatDomain &&
18983 (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
18984 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
18985 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
18986 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
18987 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
18989 bool Lo = Mask[0] == 0;
18990 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
18991 if (Depth == 1 && Root->getOpcode() == Shuffle)
18992 return false; // Nothing to do!
18994 switch (Mask.size()) {
18995 case 4: ShuffleVT = MVT::v4i32; break;
18996 case 8: ShuffleVT = MVT::v8i16; break;
18997 case 16: ShuffleVT = MVT::v16i8; break;
18999 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19000 DCI.AddToWorklist(Op.getNode());
19001 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19002 DCI.AddToWorklist(Op.getNode());
19003 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19009 // Don't try to re-form single instruction chains under any circumstances now
19010 // that we've done encoding canonicalization for them.
19014 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19015 // can replace them with a single PSHUFB instruction profitably. Intel's
19016 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19017 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19018 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19019 SmallVector<SDValue, 16> PSHUFBMask;
19020 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19021 int Ratio = 16 / Mask.size();
19022 for (unsigned i = 0; i < 16; ++i) {
19023 int M = Ratio * Mask[i / Ratio] + i % Ratio;
19024 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19026 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19027 DCI.AddToWorklist(Op.getNode());
19028 SDValue PSHUFBMaskOp =
19029 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19030 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19031 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19032 DCI.AddToWorklist(Op.getNode());
19033 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19038 // Failed to find any combines.
19042 /// \brief Fully generic combining of x86 shuffle instructions.
19044 /// This should be the last combine run over the x86 shuffle instructions. Once
19045 /// they have been fully optimized, this will recursively consdier all chains
19046 /// of single-use shuffle instructions, build a generic model of the cumulative
19047 /// shuffle operation, and check for simpler instructions which implement this
19048 /// operation. We use this primarily for two purposes:
19050 /// 1) Collapse generic shuffles to specialized single instructions when
19051 /// equivalent. In most cases, this is just an encoding size win, but
19052 /// sometimes we will collapse multiple generic shuffles into a single
19053 /// special-purpose shuffle.
19054 /// 2) Look for sequences of shuffle instructions with 3 or more total
19055 /// instructions, and replace them with the slightly more expensive SSSE3
19056 /// PSHUFB instruction if available. We do this as the last combining step
19057 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19058 /// a suitable short sequence of other instructions. The PHUFB will either
19059 /// use a register or have to read from memory and so is slightly (but only
19060 /// slightly) more expensive than the other shuffle instructions.
19062 /// Because this is inherently a quadratic operation (for each shuffle in
19063 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19064 /// This should never be an issue in practice as the shuffle lowering doesn't
19065 /// produce sequences of more than 8 instructions.
19067 /// FIXME: We will currently miss some cases where the redundant shuffling
19068 /// would simplify under the threshold for PSHUFB formation because of
19069 /// combine-ordering. To fix this, we should do the redundant instruction
19070 /// combining in this recursive walk.
19071 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19072 ArrayRef<int> IncomingMask, int Depth,
19073 bool HasPSHUFB, SelectionDAG &DAG,
19074 TargetLowering::DAGCombinerInfo &DCI,
19075 const X86Subtarget *Subtarget) {
19076 // Bound the depth of our recursive combine because this is ultimately
19077 // quadratic in nature.
19081 // Directly rip through bitcasts to find the underlying operand.
19082 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19083 Op = Op.getOperand(0);
19085 MVT VT = Op.getSimpleValueType();
19086 if (!VT.isVector())
19087 return false; // Bail if we hit a non-vector.
19088 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19089 // version should be added.
19090 if (VT.getSizeInBits() != 128)
19093 assert(Root.getSimpleValueType().isVector() &&
19094 "Shuffles operate on vector types!");
19095 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19096 "Can only combine shuffles of the same vector register size.");
19098 if (!isTargetShuffle(Op.getOpcode()))
19100 SmallVector<int, 16> OpMask;
19102 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19103 // We only can combine unary shuffles which we can decode the mask for.
19104 if (!HaveMask || !IsUnary)
19107 assert(VT.getVectorNumElements() == OpMask.size() &&
19108 "Different mask size from vector size!");
19110 SmallVector<int, 16> Mask;
19111 Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
19113 // Merge this shuffle operation's mask into our accumulated mask. This is
19114 // a bit tricky as the shuffle may have a different size from the root.
19115 if (OpMask.size() == IncomingMask.size()) {
19116 for (int M : IncomingMask)
19117 Mask.push_back(OpMask[M]);
19118 } else if (OpMask.size() < IncomingMask.size()) {
19119 assert(IncomingMask.size() % OpMask.size() == 0 &&
19120 "The smaller number of elements must divide the larger.");
19121 int Ratio = IncomingMask.size() / OpMask.size();
19122 for (int M : IncomingMask)
19123 Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19125 assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19126 assert(OpMask.size() % IncomingMask.size() == 0 &&
19127 "The smaller number of elements must divide the larger.");
19128 int Ratio = OpMask.size() / IncomingMask.size();
19129 for (int i = 0, e = OpMask.size(); i < e; ++i)
19130 Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19133 // See if we can recurse into the operand to combine more things.
19134 switch (Op.getOpcode()) {
19135 case X86ISD::PSHUFB:
19137 case X86ISD::PSHUFD:
19138 case X86ISD::PSHUFHW:
19139 case X86ISD::PSHUFLW:
19140 if (Op.getOperand(0).hasOneUse() &&
19141 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19142 HasPSHUFB, DAG, DCI, Subtarget))
19146 case X86ISD::UNPCKL:
19147 case X86ISD::UNPCKH:
19148 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19149 // We can't check for single use, we have to check that this shuffle is the only user.
19150 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19151 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19152 HasPSHUFB, DAG, DCI, Subtarget))
19157 // Minor canonicalization of the accumulated shuffle mask to make it easier
19158 // to match below. All this does is detect masks with squential pairs of
19159 // elements, and shrink them to the half-width mask. It does this in a loop
19160 // so it will reduce the size of the mask to the minimal width mask which
19161 // performs an equivalent shuffle.
19162 while (Mask.size() > 1) {
19163 SmallVector<int, 16> NewMask;
19164 for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19165 if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19169 NewMask.push_back(Mask[2*i] / 2);
19171 if (NewMask.empty())
19173 Mask.swap(NewMask);
19176 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19180 /// \brief Get the PSHUF-style mask from PSHUF node.
19182 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19183 /// PSHUF-style masks that can be reused with such instructions.
19184 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19185 SmallVector<int, 4> Mask;
19187 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19191 switch (N.getOpcode()) {
19192 case X86ISD::PSHUFD:
19194 case X86ISD::PSHUFLW:
19197 case X86ISD::PSHUFHW:
19198 Mask.erase(Mask.begin(), Mask.begin() + 4);
19199 for (int &M : Mask)
19203 llvm_unreachable("No valid shuffle instruction found!");
19207 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19209 /// We walk up the chain and look for a combinable shuffle, skipping over
19210 /// shuffles that we could hoist this shuffle's transformation past without
19211 /// altering anything.
19212 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19214 TargetLowering::DAGCombinerInfo &DCI) {
19215 assert(N.getOpcode() == X86ISD::PSHUFD &&
19216 "Called with something other than an x86 128-bit half shuffle!");
19219 // Walk up a single-use chain looking for a combinable shuffle.
19220 SDValue V = N.getOperand(0);
19221 for (; V.hasOneUse(); V = V.getOperand(0)) {
19222 switch (V.getOpcode()) {
19224 return false; // Nothing combined!
19227 // Skip bitcasts as we always know the type for the target specific
19231 case X86ISD::PSHUFD:
19232 // Found another dword shuffle.
19235 case X86ISD::PSHUFLW:
19236 // Check that the low words (being shuffled) are the identity in the
19237 // dword shuffle, and the high words are self-contained.
19238 if (Mask[0] != 0 || Mask[1] != 1 ||
19239 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19244 case X86ISD::PSHUFHW:
19245 // Check that the high words (being shuffled) are the identity in the
19246 // dword shuffle, and the low words are self-contained.
19247 if (Mask[2] != 2 || Mask[3] != 3 ||
19248 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19253 case X86ISD::UNPCKL:
19254 case X86ISD::UNPCKH:
19255 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19256 // shuffle into a preceding word shuffle.
19257 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19260 // Search for a half-shuffle which we can combine with.
19261 unsigned CombineOp =
19262 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19263 if (V.getOperand(0) != V.getOperand(1) ||
19264 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19266 V = V.getOperand(0);
19268 switch (V.getOpcode()) {
19270 return false; // Nothing to combine.
19272 case X86ISD::PSHUFLW:
19273 case X86ISD::PSHUFHW:
19274 if (V.getOpcode() == CombineOp)
19279 V = V.getOperand(0);
19283 } while (V.hasOneUse());
19286 // Break out of the loop if we break out of the switch.
19290 if (!V.hasOneUse())
19291 // We fell out of the loop without finding a viable combining instruction.
19294 // Record the old value to use in RAUW-ing.
19297 // Merge this node's mask and our incoming mask.
19298 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19299 for (int &M : Mask)
19301 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19302 getV4X86ShuffleImm8ForMask(Mask, DAG));
19304 // It is possible that one of the combinable shuffles was completely absorbed
19305 // by the other, just replace it and revisit all users in that case.
19306 if (Old.getNode() == V.getNode()) {
19307 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19311 // Replace N with its operand as we're going to combine that shuffle away.
19312 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19314 // Replace the combinable shuffle with the combined one, updating all users
19315 // so that we re-evaluate the chain here.
19316 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19320 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19322 /// We walk up the chain, skipping shuffles of the other half and looking
19323 /// through shuffles which switch halves trying to find a shuffle of the same
19324 /// pair of dwords.
19325 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19327 TargetLowering::DAGCombinerInfo &DCI) {
19329 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19330 "Called with something other than an x86 128-bit half shuffle!");
19332 unsigned CombineOpcode = N.getOpcode();
19334 // Walk up a single-use chain looking for a combinable shuffle.
19335 SDValue V = N.getOperand(0);
19336 for (; V.hasOneUse(); V = V.getOperand(0)) {
19337 switch (V.getOpcode()) {
19339 return false; // Nothing combined!
19342 // Skip bitcasts as we always know the type for the target specific
19346 case X86ISD::PSHUFLW:
19347 case X86ISD::PSHUFHW:
19348 if (V.getOpcode() == CombineOpcode)
19351 // Other-half shuffles are no-ops.
19354 case X86ISD::PSHUFD: {
19355 // We can only handle pshufd if the half we are combining either stays in
19356 // its half, or switches to the other half. Bail if one of these isn't
19358 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19359 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19360 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19361 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19364 // Map the mask through the pshufd and keep walking up the chain.
19365 for (int i = 0; i < 4; ++i)
19366 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19368 // Switch halves if the pshufd does.
19370 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19374 // Break out of the loop if we break out of the switch.
19378 if (!V.hasOneUse())
19379 // We fell out of the loop without finding a viable combining instruction.
19382 // Record the old value to use in RAUW-ing.
19385 // Merge this node's mask and our incoming mask (adjusted to account for all
19386 // the pshufd instructions encountered).
19387 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19388 for (int &M : Mask)
19390 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19391 getV4X86ShuffleImm8ForMask(Mask, DAG));
19393 // Replace N with its operand as we're going to combine that shuffle away.
19394 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19396 // Replace the combinable shuffle with the combined one, updating all users
19397 // so that we re-evaluate the chain here.
19398 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19402 /// \brief Try to combine x86 target specific shuffles.
19403 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19404 TargetLowering::DAGCombinerInfo &DCI,
19405 const X86Subtarget *Subtarget) {
19407 MVT VT = N.getSimpleValueType();
19408 SmallVector<int, 4> Mask;
19410 switch (N.getOpcode()) {
19411 case X86ISD::PSHUFD:
19412 case X86ISD::PSHUFLW:
19413 case X86ISD::PSHUFHW:
19414 Mask = getPSHUFShuffleMask(N);
19415 assert(Mask.size() == 4);
19421 // Nuke no-op shuffles that show up after combining.
19422 if (isNoopShuffleMask(Mask))
19423 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19425 // Look for simplifications involving one or two shuffle instructions.
19426 SDValue V = N.getOperand(0);
19427 switch (N.getOpcode()) {
19430 case X86ISD::PSHUFLW:
19431 case X86ISD::PSHUFHW:
19432 assert(VT == MVT::v8i16);
19435 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19436 return SDValue(); // We combined away this shuffle, so we're done.
19438 // See if this reduces to a PSHUFD which is no more expensive and can
19439 // combine with more operations.
19440 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19441 areAdjacentMasksSequential(Mask)) {
19442 int DMask[] = {-1, -1, -1, -1};
19443 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19444 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19445 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19446 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19447 DCI.AddToWorklist(V.getNode());
19448 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19449 getV4X86ShuffleImm8ForMask(DMask, DAG));
19450 DCI.AddToWorklist(V.getNode());
19451 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19454 // Look for shuffle patterns which can be implemented as a single unpack.
19455 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19456 // only works when we have a PSHUFD followed by two half-shuffles.
19457 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19458 (V.getOpcode() == X86ISD::PSHUFLW ||
19459 V.getOpcode() == X86ISD::PSHUFHW) &&
19460 V.getOpcode() != N.getOpcode() &&
19462 SDValue D = V.getOperand(0);
19463 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19464 D = D.getOperand(0);
19465 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19466 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19467 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19468 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19469 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19471 for (int i = 0; i < 4; ++i) {
19472 WordMask[i + NOffset] = Mask[i] + NOffset;
19473 WordMask[i + VOffset] = VMask[i] + VOffset;
19475 // Map the word mask through the DWord mask.
19477 for (int i = 0; i < 8; ++i)
19478 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19479 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19480 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19481 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19482 std::begin(UnpackLoMask)) ||
19483 std::equal(std::begin(MappedMask), std::end(MappedMask),
19484 std::begin(UnpackHiMask))) {
19485 // We can replace all three shuffles with an unpack.
19486 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19487 DCI.AddToWorklist(V.getNode());
19488 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19490 DL, MVT::v8i16, V, V);
19497 case X86ISD::PSHUFD:
19498 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19499 return SDValue(); // We combined away this shuffle.
19507 /// PerformShuffleCombine - Performs several different shuffle combines.
19508 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19509 TargetLowering::DAGCombinerInfo &DCI,
19510 const X86Subtarget *Subtarget) {
19512 SDValue N0 = N->getOperand(0);
19513 SDValue N1 = N->getOperand(1);
19514 EVT VT = N->getValueType(0);
19516 // Don't create instructions with illegal types after legalize types has run.
19517 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19518 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19521 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19522 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19523 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19524 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19526 // During Type Legalization, when promoting illegal vector types,
19527 // the backend might introduce new shuffle dag nodes and bitcasts.
19529 // This code performs the following transformation:
19530 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19531 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19533 // We do this only if both the bitcast and the BINOP dag nodes have
19534 // one use. Also, perform this transformation only if the new binary
19535 // operation is legal. This is to avoid introducing dag nodes that
19536 // potentially need to be further expanded (or custom lowered) into a
19537 // less optimal sequence of dag nodes.
19538 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19539 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19540 N0.getOpcode() == ISD::BITCAST) {
19541 SDValue BC0 = N0.getOperand(0);
19542 EVT SVT = BC0.getValueType();
19543 unsigned Opcode = BC0.getOpcode();
19544 unsigned NumElts = VT.getVectorNumElements();
19546 if (BC0.hasOneUse() && SVT.isVector() &&
19547 SVT.getVectorNumElements() * 2 == NumElts &&
19548 TLI.isOperationLegal(Opcode, VT)) {
19549 bool CanFold = false;
19561 unsigned SVTNumElts = SVT.getVectorNumElements();
19562 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19563 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19564 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19565 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19566 CanFold = SVOp->getMaskElt(i) < 0;
19569 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19570 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19571 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19572 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19577 // Only handle 128 wide vector from here on.
19578 if (!VT.is128BitVector())
19581 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19582 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19583 // consecutive, non-overlapping, and in the right order.
19584 SmallVector<SDValue, 16> Elts;
19585 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19586 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19588 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19592 if (isTargetShuffle(N->getOpcode())) {
19594 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19595 if (Shuffle.getNode())
19598 // Try recursively combining arbitrary sequences of x86 shuffle
19599 // instructions into higher-order shuffles. We do this after combining
19600 // specific PSHUF instruction sequences into their minimal form so that we
19601 // can evaluate how many specialized shuffle instructions are involved in
19602 // a particular chain.
19603 SmallVector<int, 1> NonceMask; // Just a placeholder.
19604 NonceMask.push_back(0);
19605 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19606 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19608 return SDValue(); // This routine will use CombineTo to replace N.
19614 /// PerformTruncateCombine - Converts truncate operation to
19615 /// a sequence of vector shuffle operations.
19616 /// It is possible when we truncate 256-bit vector to 128-bit vector
19617 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19618 TargetLowering::DAGCombinerInfo &DCI,
19619 const X86Subtarget *Subtarget) {
19623 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19624 /// specific shuffle of a load can be folded into a single element load.
19625 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19626 /// shuffles have been customed lowered so we need to handle those here.
19627 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19628 TargetLowering::DAGCombinerInfo &DCI) {
19629 if (DCI.isBeforeLegalizeOps())
19632 SDValue InVec = N->getOperand(0);
19633 SDValue EltNo = N->getOperand(1);
19635 if (!isa<ConstantSDNode>(EltNo))
19638 EVT VT = InVec.getValueType();
19640 bool HasShuffleIntoBitcast = false;
19641 if (InVec.getOpcode() == ISD::BITCAST) {
19642 // Don't duplicate a load with other uses.
19643 if (!InVec.hasOneUse())
19645 EVT BCVT = InVec.getOperand(0).getValueType();
19646 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19648 InVec = InVec.getOperand(0);
19649 HasShuffleIntoBitcast = true;
19652 if (!isTargetShuffle(InVec.getOpcode()))
19655 // Don't duplicate a load with other uses.
19656 if (!InVec.hasOneUse())
19659 SmallVector<int, 16> ShuffleMask;
19661 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19665 // Select the input vector, guarding against out of range extract vector.
19666 unsigned NumElems = VT.getVectorNumElements();
19667 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19668 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19669 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19670 : InVec.getOperand(1);
19672 // If inputs to shuffle are the same for both ops, then allow 2 uses
19673 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19675 if (LdNode.getOpcode() == ISD::BITCAST) {
19676 // Don't duplicate a load with other uses.
19677 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19680 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19681 LdNode = LdNode.getOperand(0);
19684 if (!ISD::isNormalLoad(LdNode.getNode()))
19687 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19689 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19692 if (HasShuffleIntoBitcast) {
19693 // If there's a bitcast before the shuffle, check if the load type and
19694 // alignment is valid.
19695 unsigned Align = LN0->getAlignment();
19696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19697 unsigned NewAlign = TLI.getDataLayout()->
19698 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19700 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19704 // All checks match so transform back to vector_shuffle so that DAG combiner
19705 // can finish the job
19708 // Create shuffle node taking into account the case that its a unary shuffle
19709 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19710 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19711 InVec.getOperand(0), Shuffle,
19713 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19714 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19718 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19719 /// generation and convert it from being a bunch of shuffles and extracts
19720 /// to a simple store and scalar loads to extract the elements.
19721 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19722 TargetLowering::DAGCombinerInfo &DCI) {
19723 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19724 if (NewOp.getNode())
19727 SDValue InputVector = N->getOperand(0);
19729 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19730 // from mmx to v2i32 has a single usage.
19731 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19732 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19733 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19734 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19735 N->getValueType(0),
19736 InputVector.getNode()->getOperand(0));
19738 // Only operate on vectors of 4 elements, where the alternative shuffling
19739 // gets to be more expensive.
19740 if (InputVector.getValueType() != MVT::v4i32)
19743 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19744 // single use which is a sign-extend or zero-extend, and all elements are
19746 SmallVector<SDNode *, 4> Uses;
19747 unsigned ExtractedElements = 0;
19748 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19749 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19750 if (UI.getUse().getResNo() != InputVector.getResNo())
19753 SDNode *Extract = *UI;
19754 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19757 if (Extract->getValueType(0) != MVT::i32)
19759 if (!Extract->hasOneUse())
19761 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19762 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19764 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19767 // Record which element was extracted.
19768 ExtractedElements |=
19769 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19771 Uses.push_back(Extract);
19774 // If not all the elements were used, this may not be worthwhile.
19775 if (ExtractedElements != 15)
19778 // Ok, we've now decided to do the transformation.
19779 SDLoc dl(InputVector);
19781 // Store the value to a temporary stack slot.
19782 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19783 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19784 MachinePointerInfo(), false, false, 0);
19786 // Replace each use (extract) with a load of the appropriate element.
19787 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19788 UE = Uses.end(); UI != UE; ++UI) {
19789 SDNode *Extract = *UI;
19791 // cOMpute the element's address.
19792 SDValue Idx = Extract->getOperand(1);
19794 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19795 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19796 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19797 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19799 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19800 StackPtr, OffsetVal);
19802 // Load the scalar.
19803 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19804 ScalarAddr, MachinePointerInfo(),
19805 false, false, false, 0);
19807 // Replace the exact with the load.
19808 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19811 // The replacement was made in place; don't return anything.
19815 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19816 static std::pair<unsigned, bool>
19817 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19818 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19819 if (!VT.isVector())
19820 return std::make_pair(0, false);
19822 bool NeedSplit = false;
19823 switch (VT.getSimpleVT().SimpleTy) {
19824 default: return std::make_pair(0, false);
19828 if (!Subtarget->hasAVX2())
19830 if (!Subtarget->hasAVX())
19831 return std::make_pair(0, false);
19836 if (!Subtarget->hasSSE2())
19837 return std::make_pair(0, false);
19840 // SSE2 has only a small subset of the operations.
19841 bool hasUnsigned = Subtarget->hasSSE41() ||
19842 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19843 bool hasSigned = Subtarget->hasSSE41() ||
19844 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19846 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19849 // Check for x CC y ? x : y.
19850 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19851 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19856 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19859 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19862 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19865 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19867 // Check for x CC y ? y : x -- a min/max with reversed arms.
19868 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19869 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19874 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19877 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19880 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19883 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19887 return std::make_pair(Opc, NeedSplit);
19891 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19892 const X86Subtarget *Subtarget) {
19894 SDValue Cond = N->getOperand(0);
19895 SDValue LHS = N->getOperand(1);
19896 SDValue RHS = N->getOperand(2);
19898 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19899 SDValue CondSrc = Cond->getOperand(0);
19900 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19901 Cond = CondSrc->getOperand(0);
19904 MVT VT = N->getSimpleValueType(0);
19905 MVT EltVT = VT.getVectorElementType();
19906 unsigned NumElems = VT.getVectorNumElements();
19907 // There is no blend with immediate in AVX-512.
19908 if (VT.is512BitVector())
19911 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19913 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19916 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19919 unsigned MaskValue = 0;
19920 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19923 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19924 for (unsigned i = 0; i < NumElems; ++i) {
19925 // Be sure we emit undef where we can.
19926 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19927 ShuffleMask[i] = -1;
19929 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19932 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19935 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19937 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19938 TargetLowering::DAGCombinerInfo &DCI,
19939 const X86Subtarget *Subtarget) {
19941 SDValue Cond = N->getOperand(0);
19942 // Get the LHS/RHS of the select.
19943 SDValue LHS = N->getOperand(1);
19944 SDValue RHS = N->getOperand(2);
19945 EVT VT = LHS.getValueType();
19946 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19948 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19949 // instructions match the semantics of the common C idiom x<y?x:y but not
19950 // x<=y?x:y, because of how they handle negative zero (which can be
19951 // ignored in unsafe-math mode).
19952 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19953 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19954 (Subtarget->hasSSE2() ||
19955 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19956 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19958 unsigned Opcode = 0;
19959 // Check for x CC y ? x : y.
19960 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19961 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19965 // Converting this to a min would handle NaNs incorrectly, and swapping
19966 // the operands would cause it to handle comparisons between positive
19967 // and negative zero incorrectly.
19968 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19969 if (!DAG.getTarget().Options.UnsafeFPMath &&
19970 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19972 std::swap(LHS, RHS);
19974 Opcode = X86ISD::FMIN;
19977 // Converting this to a min would handle comparisons between positive
19978 // and negative zero incorrectly.
19979 if (!DAG.getTarget().Options.UnsafeFPMath &&
19980 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19982 Opcode = X86ISD::FMIN;
19985 // Converting this to a min would handle both negative zeros and NaNs
19986 // incorrectly, but we can swap the operands to fix both.
19987 std::swap(LHS, RHS);
19991 Opcode = X86ISD::FMIN;
19995 // Converting this to a max would handle comparisons between positive
19996 // and negative zero incorrectly.
19997 if (!DAG.getTarget().Options.UnsafeFPMath &&
19998 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20000 Opcode = X86ISD::FMAX;
20003 // Converting this to a max would handle NaNs incorrectly, and swapping
20004 // the operands would cause it to handle comparisons between positive
20005 // and negative zero incorrectly.
20006 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20007 if (!DAG.getTarget().Options.UnsafeFPMath &&
20008 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20010 std::swap(LHS, RHS);
20012 Opcode = X86ISD::FMAX;
20015 // Converting this to a max would handle both negative zeros and NaNs
20016 // incorrectly, but we can swap the operands to fix both.
20017 std::swap(LHS, RHS);
20021 Opcode = X86ISD::FMAX;
20024 // Check for x CC y ? y : x -- a min/max with reversed arms.
20025 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20026 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20030 // Converting this to a min would handle comparisons between positive
20031 // and negative zero incorrectly, and swapping the operands would
20032 // cause it to handle NaNs incorrectly.
20033 if (!DAG.getTarget().Options.UnsafeFPMath &&
20034 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20035 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20037 std::swap(LHS, RHS);
20039 Opcode = X86ISD::FMIN;
20042 // Converting this to a min would handle NaNs incorrectly.
20043 if (!DAG.getTarget().Options.UnsafeFPMath &&
20044 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20046 Opcode = X86ISD::FMIN;
20049 // Converting this to a min would handle both negative zeros and NaNs
20050 // incorrectly, but we can swap the operands to fix both.
20051 std::swap(LHS, RHS);
20055 Opcode = X86ISD::FMIN;
20059 // Converting this to a max would handle NaNs incorrectly.
20060 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20062 Opcode = X86ISD::FMAX;
20065 // Converting this to a max would handle comparisons between positive
20066 // and negative zero incorrectly, and swapping the operands would
20067 // cause it to handle NaNs incorrectly.
20068 if (!DAG.getTarget().Options.UnsafeFPMath &&
20069 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20070 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20072 std::swap(LHS, RHS);
20074 Opcode = X86ISD::FMAX;
20077 // Converting this to a max would handle both negative zeros and NaNs
20078 // incorrectly, but we can swap the operands to fix both.
20079 std::swap(LHS, RHS);
20083 Opcode = X86ISD::FMAX;
20089 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20092 EVT CondVT = Cond.getValueType();
20093 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20094 CondVT.getVectorElementType() == MVT::i1) {
20095 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20096 // lowering on AVX-512. In this case we convert it to
20097 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20098 // The same situation for all 128 and 256-bit vectors of i8 and i16
20099 EVT OpVT = LHS.getValueType();
20100 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20101 (OpVT.getVectorElementType() == MVT::i8 ||
20102 OpVT.getVectorElementType() == MVT::i16)) {
20103 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20104 DCI.AddToWorklist(Cond.getNode());
20105 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20108 // If this is a select between two integer constants, try to do some
20110 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20111 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20112 // Don't do this for crazy integer types.
20113 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20114 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20115 // so that TrueC (the true value) is larger than FalseC.
20116 bool NeedsCondInvert = false;
20118 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20119 // Efficiently invertible.
20120 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20121 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20122 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20123 NeedsCondInvert = true;
20124 std::swap(TrueC, FalseC);
20127 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20128 if (FalseC->getAPIntValue() == 0 &&
20129 TrueC->getAPIntValue().isPowerOf2()) {
20130 if (NeedsCondInvert) // Invert the condition if needed.
20131 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20132 DAG.getConstant(1, Cond.getValueType()));
20134 // Zero extend the condition if needed.
20135 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20137 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20138 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20139 DAG.getConstant(ShAmt, MVT::i8));
20142 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20143 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20144 if (NeedsCondInvert) // Invert the condition if needed.
20145 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20146 DAG.getConstant(1, Cond.getValueType()));
20148 // Zero extend the condition if needed.
20149 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20150 FalseC->getValueType(0), Cond);
20151 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20152 SDValue(FalseC, 0));
20155 // Optimize cases that will turn into an LEA instruction. This requires
20156 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20157 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20158 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20159 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20161 bool isFastMultiplier = false;
20163 switch ((unsigned char)Diff) {
20165 case 1: // result = add base, cond
20166 case 2: // result = lea base( , cond*2)
20167 case 3: // result = lea base(cond, cond*2)
20168 case 4: // result = lea base( , cond*4)
20169 case 5: // result = lea base(cond, cond*4)
20170 case 8: // result = lea base( , cond*8)
20171 case 9: // result = lea base(cond, cond*8)
20172 isFastMultiplier = true;
20177 if (isFastMultiplier) {
20178 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20179 if (NeedsCondInvert) // Invert the condition if needed.
20180 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20181 DAG.getConstant(1, Cond.getValueType()));
20183 // Zero extend the condition if needed.
20184 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20186 // Scale the condition by the difference.
20188 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20189 DAG.getConstant(Diff, Cond.getValueType()));
20191 // Add the base if non-zero.
20192 if (FalseC->getAPIntValue() != 0)
20193 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20194 SDValue(FalseC, 0));
20201 // Canonicalize max and min:
20202 // (x > y) ? x : y -> (x >= y) ? x : y
20203 // (x < y) ? x : y -> (x <= y) ? x : y
20204 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20205 // the need for an extra compare
20206 // against zero. e.g.
20207 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20209 // testl %edi, %edi
20211 // cmovgl %edi, %eax
20215 // cmovsl %eax, %edi
20216 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20217 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20218 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20219 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20224 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20225 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20226 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20227 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20232 // Early exit check
20233 if (!TLI.isTypeLegal(VT))
20236 // Match VSELECTs into subs with unsigned saturation.
20237 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20238 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20239 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20240 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20241 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20243 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20244 // left side invert the predicate to simplify logic below.
20246 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20248 CC = ISD::getSetCCInverse(CC, true);
20249 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20253 if (Other.getNode() && Other->getNumOperands() == 2 &&
20254 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20255 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20256 SDValue CondRHS = Cond->getOperand(1);
20258 // Look for a general sub with unsigned saturation first.
20259 // x >= y ? x-y : 0 --> subus x, y
20260 // x > y ? x-y : 0 --> subus x, y
20261 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20262 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20263 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20265 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20266 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20267 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20268 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20269 // If the RHS is a constant we have to reverse the const
20270 // canonicalization.
20271 // x > C-1 ? x+-C : 0 --> subus x, C
20272 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20273 CondRHSConst->getAPIntValue() ==
20274 (-OpRHSConst->getAPIntValue() - 1))
20275 return DAG.getNode(
20276 X86ISD::SUBUS, DL, VT, OpLHS,
20277 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20279 // Another special case: If C was a sign bit, the sub has been
20280 // canonicalized into a xor.
20281 // FIXME: Would it be better to use computeKnownBits to determine
20282 // whether it's safe to decanonicalize the xor?
20283 // x s< 0 ? x^C : 0 --> subus x, C
20284 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20285 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20286 OpRHSConst->getAPIntValue().isSignBit())
20287 // Note that we have to rebuild the RHS constant here to ensure we
20288 // don't rely on particular values of undef lanes.
20289 return DAG.getNode(
20290 X86ISD::SUBUS, DL, VT, OpLHS,
20291 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20296 // Try to match a min/max vector operation.
20297 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20298 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20299 unsigned Opc = ret.first;
20300 bool NeedSplit = ret.second;
20302 if (Opc && NeedSplit) {
20303 unsigned NumElems = VT.getVectorNumElements();
20304 // Extract the LHS vectors
20305 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20306 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20308 // Extract the RHS vectors
20309 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20310 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20312 // Create min/max for each subvector
20313 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20314 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20316 // Merge the result
20317 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20319 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20322 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20323 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20324 // Check if SETCC has already been promoted
20325 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20326 // Check that condition value type matches vselect operand type
20329 assert(Cond.getValueType().isVector() &&
20330 "vector select expects a vector selector!");
20332 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20333 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20335 if (!TValIsAllOnes && !FValIsAllZeros) {
20336 // Try invert the condition if true value is not all 1s and false value
20338 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20339 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20341 if (TValIsAllZeros || FValIsAllOnes) {
20342 SDValue CC = Cond.getOperand(2);
20343 ISD::CondCode NewCC =
20344 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20345 Cond.getOperand(0).getValueType().isInteger());
20346 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20347 std::swap(LHS, RHS);
20348 TValIsAllOnes = FValIsAllOnes;
20349 FValIsAllZeros = TValIsAllZeros;
20353 if (TValIsAllOnes || FValIsAllZeros) {
20356 if (TValIsAllOnes && FValIsAllZeros)
20358 else if (TValIsAllOnes)
20359 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20360 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20361 else if (FValIsAllZeros)
20362 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20363 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20365 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20369 // Try to fold this VSELECT into a MOVSS/MOVSD
20370 if (N->getOpcode() == ISD::VSELECT &&
20371 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20372 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20373 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20374 bool CanFold = false;
20375 unsigned NumElems = Cond.getNumOperands();
20379 if (isZero(Cond.getOperand(0))) {
20382 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20383 // fold (vselect <0,-1> -> (movsd A, B)
20384 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20385 CanFold = isAllOnes(Cond.getOperand(i));
20386 } else if (isAllOnes(Cond.getOperand(0))) {
20390 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20391 // fold (vselect <-1,0> -> (movsd B, A)
20392 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20393 CanFold = isZero(Cond.getOperand(i));
20397 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20398 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20399 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20402 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20403 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20404 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20405 // (v2i64 (bitcast B)))))
20407 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20408 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20409 // (v2f64 (bitcast B)))))
20411 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20412 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20413 // (v2i64 (bitcast A)))))
20415 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20416 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20417 // (v2f64 (bitcast A)))))
20419 CanFold = (isZero(Cond.getOperand(0)) &&
20420 isZero(Cond.getOperand(1)) &&
20421 isAllOnes(Cond.getOperand(2)) &&
20422 isAllOnes(Cond.getOperand(3)));
20424 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20425 isAllOnes(Cond.getOperand(1)) &&
20426 isZero(Cond.getOperand(2)) &&
20427 isZero(Cond.getOperand(3))) {
20429 std::swap(LHS, RHS);
20433 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20434 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20435 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20436 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20438 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20444 // If we know that this node is legal then we know that it is going to be
20445 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20446 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20447 // to simplify previous instructions.
20448 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20449 !DCI.isBeforeLegalize() &&
20450 // We explicitly check against v8i16 and v16i16 because, although
20451 // they're marked as Custom, they might only be legal when Cond is a
20452 // build_vector of constants. This will be taken care in a later
20454 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20455 VT != MVT::v8i16)) {
20456 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20458 // Don't optimize vector selects that map to mask-registers.
20462 // Check all uses of that condition operand to check whether it will be
20463 // consumed by non-BLEND instructions, which may depend on all bits are set
20465 for (SDNode::use_iterator I = Cond->use_begin(),
20466 E = Cond->use_end(); I != E; ++I)
20467 if (I->getOpcode() != ISD::VSELECT)
20468 // TODO: Add other opcodes eventually lowered into BLEND.
20471 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20472 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20474 APInt KnownZero, KnownOne;
20475 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20476 DCI.isBeforeLegalizeOps());
20477 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20478 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20479 DCI.CommitTargetLoweringOpt(TLO);
20482 // We should generate an X86ISD::BLENDI from a vselect if its argument
20483 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20484 // constants. This specific pattern gets generated when we split a
20485 // selector for a 512 bit vector in a machine without AVX512 (but with
20486 // 256-bit vectors), during legalization:
20488 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20490 // Iff we find this pattern and the build_vectors are built from
20491 // constants, we translate the vselect into a shuffle_vector that we
20492 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20493 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20494 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20495 if (Shuffle.getNode())
20502 // Check whether a boolean test is testing a boolean value generated by
20503 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20506 // Simplify the following patterns:
20507 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20508 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20509 // to (Op EFLAGS Cond)
20511 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20512 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20513 // to (Op EFLAGS !Cond)
20515 // where Op could be BRCOND or CMOV.
20517 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20518 // Quit if not CMP and SUB with its value result used.
20519 if (Cmp.getOpcode() != X86ISD::CMP &&
20520 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20523 // Quit if not used as a boolean value.
20524 if (CC != X86::COND_E && CC != X86::COND_NE)
20527 // Check CMP operands. One of them should be 0 or 1 and the other should be
20528 // an SetCC or extended from it.
20529 SDValue Op1 = Cmp.getOperand(0);
20530 SDValue Op2 = Cmp.getOperand(1);
20533 const ConstantSDNode* C = nullptr;
20534 bool needOppositeCond = (CC == X86::COND_E);
20535 bool checkAgainstTrue = false; // Is it a comparison against 1?
20537 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20539 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20541 else // Quit if all operands are not constants.
20544 if (C->getZExtValue() == 1) {
20545 needOppositeCond = !needOppositeCond;
20546 checkAgainstTrue = true;
20547 } else if (C->getZExtValue() != 0)
20548 // Quit if the constant is neither 0 or 1.
20551 bool truncatedToBoolWithAnd = false;
20552 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20553 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20554 SetCC.getOpcode() == ISD::TRUNCATE ||
20555 SetCC.getOpcode() == ISD::AND) {
20556 if (SetCC.getOpcode() == ISD::AND) {
20558 ConstantSDNode *CS;
20559 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20560 CS->getZExtValue() == 1)
20562 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20563 CS->getZExtValue() == 1)
20567 SetCC = SetCC.getOperand(OpIdx);
20568 truncatedToBoolWithAnd = true;
20570 SetCC = SetCC.getOperand(0);
20573 switch (SetCC.getOpcode()) {
20574 case X86ISD::SETCC_CARRY:
20575 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20576 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20577 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20578 // truncated to i1 using 'and'.
20579 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20581 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20582 "Invalid use of SETCC_CARRY!");
20584 case X86ISD::SETCC:
20585 // Set the condition code or opposite one if necessary.
20586 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20587 if (needOppositeCond)
20588 CC = X86::GetOppositeBranchCondition(CC);
20589 return SetCC.getOperand(1);
20590 case X86ISD::CMOV: {
20591 // Check whether false/true value has canonical one, i.e. 0 or 1.
20592 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20593 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20594 // Quit if true value is not a constant.
20597 // Quit if false value is not a constant.
20599 SDValue Op = SetCC.getOperand(0);
20600 // Skip 'zext' or 'trunc' node.
20601 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20602 Op.getOpcode() == ISD::TRUNCATE)
20603 Op = Op.getOperand(0);
20604 // A special case for rdrand/rdseed, where 0 is set if false cond is
20606 if ((Op.getOpcode() != X86ISD::RDRAND &&
20607 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20610 // Quit if false value is not the constant 0 or 1.
20611 bool FValIsFalse = true;
20612 if (FVal && FVal->getZExtValue() != 0) {
20613 if (FVal->getZExtValue() != 1)
20615 // If FVal is 1, opposite cond is needed.
20616 needOppositeCond = !needOppositeCond;
20617 FValIsFalse = false;
20619 // Quit if TVal is not the constant opposite of FVal.
20620 if (FValIsFalse && TVal->getZExtValue() != 1)
20622 if (!FValIsFalse && TVal->getZExtValue() != 0)
20624 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20625 if (needOppositeCond)
20626 CC = X86::GetOppositeBranchCondition(CC);
20627 return SetCC.getOperand(3);
20634 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20635 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20636 TargetLowering::DAGCombinerInfo &DCI,
20637 const X86Subtarget *Subtarget) {
20640 // If the flag operand isn't dead, don't touch this CMOV.
20641 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20644 SDValue FalseOp = N->getOperand(0);
20645 SDValue TrueOp = N->getOperand(1);
20646 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20647 SDValue Cond = N->getOperand(3);
20649 if (CC == X86::COND_E || CC == X86::COND_NE) {
20650 switch (Cond.getOpcode()) {
20654 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20655 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20656 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20662 Flags = checkBoolTestSetCCCombine(Cond, CC);
20663 if (Flags.getNode() &&
20664 // Extra check as FCMOV only supports a subset of X86 cond.
20665 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20666 SDValue Ops[] = { FalseOp, TrueOp,
20667 DAG.getConstant(CC, MVT::i8), Flags };
20668 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20671 // If this is a select between two integer constants, try to do some
20672 // optimizations. Note that the operands are ordered the opposite of SELECT
20674 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20675 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20676 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20677 // larger than FalseC (the false value).
20678 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20679 CC = X86::GetOppositeBranchCondition(CC);
20680 std::swap(TrueC, FalseC);
20681 std::swap(TrueOp, FalseOp);
20684 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20685 // This is efficient for any integer data type (including i8/i16) and
20687 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20688 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20689 DAG.getConstant(CC, MVT::i8), Cond);
20691 // Zero extend the condition if needed.
20692 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20694 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20695 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20696 DAG.getConstant(ShAmt, MVT::i8));
20697 if (N->getNumValues() == 2) // Dead flag value?
20698 return DCI.CombineTo(N, Cond, SDValue());
20702 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20703 // for any integer data type, including i8/i16.
20704 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20705 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20706 DAG.getConstant(CC, MVT::i8), Cond);
20708 // Zero extend the condition if needed.
20709 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20710 FalseC->getValueType(0), Cond);
20711 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20712 SDValue(FalseC, 0));
20714 if (N->getNumValues() == 2) // Dead flag value?
20715 return DCI.CombineTo(N, Cond, SDValue());
20719 // Optimize cases that will turn into an LEA instruction. This requires
20720 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20721 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20722 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20723 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20725 bool isFastMultiplier = false;
20727 switch ((unsigned char)Diff) {
20729 case 1: // result = add base, cond
20730 case 2: // result = lea base( , cond*2)
20731 case 3: // result = lea base(cond, cond*2)
20732 case 4: // result = lea base( , cond*4)
20733 case 5: // result = lea base(cond, cond*4)
20734 case 8: // result = lea base( , cond*8)
20735 case 9: // result = lea base(cond, cond*8)
20736 isFastMultiplier = true;
20741 if (isFastMultiplier) {
20742 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20743 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20744 DAG.getConstant(CC, MVT::i8), Cond);
20745 // Zero extend the condition if needed.
20746 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20748 // Scale the condition by the difference.
20750 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20751 DAG.getConstant(Diff, Cond.getValueType()));
20753 // Add the base if non-zero.
20754 if (FalseC->getAPIntValue() != 0)
20755 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20756 SDValue(FalseC, 0));
20757 if (N->getNumValues() == 2) // Dead flag value?
20758 return DCI.CombineTo(N, Cond, SDValue());
20765 // Handle these cases:
20766 // (select (x != c), e, c) -> select (x != c), e, x),
20767 // (select (x == c), c, e) -> select (x == c), x, e)
20768 // where the c is an integer constant, and the "select" is the combination
20769 // of CMOV and CMP.
20771 // The rationale for this change is that the conditional-move from a constant
20772 // needs two instructions, however, conditional-move from a register needs
20773 // only one instruction.
20775 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20776 // some instruction-combining opportunities. This opt needs to be
20777 // postponed as late as possible.
20779 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20780 // the DCI.xxxx conditions are provided to postpone the optimization as
20781 // late as possible.
20783 ConstantSDNode *CmpAgainst = nullptr;
20784 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20785 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20786 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20788 if (CC == X86::COND_NE &&
20789 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20790 CC = X86::GetOppositeBranchCondition(CC);
20791 std::swap(TrueOp, FalseOp);
20794 if (CC == X86::COND_E &&
20795 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20796 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20797 DAG.getConstant(CC, MVT::i8), Cond };
20798 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20806 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20807 const X86Subtarget *Subtarget) {
20808 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20810 default: return SDValue();
20811 // SSE/AVX/AVX2 blend intrinsics.
20812 case Intrinsic::x86_avx2_pblendvb:
20813 case Intrinsic::x86_avx2_pblendw:
20814 case Intrinsic::x86_avx2_pblendd_128:
20815 case Intrinsic::x86_avx2_pblendd_256:
20816 // Don't try to simplify this intrinsic if we don't have AVX2.
20817 if (!Subtarget->hasAVX2())
20820 case Intrinsic::x86_avx_blend_pd_256:
20821 case Intrinsic::x86_avx_blend_ps_256:
20822 case Intrinsic::x86_avx_blendv_pd_256:
20823 case Intrinsic::x86_avx_blendv_ps_256:
20824 // Don't try to simplify this intrinsic if we don't have AVX.
20825 if (!Subtarget->hasAVX())
20828 case Intrinsic::x86_sse41_pblendw:
20829 case Intrinsic::x86_sse41_blendpd:
20830 case Intrinsic::x86_sse41_blendps:
20831 case Intrinsic::x86_sse41_blendvps:
20832 case Intrinsic::x86_sse41_blendvpd:
20833 case Intrinsic::x86_sse41_pblendvb: {
20834 SDValue Op0 = N->getOperand(1);
20835 SDValue Op1 = N->getOperand(2);
20836 SDValue Mask = N->getOperand(3);
20838 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20839 if (!Subtarget->hasSSE41())
20842 // fold (blend A, A, Mask) -> A
20845 // fold (blend A, B, allZeros) -> A
20846 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20848 // fold (blend A, B, allOnes) -> B
20849 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20852 // Simplify the case where the mask is a constant i32 value.
20853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20854 if (C->isNullValue())
20856 if (C->isAllOnesValue())
20863 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20864 case Intrinsic::x86_sse2_psrai_w:
20865 case Intrinsic::x86_sse2_psrai_d:
20866 case Intrinsic::x86_avx2_psrai_w:
20867 case Intrinsic::x86_avx2_psrai_d:
20868 case Intrinsic::x86_sse2_psra_w:
20869 case Intrinsic::x86_sse2_psra_d:
20870 case Intrinsic::x86_avx2_psra_w:
20871 case Intrinsic::x86_avx2_psra_d: {
20872 SDValue Op0 = N->getOperand(1);
20873 SDValue Op1 = N->getOperand(2);
20874 EVT VT = Op0.getValueType();
20875 assert(VT.isVector() && "Expected a vector type!");
20877 if (isa<BuildVectorSDNode>(Op1))
20878 Op1 = Op1.getOperand(0);
20880 if (!isa<ConstantSDNode>(Op1))
20883 EVT SVT = VT.getVectorElementType();
20884 unsigned SVTBits = SVT.getSizeInBits();
20886 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20887 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20888 uint64_t ShAmt = C.getZExtValue();
20890 // Don't try to convert this shift into a ISD::SRA if the shift
20891 // count is bigger than or equal to the element size.
20892 if (ShAmt >= SVTBits)
20895 // Trivial case: if the shift count is zero, then fold this
20896 // into the first operand.
20900 // Replace this packed shift intrinsic with a target independent
20902 SDValue Splat = DAG.getConstant(C, VT);
20903 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20908 /// PerformMulCombine - Optimize a single multiply with constant into two
20909 /// in order to implement it with two cheaper instructions, e.g.
20910 /// LEA + SHL, LEA + LEA.
20911 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20912 TargetLowering::DAGCombinerInfo &DCI) {
20913 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20916 EVT VT = N->getValueType(0);
20917 if (VT != MVT::i64)
20920 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20923 uint64_t MulAmt = C->getZExtValue();
20924 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20927 uint64_t MulAmt1 = 0;
20928 uint64_t MulAmt2 = 0;
20929 if ((MulAmt % 9) == 0) {
20931 MulAmt2 = MulAmt / 9;
20932 } else if ((MulAmt % 5) == 0) {
20934 MulAmt2 = MulAmt / 5;
20935 } else if ((MulAmt % 3) == 0) {
20937 MulAmt2 = MulAmt / 3;
20940 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20943 if (isPowerOf2_64(MulAmt2) &&
20944 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20945 // If second multiplifer is pow2, issue it first. We want the multiply by
20946 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20948 std::swap(MulAmt1, MulAmt2);
20951 if (isPowerOf2_64(MulAmt1))
20952 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20953 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20955 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20956 DAG.getConstant(MulAmt1, VT));
20958 if (isPowerOf2_64(MulAmt2))
20959 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20960 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20962 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20963 DAG.getConstant(MulAmt2, VT));
20965 // Do not add new nodes to DAG combiner worklist.
20966 DCI.CombineTo(N, NewMul, false);
20971 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20972 SDValue N0 = N->getOperand(0);
20973 SDValue N1 = N->getOperand(1);
20974 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20975 EVT VT = N0.getValueType();
20977 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20978 // since the result of setcc_c is all zero's or all ones.
20979 if (VT.isInteger() && !VT.isVector() &&
20980 N1C && N0.getOpcode() == ISD::AND &&
20981 N0.getOperand(1).getOpcode() == ISD::Constant) {
20982 SDValue N00 = N0.getOperand(0);
20983 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20984 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20985 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20986 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20987 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20988 APInt ShAmt = N1C->getAPIntValue();
20989 Mask = Mask.shl(ShAmt);
20991 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20992 N00, DAG.getConstant(Mask, VT));
20996 // Hardware support for vector shifts is sparse which makes us scalarize the
20997 // vector operations in many cases. Also, on sandybridge ADD is faster than
20999 // (shl V, 1) -> add V,V
21000 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21001 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21002 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21003 // We shift all of the values by one. In many cases we do not have
21004 // hardware support for this operation. This is better expressed as an ADD
21006 if (N1SplatC->getZExtValue() == 1)
21007 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21013 /// \brief Returns a vector of 0s if the node in input is a vector logical
21014 /// shift by a constant amount which is known to be bigger than or equal
21015 /// to the vector element size in bits.
21016 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21017 const X86Subtarget *Subtarget) {
21018 EVT VT = N->getValueType(0);
21020 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21021 (!Subtarget->hasInt256() ||
21022 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21025 SDValue Amt = N->getOperand(1);
21027 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21028 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21029 APInt ShiftAmt = AmtSplat->getAPIntValue();
21030 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21032 // SSE2/AVX2 logical shifts always return a vector of 0s
21033 // if the shift amount is bigger than or equal to
21034 // the element size. The constant shift amount will be
21035 // encoded as a 8-bit immediate.
21036 if (ShiftAmt.trunc(8).uge(MaxAmount))
21037 return getZeroVector(VT, Subtarget, DAG, DL);
21043 /// PerformShiftCombine - Combine shifts.
21044 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21045 TargetLowering::DAGCombinerInfo &DCI,
21046 const X86Subtarget *Subtarget) {
21047 if (N->getOpcode() == ISD::SHL) {
21048 SDValue V = PerformSHLCombine(N, DAG);
21049 if (V.getNode()) return V;
21052 if (N->getOpcode() != ISD::SRA) {
21053 // Try to fold this logical shift into a zero vector.
21054 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21055 if (V.getNode()) return V;
21061 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21062 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21063 // and friends. Likewise for OR -> CMPNEQSS.
21064 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21065 TargetLowering::DAGCombinerInfo &DCI,
21066 const X86Subtarget *Subtarget) {
21069 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21070 // we're requiring SSE2 for both.
21071 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21072 SDValue N0 = N->getOperand(0);
21073 SDValue N1 = N->getOperand(1);
21074 SDValue CMP0 = N0->getOperand(1);
21075 SDValue CMP1 = N1->getOperand(1);
21078 // The SETCCs should both refer to the same CMP.
21079 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21082 SDValue CMP00 = CMP0->getOperand(0);
21083 SDValue CMP01 = CMP0->getOperand(1);
21084 EVT VT = CMP00.getValueType();
21086 if (VT == MVT::f32 || VT == MVT::f64) {
21087 bool ExpectingFlags = false;
21088 // Check for any users that want flags:
21089 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21090 !ExpectingFlags && UI != UE; ++UI)
21091 switch (UI->getOpcode()) {
21096 ExpectingFlags = true;
21098 case ISD::CopyToReg:
21099 case ISD::SIGN_EXTEND:
21100 case ISD::ZERO_EXTEND:
21101 case ISD::ANY_EXTEND:
21105 if (!ExpectingFlags) {
21106 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21107 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21109 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21110 X86::CondCode tmp = cc0;
21115 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21116 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21117 // FIXME: need symbolic constants for these magic numbers.
21118 // See X86ATTInstPrinter.cpp:printSSECC().
21119 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21120 if (Subtarget->hasAVX512()) {
21121 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21122 CMP01, DAG.getConstant(x86cc, MVT::i8));
21123 if (N->getValueType(0) != MVT::i1)
21124 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21128 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21129 CMP00.getValueType(), CMP00, CMP01,
21130 DAG.getConstant(x86cc, MVT::i8));
21132 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21133 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21135 if (is64BitFP && !Subtarget->is64Bit()) {
21136 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21137 // 64-bit integer, since that's not a legal type. Since
21138 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21139 // bits, but can do this little dance to extract the lowest 32 bits
21140 // and work with those going forward.
21141 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21143 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21145 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21146 Vector32, DAG.getIntPtrConstant(0));
21150 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21151 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21152 DAG.getConstant(1, IntVT));
21153 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21154 return OneBitOfTruth;
21162 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21163 /// so it can be folded inside ANDNP.
21164 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21165 EVT VT = N->getValueType(0);
21167 // Match direct AllOnes for 128 and 256-bit vectors
21168 if (ISD::isBuildVectorAllOnes(N))
21171 // Look through a bit convert.
21172 if (N->getOpcode() == ISD::BITCAST)
21173 N = N->getOperand(0).getNode();
21175 // Sometimes the operand may come from a insert_subvector building a 256-bit
21177 if (VT.is256BitVector() &&
21178 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21179 SDValue V1 = N->getOperand(0);
21180 SDValue V2 = N->getOperand(1);
21182 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21183 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21184 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21185 ISD::isBuildVectorAllOnes(V2.getNode()))
21192 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21193 // register. In most cases we actually compare or select YMM-sized registers
21194 // and mixing the two types creates horrible code. This method optimizes
21195 // some of the transition sequences.
21196 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21197 TargetLowering::DAGCombinerInfo &DCI,
21198 const X86Subtarget *Subtarget) {
21199 EVT VT = N->getValueType(0);
21200 if (!VT.is256BitVector())
21203 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21204 N->getOpcode() == ISD::ZERO_EXTEND ||
21205 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21207 SDValue Narrow = N->getOperand(0);
21208 EVT NarrowVT = Narrow->getValueType(0);
21209 if (!NarrowVT.is128BitVector())
21212 if (Narrow->getOpcode() != ISD::XOR &&
21213 Narrow->getOpcode() != ISD::AND &&
21214 Narrow->getOpcode() != ISD::OR)
21217 SDValue N0 = Narrow->getOperand(0);
21218 SDValue N1 = Narrow->getOperand(1);
21221 // The Left side has to be a trunc.
21222 if (N0.getOpcode() != ISD::TRUNCATE)
21225 // The type of the truncated inputs.
21226 EVT WideVT = N0->getOperand(0)->getValueType(0);
21230 // The right side has to be a 'trunc' or a constant vector.
21231 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21232 ConstantSDNode *RHSConstSplat = nullptr;
21233 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21234 RHSConstSplat = RHSBV->getConstantSplatNode();
21235 if (!RHSTrunc && !RHSConstSplat)
21238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21240 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21243 // Set N0 and N1 to hold the inputs to the new wide operation.
21244 N0 = N0->getOperand(0);
21245 if (RHSConstSplat) {
21246 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21247 SDValue(RHSConstSplat, 0));
21248 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21249 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21250 } else if (RHSTrunc) {
21251 N1 = N1->getOperand(0);
21254 // Generate the wide operation.
21255 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21256 unsigned Opcode = N->getOpcode();
21258 case ISD::ANY_EXTEND:
21260 case ISD::ZERO_EXTEND: {
21261 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21262 APInt Mask = APInt::getAllOnesValue(InBits);
21263 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21264 return DAG.getNode(ISD::AND, DL, VT,
21265 Op, DAG.getConstant(Mask, VT));
21267 case ISD::SIGN_EXTEND:
21268 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21269 Op, DAG.getValueType(NarrowVT));
21271 llvm_unreachable("Unexpected opcode");
21275 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21276 TargetLowering::DAGCombinerInfo &DCI,
21277 const X86Subtarget *Subtarget) {
21278 EVT VT = N->getValueType(0);
21279 if (DCI.isBeforeLegalizeOps())
21282 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21286 // Create BEXTR instructions
21287 // BEXTR is ((X >> imm) & (2**size-1))
21288 if (VT == MVT::i32 || VT == MVT::i64) {
21289 SDValue N0 = N->getOperand(0);
21290 SDValue N1 = N->getOperand(1);
21293 // Check for BEXTR.
21294 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21295 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21296 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21297 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21298 if (MaskNode && ShiftNode) {
21299 uint64_t Mask = MaskNode->getZExtValue();
21300 uint64_t Shift = ShiftNode->getZExtValue();
21301 if (isMask_64(Mask)) {
21302 uint64_t MaskSize = CountPopulation_64(Mask);
21303 if (Shift + MaskSize <= VT.getSizeInBits())
21304 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21305 DAG.getConstant(Shift | (MaskSize << 8), VT));
21313 // Want to form ANDNP nodes:
21314 // 1) In the hopes of then easily combining them with OR and AND nodes
21315 // to form PBLEND/PSIGN.
21316 // 2) To match ANDN packed intrinsics
21317 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21320 SDValue N0 = N->getOperand(0);
21321 SDValue N1 = N->getOperand(1);
21324 // Check LHS for vnot
21325 if (N0.getOpcode() == ISD::XOR &&
21326 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21327 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21328 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21330 // Check RHS for vnot
21331 if (N1.getOpcode() == ISD::XOR &&
21332 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21333 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21334 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21339 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21340 TargetLowering::DAGCombinerInfo &DCI,
21341 const X86Subtarget *Subtarget) {
21342 if (DCI.isBeforeLegalizeOps())
21345 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21349 SDValue N0 = N->getOperand(0);
21350 SDValue N1 = N->getOperand(1);
21351 EVT VT = N->getValueType(0);
21353 // look for psign/blend
21354 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21355 if (!Subtarget->hasSSSE3() ||
21356 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21359 // Canonicalize pandn to RHS
21360 if (N0.getOpcode() == X86ISD::ANDNP)
21362 // or (and (m, y), (pandn m, x))
21363 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21364 SDValue Mask = N1.getOperand(0);
21365 SDValue X = N1.getOperand(1);
21367 if (N0.getOperand(0) == Mask)
21368 Y = N0.getOperand(1);
21369 if (N0.getOperand(1) == Mask)
21370 Y = N0.getOperand(0);
21372 // Check to see if the mask appeared in both the AND and ANDNP and
21376 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21377 // Look through mask bitcast.
21378 if (Mask.getOpcode() == ISD::BITCAST)
21379 Mask = Mask.getOperand(0);
21380 if (X.getOpcode() == ISD::BITCAST)
21381 X = X.getOperand(0);
21382 if (Y.getOpcode() == ISD::BITCAST)
21383 Y = Y.getOperand(0);
21385 EVT MaskVT = Mask.getValueType();
21387 // Validate that the Mask operand is a vector sra node.
21388 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21389 // there is no psrai.b
21390 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21391 unsigned SraAmt = ~0;
21392 if (Mask.getOpcode() == ISD::SRA) {
21393 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21394 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21395 SraAmt = AmtConst->getZExtValue();
21396 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21397 SDValue SraC = Mask.getOperand(1);
21398 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21400 if ((SraAmt + 1) != EltBits)
21405 // Now we know we at least have a plendvb with the mask val. See if
21406 // we can form a psignb/w/d.
21407 // psign = x.type == y.type == mask.type && y = sub(0, x);
21408 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21409 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21410 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21411 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21412 "Unsupported VT for PSIGN");
21413 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21414 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21416 // PBLENDVB only available on SSE 4.1
21417 if (!Subtarget->hasSSE41())
21420 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21422 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21423 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21424 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21425 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21426 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21430 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21433 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21434 MachineFunction &MF = DAG.getMachineFunction();
21435 bool OptForSize = MF.getFunction()->getAttributes().
21436 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21438 // SHLD/SHRD instructions have lower register pressure, but on some
21439 // platforms they have higher latency than the equivalent
21440 // series of shifts/or that would otherwise be generated.
21441 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21442 // have higher latencies and we are not optimizing for size.
21443 if (!OptForSize && Subtarget->isSHLDSlow())
21446 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21448 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21450 if (!N0.hasOneUse() || !N1.hasOneUse())
21453 SDValue ShAmt0 = N0.getOperand(1);
21454 if (ShAmt0.getValueType() != MVT::i8)
21456 SDValue ShAmt1 = N1.getOperand(1);
21457 if (ShAmt1.getValueType() != MVT::i8)
21459 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21460 ShAmt0 = ShAmt0.getOperand(0);
21461 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21462 ShAmt1 = ShAmt1.getOperand(0);
21465 unsigned Opc = X86ISD::SHLD;
21466 SDValue Op0 = N0.getOperand(0);
21467 SDValue Op1 = N1.getOperand(0);
21468 if (ShAmt0.getOpcode() == ISD::SUB) {
21469 Opc = X86ISD::SHRD;
21470 std::swap(Op0, Op1);
21471 std::swap(ShAmt0, ShAmt1);
21474 unsigned Bits = VT.getSizeInBits();
21475 if (ShAmt1.getOpcode() == ISD::SUB) {
21476 SDValue Sum = ShAmt1.getOperand(0);
21477 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21478 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21479 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21480 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21481 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21482 return DAG.getNode(Opc, DL, VT,
21484 DAG.getNode(ISD::TRUNCATE, DL,
21487 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21488 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21490 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21491 return DAG.getNode(Opc, DL, VT,
21492 N0.getOperand(0), N1.getOperand(0),
21493 DAG.getNode(ISD::TRUNCATE, DL,
21500 // Generate NEG and CMOV for integer abs.
21501 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21502 EVT VT = N->getValueType(0);
21504 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21505 // 8-bit integer abs to NEG and CMOV.
21506 if (VT.isInteger() && VT.getSizeInBits() == 8)
21509 SDValue N0 = N->getOperand(0);
21510 SDValue N1 = N->getOperand(1);
21513 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21514 // and change it to SUB and CMOV.
21515 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21516 N0.getOpcode() == ISD::ADD &&
21517 N0.getOperand(1) == N1 &&
21518 N1.getOpcode() == ISD::SRA &&
21519 N1.getOperand(0) == N0.getOperand(0))
21520 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21521 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21522 // Generate SUB & CMOV.
21523 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21524 DAG.getConstant(0, VT), N0.getOperand(0));
21526 SDValue Ops[] = { N0.getOperand(0), Neg,
21527 DAG.getConstant(X86::COND_GE, MVT::i8),
21528 SDValue(Neg.getNode(), 1) };
21529 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21534 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21535 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21536 TargetLowering::DAGCombinerInfo &DCI,
21537 const X86Subtarget *Subtarget) {
21538 if (DCI.isBeforeLegalizeOps())
21541 if (Subtarget->hasCMov()) {
21542 SDValue RV = performIntegerAbsCombine(N, DAG);
21550 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21551 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21552 TargetLowering::DAGCombinerInfo &DCI,
21553 const X86Subtarget *Subtarget) {
21554 LoadSDNode *Ld = cast<LoadSDNode>(N);
21555 EVT RegVT = Ld->getValueType(0);
21556 EVT MemVT = Ld->getMemoryVT();
21558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21560 // On Sandybridge unaligned 256bit loads are inefficient.
21561 ISD::LoadExtType Ext = Ld->getExtensionType();
21562 unsigned Alignment = Ld->getAlignment();
21563 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21564 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21565 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21566 unsigned NumElems = RegVT.getVectorNumElements();
21570 SDValue Ptr = Ld->getBasePtr();
21571 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21573 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21575 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21576 Ld->getPointerInfo(), Ld->isVolatile(),
21577 Ld->isNonTemporal(), Ld->isInvariant(),
21579 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21580 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21581 Ld->getPointerInfo(), Ld->isVolatile(),
21582 Ld->isNonTemporal(), Ld->isInvariant(),
21583 std::min(16U, Alignment));
21584 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21586 Load2.getValue(1));
21588 SDValue NewVec = DAG.getUNDEF(RegVT);
21589 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21590 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21591 return DCI.CombineTo(N, NewVec, TF, true);
21597 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21598 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21599 const X86Subtarget *Subtarget) {
21600 StoreSDNode *St = cast<StoreSDNode>(N);
21601 EVT VT = St->getValue().getValueType();
21602 EVT StVT = St->getMemoryVT();
21604 SDValue StoredVal = St->getOperand(1);
21605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21607 // If we are saving a concatenation of two XMM registers, perform two stores.
21608 // On Sandy Bridge, 256-bit memory operations are executed by two
21609 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21610 // memory operation.
21611 unsigned Alignment = St->getAlignment();
21612 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21613 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21614 StVT == VT && !IsAligned) {
21615 unsigned NumElems = VT.getVectorNumElements();
21619 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21620 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21622 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21623 SDValue Ptr0 = St->getBasePtr();
21624 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21626 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21627 St->getPointerInfo(), St->isVolatile(),
21628 St->isNonTemporal(), Alignment);
21629 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21630 St->getPointerInfo(), St->isVolatile(),
21631 St->isNonTemporal(),
21632 std::min(16U, Alignment));
21633 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21636 // Optimize trunc store (of multiple scalars) to shuffle and store.
21637 // First, pack all of the elements in one place. Next, store to memory
21638 // in fewer chunks.
21639 if (St->isTruncatingStore() && VT.isVector()) {
21640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21641 unsigned NumElems = VT.getVectorNumElements();
21642 assert(StVT != VT && "Cannot truncate to the same type");
21643 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21644 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21646 // From, To sizes and ElemCount must be pow of two
21647 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21648 // We are going to use the original vector elt for storing.
21649 // Accumulated smaller vector elements must be a multiple of the store size.
21650 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21652 unsigned SizeRatio = FromSz / ToSz;
21654 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21656 // Create a type on which we perform the shuffle
21657 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21658 StVT.getScalarType(), NumElems*SizeRatio);
21660 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21662 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21663 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21664 for (unsigned i = 0; i != NumElems; ++i)
21665 ShuffleVec[i] = i * SizeRatio;
21667 // Can't shuffle using an illegal type.
21668 if (!TLI.isTypeLegal(WideVecVT))
21671 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21672 DAG.getUNDEF(WideVecVT),
21674 // At this point all of the data is stored at the bottom of the
21675 // register. We now need to save it to mem.
21677 // Find the largest store unit
21678 MVT StoreType = MVT::i8;
21679 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21680 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21681 MVT Tp = (MVT::SimpleValueType)tp;
21682 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21686 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21687 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21688 (64 <= NumElems * ToSz))
21689 StoreType = MVT::f64;
21691 // Bitcast the original vector into a vector of store-size units
21692 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21693 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21694 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21695 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21696 SmallVector<SDValue, 8> Chains;
21697 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21698 TLI.getPointerTy());
21699 SDValue Ptr = St->getBasePtr();
21701 // Perform one or more big stores into memory.
21702 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21703 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21704 StoreType, ShuffWide,
21705 DAG.getIntPtrConstant(i));
21706 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21707 St->getPointerInfo(), St->isVolatile(),
21708 St->isNonTemporal(), St->getAlignment());
21709 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21710 Chains.push_back(Ch);
21713 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21716 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21717 // the FP state in cases where an emms may be missing.
21718 // A preferable solution to the general problem is to figure out the right
21719 // places to insert EMMS. This qualifies as a quick hack.
21721 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21722 if (VT.getSizeInBits() != 64)
21725 const Function *F = DAG.getMachineFunction().getFunction();
21726 bool NoImplicitFloatOps = F->getAttributes().
21727 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21728 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21729 && Subtarget->hasSSE2();
21730 if ((VT.isVector() ||
21731 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21732 isa<LoadSDNode>(St->getValue()) &&
21733 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21734 St->getChain().hasOneUse() && !St->isVolatile()) {
21735 SDNode* LdVal = St->getValue().getNode();
21736 LoadSDNode *Ld = nullptr;
21737 int TokenFactorIndex = -1;
21738 SmallVector<SDValue, 8> Ops;
21739 SDNode* ChainVal = St->getChain().getNode();
21740 // Must be a store of a load. We currently handle two cases: the load
21741 // is a direct child, and it's under an intervening TokenFactor. It is
21742 // possible to dig deeper under nested TokenFactors.
21743 if (ChainVal == LdVal)
21744 Ld = cast<LoadSDNode>(St->getChain());
21745 else if (St->getValue().hasOneUse() &&
21746 ChainVal->getOpcode() == ISD::TokenFactor) {
21747 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21748 if (ChainVal->getOperand(i).getNode() == LdVal) {
21749 TokenFactorIndex = i;
21750 Ld = cast<LoadSDNode>(St->getValue());
21752 Ops.push_back(ChainVal->getOperand(i));
21756 if (!Ld || !ISD::isNormalLoad(Ld))
21759 // If this is not the MMX case, i.e. we are just turning i64 load/store
21760 // into f64 load/store, avoid the transformation if there are multiple
21761 // uses of the loaded value.
21762 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21767 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21768 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21770 if (Subtarget->is64Bit() || F64IsLegal) {
21771 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21772 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21773 Ld->getPointerInfo(), Ld->isVolatile(),
21774 Ld->isNonTemporal(), Ld->isInvariant(),
21775 Ld->getAlignment());
21776 SDValue NewChain = NewLd.getValue(1);
21777 if (TokenFactorIndex != -1) {
21778 Ops.push_back(NewChain);
21779 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21781 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21782 St->getPointerInfo(),
21783 St->isVolatile(), St->isNonTemporal(),
21784 St->getAlignment());
21787 // Otherwise, lower to two pairs of 32-bit loads / stores.
21788 SDValue LoAddr = Ld->getBasePtr();
21789 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21790 DAG.getConstant(4, MVT::i32));
21792 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21793 Ld->getPointerInfo(),
21794 Ld->isVolatile(), Ld->isNonTemporal(),
21795 Ld->isInvariant(), Ld->getAlignment());
21796 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21797 Ld->getPointerInfo().getWithOffset(4),
21798 Ld->isVolatile(), Ld->isNonTemporal(),
21800 MinAlign(Ld->getAlignment(), 4));
21802 SDValue NewChain = LoLd.getValue(1);
21803 if (TokenFactorIndex != -1) {
21804 Ops.push_back(LoLd);
21805 Ops.push_back(HiLd);
21806 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21809 LoAddr = St->getBasePtr();
21810 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21811 DAG.getConstant(4, MVT::i32));
21813 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21814 St->getPointerInfo(),
21815 St->isVolatile(), St->isNonTemporal(),
21816 St->getAlignment());
21817 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21818 St->getPointerInfo().getWithOffset(4),
21820 St->isNonTemporal(),
21821 MinAlign(St->getAlignment(), 4));
21822 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21827 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21828 /// and return the operands for the horizontal operation in LHS and RHS. A
21829 /// horizontal operation performs the binary operation on successive elements
21830 /// of its first operand, then on successive elements of its second operand,
21831 /// returning the resulting values in a vector. For example, if
21832 /// A = < float a0, float a1, float a2, float a3 >
21834 /// B = < float b0, float b1, float b2, float b3 >
21835 /// then the result of doing a horizontal operation on A and B is
21836 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21837 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21838 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21839 /// set to A, RHS to B, and the routine returns 'true'.
21840 /// Note that the binary operation should have the property that if one of the
21841 /// operands is UNDEF then the result is UNDEF.
21842 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21843 // Look for the following pattern: if
21844 // A = < float a0, float a1, float a2, float a3 >
21845 // B = < float b0, float b1, float b2, float b3 >
21847 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21848 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21849 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21850 // which is A horizontal-op B.
21852 // At least one of the operands should be a vector shuffle.
21853 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21854 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21857 MVT VT = LHS.getSimpleValueType();
21859 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21860 "Unsupported vector type for horizontal add/sub");
21862 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21863 // operate independently on 128-bit lanes.
21864 unsigned NumElts = VT.getVectorNumElements();
21865 unsigned NumLanes = VT.getSizeInBits()/128;
21866 unsigned NumLaneElts = NumElts / NumLanes;
21867 assert((NumLaneElts % 2 == 0) &&
21868 "Vector type should have an even number of elements in each lane");
21869 unsigned HalfLaneElts = NumLaneElts/2;
21871 // View LHS in the form
21872 // LHS = VECTOR_SHUFFLE A, B, LMask
21873 // If LHS is not a shuffle then pretend it is the shuffle
21874 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21875 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21878 SmallVector<int, 16> LMask(NumElts);
21879 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21880 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21881 A = LHS.getOperand(0);
21882 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21883 B = LHS.getOperand(1);
21884 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21885 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21887 if (LHS.getOpcode() != ISD::UNDEF)
21889 for (unsigned i = 0; i != NumElts; ++i)
21893 // Likewise, view RHS in the form
21894 // RHS = VECTOR_SHUFFLE C, D, RMask
21896 SmallVector<int, 16> RMask(NumElts);
21897 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21898 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21899 C = RHS.getOperand(0);
21900 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21901 D = RHS.getOperand(1);
21902 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21903 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21905 if (RHS.getOpcode() != ISD::UNDEF)
21907 for (unsigned i = 0; i != NumElts; ++i)
21911 // Check that the shuffles are both shuffling the same vectors.
21912 if (!(A == C && B == D) && !(A == D && B == C))
21915 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21916 if (!A.getNode() && !B.getNode())
21919 // If A and B occur in reverse order in RHS, then "swap" them (which means
21920 // rewriting the mask).
21922 CommuteVectorShuffleMask(RMask, NumElts);
21924 // At this point LHS and RHS are equivalent to
21925 // LHS = VECTOR_SHUFFLE A, B, LMask
21926 // RHS = VECTOR_SHUFFLE A, B, RMask
21927 // Check that the masks correspond to performing a horizontal operation.
21928 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21929 for (unsigned i = 0; i != NumLaneElts; ++i) {
21930 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21932 // Ignore any UNDEF components.
21933 if (LIdx < 0 || RIdx < 0 ||
21934 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21935 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21938 // Check that successive elements are being operated on. If not, this is
21939 // not a horizontal operation.
21940 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21941 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21942 if (!(LIdx == Index && RIdx == Index + 1) &&
21943 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21948 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21949 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21953 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21954 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21955 const X86Subtarget *Subtarget) {
21956 EVT VT = N->getValueType(0);
21957 SDValue LHS = N->getOperand(0);
21958 SDValue RHS = N->getOperand(1);
21960 // Try to synthesize horizontal adds from adds of shuffles.
21961 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21962 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21963 isHorizontalBinOp(LHS, RHS, true))
21964 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21968 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21969 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21970 const X86Subtarget *Subtarget) {
21971 EVT VT = N->getValueType(0);
21972 SDValue LHS = N->getOperand(0);
21973 SDValue RHS = N->getOperand(1);
21975 // Try to synthesize horizontal subs from subs of shuffles.
21976 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21977 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21978 isHorizontalBinOp(LHS, RHS, false))
21979 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21983 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21984 /// X86ISD::FXOR nodes.
21985 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21986 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21987 // F[X]OR(0.0, x) -> x
21988 // F[X]OR(x, 0.0) -> x
21989 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21990 if (C->getValueAPF().isPosZero())
21991 return N->getOperand(1);
21992 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21993 if (C->getValueAPF().isPosZero())
21994 return N->getOperand(0);
21998 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21999 /// X86ISD::FMAX nodes.
22000 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22001 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22003 // Only perform optimizations if UnsafeMath is used.
22004 if (!DAG.getTarget().Options.UnsafeFPMath)
22007 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22008 // into FMINC and FMAXC, which are Commutative operations.
22009 unsigned NewOp = 0;
22010 switch (N->getOpcode()) {
22011 default: llvm_unreachable("unknown opcode");
22012 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22013 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22016 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22017 N->getOperand(0), N->getOperand(1));
22020 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22021 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22022 // FAND(0.0, x) -> 0.0
22023 // FAND(x, 0.0) -> 0.0
22024 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22025 if (C->getValueAPF().isPosZero())
22026 return N->getOperand(0);
22027 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22028 if (C->getValueAPF().isPosZero())
22029 return N->getOperand(1);
22033 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22034 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22035 // FANDN(x, 0.0) -> 0.0
22036 // FANDN(0.0, x) -> x
22037 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22038 if (C->getValueAPF().isPosZero())
22039 return N->getOperand(1);
22040 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22041 if (C->getValueAPF().isPosZero())
22042 return N->getOperand(1);
22046 static SDValue PerformBTCombine(SDNode *N,
22048 TargetLowering::DAGCombinerInfo &DCI) {
22049 // BT ignores high bits in the bit index operand.
22050 SDValue Op1 = N->getOperand(1);
22051 if (Op1.hasOneUse()) {
22052 unsigned BitWidth = Op1.getValueSizeInBits();
22053 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22054 APInt KnownZero, KnownOne;
22055 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22056 !DCI.isBeforeLegalizeOps());
22057 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22058 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22059 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22060 DCI.CommitTargetLoweringOpt(TLO);
22065 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22066 SDValue Op = N->getOperand(0);
22067 if (Op.getOpcode() == ISD::BITCAST)
22068 Op = Op.getOperand(0);
22069 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22070 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22071 VT.getVectorElementType().getSizeInBits() ==
22072 OpVT.getVectorElementType().getSizeInBits()) {
22073 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22078 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22079 const X86Subtarget *Subtarget) {
22080 EVT VT = N->getValueType(0);
22081 if (!VT.isVector())
22084 SDValue N0 = N->getOperand(0);
22085 SDValue N1 = N->getOperand(1);
22086 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22089 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22090 // both SSE and AVX2 since there is no sign-extended shift right
22091 // operation on a vector with 64-bit elements.
22092 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22093 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22094 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22095 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22096 SDValue N00 = N0.getOperand(0);
22098 // EXTLOAD has a better solution on AVX2,
22099 // it may be replaced with X86ISD::VSEXT node.
22100 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22101 if (!ISD::isNormalLoad(N00.getNode()))
22104 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22105 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22107 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22113 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22114 TargetLowering::DAGCombinerInfo &DCI,
22115 const X86Subtarget *Subtarget) {
22116 if (!DCI.isBeforeLegalizeOps())
22119 if (!Subtarget->hasFp256())
22122 EVT VT = N->getValueType(0);
22123 if (VT.isVector() && VT.getSizeInBits() == 256) {
22124 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22132 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22133 const X86Subtarget* Subtarget) {
22135 EVT VT = N->getValueType(0);
22137 // Let legalize expand this if it isn't a legal type yet.
22138 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22141 EVT ScalarVT = VT.getScalarType();
22142 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22143 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22146 SDValue A = N->getOperand(0);
22147 SDValue B = N->getOperand(1);
22148 SDValue C = N->getOperand(2);
22150 bool NegA = (A.getOpcode() == ISD::FNEG);
22151 bool NegB = (B.getOpcode() == ISD::FNEG);
22152 bool NegC = (C.getOpcode() == ISD::FNEG);
22154 // Negative multiplication when NegA xor NegB
22155 bool NegMul = (NegA != NegB);
22157 A = A.getOperand(0);
22159 B = B.getOperand(0);
22161 C = C.getOperand(0);
22165 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22167 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22169 return DAG.getNode(Opcode, dl, VT, A, B, C);
22172 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22173 TargetLowering::DAGCombinerInfo &DCI,
22174 const X86Subtarget *Subtarget) {
22175 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22176 // (and (i32 x86isd::setcc_carry), 1)
22177 // This eliminates the zext. This transformation is necessary because
22178 // ISD::SETCC is always legalized to i8.
22180 SDValue N0 = N->getOperand(0);
22181 EVT VT = N->getValueType(0);
22183 if (N0.getOpcode() == ISD::AND &&
22185 N0.getOperand(0).hasOneUse()) {
22186 SDValue N00 = N0.getOperand(0);
22187 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22188 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22189 if (!C || C->getZExtValue() != 1)
22191 return DAG.getNode(ISD::AND, dl, VT,
22192 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22193 N00.getOperand(0), N00.getOperand(1)),
22194 DAG.getConstant(1, VT));
22198 if (N0.getOpcode() == ISD::TRUNCATE &&
22200 N0.getOperand(0).hasOneUse()) {
22201 SDValue N00 = N0.getOperand(0);
22202 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22203 return DAG.getNode(ISD::AND, dl, VT,
22204 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22205 N00.getOperand(0), N00.getOperand(1)),
22206 DAG.getConstant(1, VT));
22209 if (VT.is256BitVector()) {
22210 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22218 // Optimize x == -y --> x+y == 0
22219 // x != -y --> x+y != 0
22220 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22221 const X86Subtarget* Subtarget) {
22222 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22223 SDValue LHS = N->getOperand(0);
22224 SDValue RHS = N->getOperand(1);
22225 EVT VT = N->getValueType(0);
22228 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22229 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22230 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22231 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22232 LHS.getValueType(), RHS, LHS.getOperand(1));
22233 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22234 addV, DAG.getConstant(0, addV.getValueType()), CC);
22236 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22238 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22239 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22240 RHS.getValueType(), LHS, RHS.getOperand(1));
22241 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22242 addV, DAG.getConstant(0, addV.getValueType()), CC);
22245 if (VT.getScalarType() == MVT::i1) {
22246 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22247 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22248 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22249 if (!IsSEXT0 && !IsVZero0)
22251 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22252 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22253 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22255 if (!IsSEXT1 && !IsVZero1)
22258 if (IsSEXT0 && IsVZero1) {
22259 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22260 if (CC == ISD::SETEQ)
22261 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22262 return LHS.getOperand(0);
22264 if (IsSEXT1 && IsVZero0) {
22265 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22266 if (CC == ISD::SETEQ)
22267 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22268 return RHS.getOperand(0);
22275 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22276 const X86Subtarget *Subtarget) {
22278 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22279 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22280 "X86insertps is only defined for v4x32");
22282 SDValue Ld = N->getOperand(1);
22283 if (MayFoldLoad(Ld)) {
22284 // Extract the countS bits from the immediate so we can get the proper
22285 // address when narrowing the vector load to a specific element.
22286 // When the second source op is a memory address, interps doesn't use
22287 // countS and just gets an f32 from that address.
22288 unsigned DestIndex =
22289 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22290 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22294 // Create this as a scalar to vector to match the instruction pattern.
22295 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22296 // countS bits are ignored when loading from memory on insertps, which
22297 // means we don't need to explicitly set them to 0.
22298 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22299 LoadScalarToVector, N->getOperand(2));
22302 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22303 // as "sbb reg,reg", since it can be extended without zext and produces
22304 // an all-ones bit which is more useful than 0/1 in some cases.
22305 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22308 return DAG.getNode(ISD::AND, DL, VT,
22309 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22310 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22311 DAG.getConstant(1, VT));
22312 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22313 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22314 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22315 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22318 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22319 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22320 TargetLowering::DAGCombinerInfo &DCI,
22321 const X86Subtarget *Subtarget) {
22323 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22324 SDValue EFLAGS = N->getOperand(1);
22326 if (CC == X86::COND_A) {
22327 // Try to convert COND_A into COND_B in an attempt to facilitate
22328 // materializing "setb reg".
22330 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22331 // cannot take an immediate as its first operand.
22333 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22334 EFLAGS.getValueType().isInteger() &&
22335 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22336 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22337 EFLAGS.getNode()->getVTList(),
22338 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22339 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22340 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22344 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22345 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22347 if (CC == X86::COND_B)
22348 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22352 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22353 if (Flags.getNode()) {
22354 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22355 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22361 // Optimize branch condition evaluation.
22363 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22364 TargetLowering::DAGCombinerInfo &DCI,
22365 const X86Subtarget *Subtarget) {
22367 SDValue Chain = N->getOperand(0);
22368 SDValue Dest = N->getOperand(1);
22369 SDValue EFLAGS = N->getOperand(3);
22370 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22374 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22375 if (Flags.getNode()) {
22376 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22377 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22384 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22385 SelectionDAG &DAG) {
22386 // Take advantage of vector comparisons producing 0 or -1 in each lane to
22387 // optimize away operation when it's from a constant.
22389 // The general transformation is:
22390 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22391 // AND(VECTOR_CMP(x,y), constant2)
22392 // constant2 = UNARYOP(constant)
22394 // Early exit if this isn't a vector operation, the operand of the
22395 // unary operation isn't a bitwise AND, or if the sizes of the operations
22396 // aren't the same.
22397 EVT VT = N->getValueType(0);
22398 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22399 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22400 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22403 // Now check that the other operand of the AND is a constant. We could
22404 // make the transformation for non-constant splats as well, but it's unclear
22405 // that would be a benefit as it would not eliminate any operations, just
22406 // perform one more step in scalar code before moving to the vector unit.
22407 if (BuildVectorSDNode *BV =
22408 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22409 // Bail out if the vector isn't a constant.
22410 if (!BV->isConstant())
22413 // Everything checks out. Build up the new and improved node.
22415 EVT IntVT = BV->getValueType(0);
22416 // Create a new constant of the appropriate type for the transformed
22418 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22419 // The AND node needs bitcasts to/from an integer vector type around it.
22420 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22421 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22422 N->getOperand(0)->getOperand(0), MaskConst);
22423 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22430 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22431 const X86TargetLowering *XTLI) {
22432 // First try to optimize away the conversion entirely when it's
22433 // conditionally from a constant. Vectors only.
22434 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22435 if (Res != SDValue())
22438 // Now move on to more general possibilities.
22439 SDValue Op0 = N->getOperand(0);
22440 EVT InVT = Op0->getValueType(0);
22442 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22443 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22445 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22446 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22447 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22450 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22451 // a 32-bit target where SSE doesn't support i64->FP operations.
22452 if (Op0.getOpcode() == ISD::LOAD) {
22453 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22454 EVT VT = Ld->getValueType(0);
22455 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22456 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22457 !XTLI->getSubtarget()->is64Bit() &&
22459 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22460 Ld->getChain(), Op0, DAG);
22461 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22468 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22469 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22470 X86TargetLowering::DAGCombinerInfo &DCI) {
22471 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22472 // the result is either zero or one (depending on the input carry bit).
22473 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22474 if (X86::isZeroNode(N->getOperand(0)) &&
22475 X86::isZeroNode(N->getOperand(1)) &&
22476 // We don't have a good way to replace an EFLAGS use, so only do this when
22478 SDValue(N, 1).use_empty()) {
22480 EVT VT = N->getValueType(0);
22481 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22482 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22483 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22484 DAG.getConstant(X86::COND_B,MVT::i8),
22486 DAG.getConstant(1, VT));
22487 return DCI.CombineTo(N, Res1, CarryOut);
22493 // fold (add Y, (sete X, 0)) -> adc 0, Y
22494 // (add Y, (setne X, 0)) -> sbb -1, Y
22495 // (sub (sete X, 0), Y) -> sbb 0, Y
22496 // (sub (setne X, 0), Y) -> adc -1, Y
22497 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22500 // Look through ZExts.
22501 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22502 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22505 SDValue SetCC = Ext.getOperand(0);
22506 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22509 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22510 if (CC != X86::COND_E && CC != X86::COND_NE)
22513 SDValue Cmp = SetCC.getOperand(1);
22514 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22515 !X86::isZeroNode(Cmp.getOperand(1)) ||
22516 !Cmp.getOperand(0).getValueType().isInteger())
22519 SDValue CmpOp0 = Cmp.getOperand(0);
22520 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22521 DAG.getConstant(1, CmpOp0.getValueType()));
22523 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22524 if (CC == X86::COND_NE)
22525 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22526 DL, OtherVal.getValueType(), OtherVal,
22527 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22528 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22529 DL, OtherVal.getValueType(), OtherVal,
22530 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22533 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22534 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22535 const X86Subtarget *Subtarget) {
22536 EVT VT = N->getValueType(0);
22537 SDValue Op0 = N->getOperand(0);
22538 SDValue Op1 = N->getOperand(1);
22540 // Try to synthesize horizontal adds from adds of shuffles.
22541 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22542 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22543 isHorizontalBinOp(Op0, Op1, true))
22544 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22546 return OptimizeConditionalInDecrement(N, DAG);
22549 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22550 const X86Subtarget *Subtarget) {
22551 SDValue Op0 = N->getOperand(0);
22552 SDValue Op1 = N->getOperand(1);
22554 // X86 can't encode an immediate LHS of a sub. See if we can push the
22555 // negation into a preceding instruction.
22556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22557 // If the RHS of the sub is a XOR with one use and a constant, invert the
22558 // immediate. Then add one to the LHS of the sub so we can turn
22559 // X-Y -> X+~Y+1, saving one register.
22560 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22561 isa<ConstantSDNode>(Op1.getOperand(1))) {
22562 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22563 EVT VT = Op0.getValueType();
22564 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22566 DAG.getConstant(~XorC, VT));
22567 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22568 DAG.getConstant(C->getAPIntValue()+1, VT));
22572 // Try to synthesize horizontal adds from adds of shuffles.
22573 EVT VT = N->getValueType(0);
22574 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22575 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22576 isHorizontalBinOp(Op0, Op1, true))
22577 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22579 return OptimizeConditionalInDecrement(N, DAG);
22582 /// performVZEXTCombine - Performs build vector combines
22583 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22584 TargetLowering::DAGCombinerInfo &DCI,
22585 const X86Subtarget *Subtarget) {
22586 // (vzext (bitcast (vzext (x)) -> (vzext x)
22587 SDValue In = N->getOperand(0);
22588 while (In.getOpcode() == ISD::BITCAST)
22589 In = In.getOperand(0);
22591 if (In.getOpcode() != X86ISD::VZEXT)
22594 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22598 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22599 DAGCombinerInfo &DCI) const {
22600 SelectionDAG &DAG = DCI.DAG;
22601 switch (N->getOpcode()) {
22603 case ISD::EXTRACT_VECTOR_ELT:
22604 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22606 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22607 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22608 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22609 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22610 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22611 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22614 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22615 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22616 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22617 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22618 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22619 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22620 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22621 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22622 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22624 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22626 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22627 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22628 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22629 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22630 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22631 case ISD::ANY_EXTEND:
22632 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22633 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22634 case ISD::SIGN_EXTEND_INREG:
22635 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22636 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22637 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22638 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22639 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22640 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22641 case X86ISD::SHUFP: // Handle all target specific shuffles
22642 case X86ISD::PALIGNR:
22643 case X86ISD::UNPCKH:
22644 case X86ISD::UNPCKL:
22645 case X86ISD::MOVHLPS:
22646 case X86ISD::MOVLHPS:
22647 case X86ISD::PSHUFB:
22648 case X86ISD::PSHUFD:
22649 case X86ISD::PSHUFHW:
22650 case X86ISD::PSHUFLW:
22651 case X86ISD::MOVSS:
22652 case X86ISD::MOVSD:
22653 case X86ISD::VPERMILP:
22654 case X86ISD::VPERM2X128:
22655 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22656 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22657 case ISD::INTRINSIC_WO_CHAIN:
22658 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22659 case X86ISD::INSERTPS:
22660 return PerformINSERTPSCombine(N, DAG, Subtarget);
22661 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22667 /// isTypeDesirableForOp - Return true if the target has native support for
22668 /// the specified value type and it is 'desirable' to use the type for the
22669 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22670 /// instruction encodings are longer and some i16 instructions are slow.
22671 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22672 if (!isTypeLegal(VT))
22674 if (VT != MVT::i16)
22681 case ISD::SIGN_EXTEND:
22682 case ISD::ZERO_EXTEND:
22683 case ISD::ANY_EXTEND:
22696 /// IsDesirableToPromoteOp - This method query the target whether it is
22697 /// beneficial for dag combiner to promote the specified node. If true, it
22698 /// should return the desired promotion type by reference.
22699 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22700 EVT VT = Op.getValueType();
22701 if (VT != MVT::i16)
22704 bool Promote = false;
22705 bool Commute = false;
22706 switch (Op.getOpcode()) {
22709 LoadSDNode *LD = cast<LoadSDNode>(Op);
22710 // If the non-extending load has a single use and it's not live out, then it
22711 // might be folded.
22712 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22713 Op.hasOneUse()*/) {
22714 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22715 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22716 // The only case where we'd want to promote LOAD (rather then it being
22717 // promoted as an operand is when it's only use is liveout.
22718 if (UI->getOpcode() != ISD::CopyToReg)
22725 case ISD::SIGN_EXTEND:
22726 case ISD::ZERO_EXTEND:
22727 case ISD::ANY_EXTEND:
22732 SDValue N0 = Op.getOperand(0);
22733 // Look out for (store (shl (load), x)).
22734 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22747 SDValue N0 = Op.getOperand(0);
22748 SDValue N1 = Op.getOperand(1);
22749 if (!Commute && MayFoldLoad(N1))
22751 // Avoid disabling potential load folding opportunities.
22752 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22754 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22764 //===----------------------------------------------------------------------===//
22765 // X86 Inline Assembly Support
22766 //===----------------------------------------------------------------------===//
22769 // Helper to match a string separated by whitespace.
22770 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22771 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22773 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22774 StringRef piece(*args[i]);
22775 if (!s.startswith(piece)) // Check if the piece matches.
22778 s = s.substr(piece.size());
22779 StringRef::size_type pos = s.find_first_not_of(" \t");
22780 if (pos == 0) // We matched a prefix.
22788 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22791 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22793 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22794 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22795 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22796 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22798 if (AsmPieces.size() == 3)
22800 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22807 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22808 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22810 std::string AsmStr = IA->getAsmString();
22812 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22813 if (!Ty || Ty->getBitWidth() % 16 != 0)
22816 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22817 SmallVector<StringRef, 4> AsmPieces;
22818 SplitString(AsmStr, AsmPieces, ";\n");
22820 switch (AsmPieces.size()) {
22821 default: return false;
22823 // FIXME: this should verify that we are targeting a 486 or better. If not,
22824 // we will turn this bswap into something that will be lowered to logical
22825 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22826 // lower so don't worry about this.
22828 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22829 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22830 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22831 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22832 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22833 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22834 // No need to check constraints, nothing other than the equivalent of
22835 // "=r,0" would be valid here.
22836 return IntrinsicLowering::LowerToByteSwap(CI);
22839 // rorw $$8, ${0:w} --> llvm.bswap.i16
22840 if (CI->getType()->isIntegerTy(16) &&
22841 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22842 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22843 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22845 const std::string &ConstraintsStr = IA->getConstraintString();
22846 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22847 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22848 if (clobbersFlagRegisters(AsmPieces))
22849 return IntrinsicLowering::LowerToByteSwap(CI);
22853 if (CI->getType()->isIntegerTy(32) &&
22854 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22855 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22856 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22857 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22859 const std::string &ConstraintsStr = IA->getConstraintString();
22860 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22861 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22862 if (clobbersFlagRegisters(AsmPieces))
22863 return IntrinsicLowering::LowerToByteSwap(CI);
22866 if (CI->getType()->isIntegerTy(64)) {
22867 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22868 if (Constraints.size() >= 2 &&
22869 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22870 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22871 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22872 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22873 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22874 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22875 return IntrinsicLowering::LowerToByteSwap(CI);
22883 /// getConstraintType - Given a constraint letter, return the type of
22884 /// constraint it is for this target.
22885 X86TargetLowering::ConstraintType
22886 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22887 if (Constraint.size() == 1) {
22888 switch (Constraint[0]) {
22899 return C_RegisterClass;
22923 return TargetLowering::getConstraintType(Constraint);
22926 /// Examine constraint type and operand type and determine a weight value.
22927 /// This object must already have been set up with the operand type
22928 /// and the current alternative constraint selected.
22929 TargetLowering::ConstraintWeight
22930 X86TargetLowering::getSingleConstraintMatchWeight(
22931 AsmOperandInfo &info, const char *constraint) const {
22932 ConstraintWeight weight = CW_Invalid;
22933 Value *CallOperandVal = info.CallOperandVal;
22934 // If we don't have a value, we can't do a match,
22935 // but allow it at the lowest weight.
22936 if (!CallOperandVal)
22938 Type *type = CallOperandVal->getType();
22939 // Look at the constraint type.
22940 switch (*constraint) {
22942 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22953 if (CallOperandVal->getType()->isIntegerTy())
22954 weight = CW_SpecificReg;
22959 if (type->isFloatingPointTy())
22960 weight = CW_SpecificReg;
22963 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22964 weight = CW_SpecificReg;
22968 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22969 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22970 weight = CW_Register;
22973 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22974 if (C->getZExtValue() <= 31)
22975 weight = CW_Constant;
22979 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22980 if (C->getZExtValue() <= 63)
22981 weight = CW_Constant;
22985 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22986 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22987 weight = CW_Constant;
22991 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22992 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22993 weight = CW_Constant;
22997 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22998 if (C->getZExtValue() <= 3)
22999 weight = CW_Constant;
23003 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23004 if (C->getZExtValue() <= 0xff)
23005 weight = CW_Constant;
23010 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23011 weight = CW_Constant;
23015 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23016 if ((C->getSExtValue() >= -0x80000000LL) &&
23017 (C->getSExtValue() <= 0x7fffffffLL))
23018 weight = CW_Constant;
23022 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23023 if (C->getZExtValue() <= 0xffffffff)
23024 weight = CW_Constant;
23031 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23032 /// with another that has more specific requirements based on the type of the
23033 /// corresponding operand.
23034 const char *X86TargetLowering::
23035 LowerXConstraint(EVT ConstraintVT) const {
23036 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23037 // 'f' like normal targets.
23038 if (ConstraintVT.isFloatingPoint()) {
23039 if (Subtarget->hasSSE2())
23041 if (Subtarget->hasSSE1())
23045 return TargetLowering::LowerXConstraint(ConstraintVT);
23048 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23049 /// vector. If it is invalid, don't add anything to Ops.
23050 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23051 std::string &Constraint,
23052 std::vector<SDValue>&Ops,
23053 SelectionDAG &DAG) const {
23056 // Only support length 1 constraints for now.
23057 if (Constraint.length() > 1) return;
23059 char ConstraintLetter = Constraint[0];
23060 switch (ConstraintLetter) {
23063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23064 if (C->getZExtValue() <= 31) {
23065 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23071 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23072 if (C->getZExtValue() <= 63) {
23073 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23079 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23080 if (isInt<8>(C->getSExtValue())) {
23081 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23088 if (C->getZExtValue() <= 255) {
23089 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23095 // 32-bit signed value
23096 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23097 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23098 C->getSExtValue())) {
23099 // Widen to 64 bits here to get it sign extended.
23100 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23103 // FIXME gcc accepts some relocatable values here too, but only in certain
23104 // memory models; it's complicated.
23109 // 32-bit unsigned value
23110 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23111 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23112 C->getZExtValue())) {
23113 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23117 // FIXME gcc accepts some relocatable values here too, but only in certain
23118 // memory models; it's complicated.
23122 // Literal immediates are always ok.
23123 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23124 // Widen to 64 bits here to get it sign extended.
23125 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23129 // In any sort of PIC mode addresses need to be computed at runtime by
23130 // adding in a register or some sort of table lookup. These can't
23131 // be used as immediates.
23132 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23135 // If we are in non-pic codegen mode, we allow the address of a global (with
23136 // an optional displacement) to be used with 'i'.
23137 GlobalAddressSDNode *GA = nullptr;
23138 int64_t Offset = 0;
23140 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23142 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23143 Offset += GA->getOffset();
23145 } else if (Op.getOpcode() == ISD::ADD) {
23146 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23147 Offset += C->getZExtValue();
23148 Op = Op.getOperand(0);
23151 } else if (Op.getOpcode() == ISD::SUB) {
23152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23153 Offset += -C->getZExtValue();
23154 Op = Op.getOperand(0);
23159 // Otherwise, this isn't something we can handle, reject it.
23163 const GlobalValue *GV = GA->getGlobal();
23164 // If we require an extra load to get this address, as in PIC mode, we
23165 // can't accept it.
23166 if (isGlobalStubReference(
23167 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23170 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23171 GA->getValueType(0), Offset);
23176 if (Result.getNode()) {
23177 Ops.push_back(Result);
23180 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23183 std::pair<unsigned, const TargetRegisterClass*>
23184 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23186 // First, see if this is a constraint that directly corresponds to an LLVM
23188 if (Constraint.size() == 1) {
23189 // GCC Constraint Letters
23190 switch (Constraint[0]) {
23192 // TODO: Slight differences here in allocation order and leaving
23193 // RIP in the class. Do they matter any more here than they do
23194 // in the normal allocation?
23195 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23196 if (Subtarget->is64Bit()) {
23197 if (VT == MVT::i32 || VT == MVT::f32)
23198 return std::make_pair(0U, &X86::GR32RegClass);
23199 if (VT == MVT::i16)
23200 return std::make_pair(0U, &X86::GR16RegClass);
23201 if (VT == MVT::i8 || VT == MVT::i1)
23202 return std::make_pair(0U, &X86::GR8RegClass);
23203 if (VT == MVT::i64 || VT == MVT::f64)
23204 return std::make_pair(0U, &X86::GR64RegClass);
23207 // 32-bit fallthrough
23208 case 'Q': // Q_REGS
23209 if (VT == MVT::i32 || VT == MVT::f32)
23210 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23211 if (VT == MVT::i16)
23212 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23213 if (VT == MVT::i8 || VT == MVT::i1)
23214 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23215 if (VT == MVT::i64)
23216 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23218 case 'r': // GENERAL_REGS
23219 case 'l': // INDEX_REGS
23220 if (VT == MVT::i8 || VT == MVT::i1)
23221 return std::make_pair(0U, &X86::GR8RegClass);
23222 if (VT == MVT::i16)
23223 return std::make_pair(0U, &X86::GR16RegClass);
23224 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23225 return std::make_pair(0U, &X86::GR32RegClass);
23226 return std::make_pair(0U, &X86::GR64RegClass);
23227 case 'R': // LEGACY_REGS
23228 if (VT == MVT::i8 || VT == MVT::i1)
23229 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23230 if (VT == MVT::i16)
23231 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23232 if (VT == MVT::i32 || !Subtarget->is64Bit())
23233 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23234 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23235 case 'f': // FP Stack registers.
23236 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23237 // value to the correct fpstack register class.
23238 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23239 return std::make_pair(0U, &X86::RFP32RegClass);
23240 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23241 return std::make_pair(0U, &X86::RFP64RegClass);
23242 return std::make_pair(0U, &X86::RFP80RegClass);
23243 case 'y': // MMX_REGS if MMX allowed.
23244 if (!Subtarget->hasMMX()) break;
23245 return std::make_pair(0U, &X86::VR64RegClass);
23246 case 'Y': // SSE_REGS if SSE2 allowed
23247 if (!Subtarget->hasSSE2()) break;
23249 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23250 if (!Subtarget->hasSSE1()) break;
23252 switch (VT.SimpleTy) {
23254 // Scalar SSE types.
23257 return std::make_pair(0U, &X86::FR32RegClass);
23260 return std::make_pair(0U, &X86::FR64RegClass);
23268 return std::make_pair(0U, &X86::VR128RegClass);
23276 return std::make_pair(0U, &X86::VR256RegClass);
23281 return std::make_pair(0U, &X86::VR512RegClass);
23287 // Use the default implementation in TargetLowering to convert the register
23288 // constraint into a member of a register class.
23289 std::pair<unsigned, const TargetRegisterClass*> Res;
23290 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23292 // Not found as a standard register?
23294 // Map st(0) -> st(7) -> ST0
23295 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23296 tolower(Constraint[1]) == 's' &&
23297 tolower(Constraint[2]) == 't' &&
23298 Constraint[3] == '(' &&
23299 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23300 Constraint[5] == ')' &&
23301 Constraint[6] == '}') {
23303 Res.first = X86::FP0+Constraint[4]-'0';
23304 Res.second = &X86::RFP80RegClass;
23308 // GCC allows "st(0)" to be called just plain "st".
23309 if (StringRef("{st}").equals_lower(Constraint)) {
23310 Res.first = X86::FP0;
23311 Res.second = &X86::RFP80RegClass;
23316 if (StringRef("{flags}").equals_lower(Constraint)) {
23317 Res.first = X86::EFLAGS;
23318 Res.second = &X86::CCRRegClass;
23322 // 'A' means EAX + EDX.
23323 if (Constraint == "A") {
23324 Res.first = X86::EAX;
23325 Res.second = &X86::GR32_ADRegClass;
23331 // Otherwise, check to see if this is a register class of the wrong value
23332 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23333 // turn into {ax},{dx}.
23334 if (Res.second->hasType(VT))
23335 return Res; // Correct type already, nothing to do.
23337 // All of the single-register GCC register classes map their values onto
23338 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23339 // really want an 8-bit or 32-bit register, map to the appropriate register
23340 // class and return the appropriate register.
23341 if (Res.second == &X86::GR16RegClass) {
23342 if (VT == MVT::i8 || VT == MVT::i1) {
23343 unsigned DestReg = 0;
23344 switch (Res.first) {
23346 case X86::AX: DestReg = X86::AL; break;
23347 case X86::DX: DestReg = X86::DL; break;
23348 case X86::CX: DestReg = X86::CL; break;
23349 case X86::BX: DestReg = X86::BL; break;
23352 Res.first = DestReg;
23353 Res.second = &X86::GR8RegClass;
23355 } else if (VT == MVT::i32 || VT == MVT::f32) {
23356 unsigned DestReg = 0;
23357 switch (Res.first) {
23359 case X86::AX: DestReg = X86::EAX; break;
23360 case X86::DX: DestReg = X86::EDX; break;
23361 case X86::CX: DestReg = X86::ECX; break;
23362 case X86::BX: DestReg = X86::EBX; break;
23363 case X86::SI: DestReg = X86::ESI; break;
23364 case X86::DI: DestReg = X86::EDI; break;
23365 case X86::BP: DestReg = X86::EBP; break;
23366 case X86::SP: DestReg = X86::ESP; break;
23369 Res.first = DestReg;
23370 Res.second = &X86::GR32RegClass;
23372 } else if (VT == MVT::i64 || VT == MVT::f64) {
23373 unsigned DestReg = 0;
23374 switch (Res.first) {
23376 case X86::AX: DestReg = X86::RAX; break;
23377 case X86::DX: DestReg = X86::RDX; break;
23378 case X86::CX: DestReg = X86::RCX; break;
23379 case X86::BX: DestReg = X86::RBX; break;
23380 case X86::SI: DestReg = X86::RSI; break;
23381 case X86::DI: DestReg = X86::RDI; break;
23382 case X86::BP: DestReg = X86::RBP; break;
23383 case X86::SP: DestReg = X86::RSP; break;
23386 Res.first = DestReg;
23387 Res.second = &X86::GR64RegClass;
23390 } else if (Res.second == &X86::FR32RegClass ||
23391 Res.second == &X86::FR64RegClass ||
23392 Res.second == &X86::VR128RegClass ||
23393 Res.second == &X86::VR256RegClass ||
23394 Res.second == &X86::FR32XRegClass ||
23395 Res.second == &X86::FR64XRegClass ||
23396 Res.second == &X86::VR128XRegClass ||
23397 Res.second == &X86::VR256XRegClass ||
23398 Res.second == &X86::VR512RegClass) {
23399 // Handle references to XMM physical registers that got mapped into the
23400 // wrong class. This can happen with constraints like {xmm0} where the
23401 // target independent register mapper will just pick the first match it can
23402 // find, ignoring the required type.
23404 if (VT == MVT::f32 || VT == MVT::i32)
23405 Res.second = &X86::FR32RegClass;
23406 else if (VT == MVT::f64 || VT == MVT::i64)
23407 Res.second = &X86::FR64RegClass;
23408 else if (X86::VR128RegClass.hasType(VT))
23409 Res.second = &X86::VR128RegClass;
23410 else if (X86::VR256RegClass.hasType(VT))
23411 Res.second = &X86::VR256RegClass;
23412 else if (X86::VR512RegClass.hasType(VT))
23413 Res.second = &X86::VR512RegClass;
23419 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23421 // Scaling factors are not free at all.
23422 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23423 // will take 2 allocations in the out of order engine instead of 1
23424 // for plain addressing mode, i.e. inst (reg1).
23426 // vaddps (%rsi,%drx), %ymm0, %ymm1
23427 // Requires two allocations (one for the load, one for the computation)
23429 // vaddps (%rsi), %ymm0, %ymm1
23430 // Requires just 1 allocation, i.e., freeing allocations for other operations
23431 // and having less micro operations to execute.
23433 // For some X86 architectures, this is even worse because for instance for
23434 // stores, the complex addressing mode forces the instruction to use the
23435 // "load" ports instead of the dedicated "store" port.
23436 // E.g., on Haswell:
23437 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23438 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23439 if (isLegalAddressingMode(AM, Ty))
23440 // Scale represents reg2 * scale, thus account for 1
23441 // as soon as we use a second register.
23442 return AM.Scale != 0;
23446 bool X86TargetLowering::isTargetFTOL() const {
23447 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();