1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62 "x86-experimental-vector-widening-legalization", cl::init(false),
63 cl::desc("Enable an experimental vector type legalization through widening "
64 "rather than promotion."),
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68 "x86-experimental-vector-shuffle-lowering", cl::init(false),
69 cl::desc("Enable an experimental vector shuffle lowering code path."),
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77 SelectionDAG &DAG, SDLoc dl,
78 unsigned vectorWidth) {
79 assert((vectorWidth == 128 || vectorWidth == 256) &&
80 "Unsupported vector width");
81 EVT VT = Vec.getValueType();
82 EVT ElVT = VT.getVectorElementType();
83 unsigned Factor = VT.getSizeInBits()/vectorWidth;
84 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85 VT.getVectorNumElements()/Factor);
87 // Extract from UNDEF is UNDEF.
88 if (Vec.getOpcode() == ISD::UNDEF)
89 return DAG.getUNDEF(ResultVT);
91 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
92 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94 // This is the index of the first element of the vectorWidth-bit chunk
96 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99 // If the input is a buildvector just emit a smaller one.
100 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit bounday. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163 unsigned IdxVal, SelectionDAG &DAG,
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170 unsigned IdxVal, SelectionDAG &DAG,
172 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181 unsigned NumElems, SelectionDAG &DAG,
183 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188 unsigned NumElems, SelectionDAG &DAG,
190 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195 if (TT.isOSBinFormatMachO()) {
196 if (TT.getArch() == Triple::x86_64)
197 return new X86_64MachoTargetObjectFile();
198 return new TargetLoweringObjectFileMachO();
202 return new X86LinuxTargetObjectFile();
203 if (TT.isOSBinFormatELF())
204 return new TargetLoweringObjectFileELF();
205 if (TT.isKnownWindowsMSVCEnvironment())
206 return new X86WindowsTargetObjectFile();
207 if (TT.isOSBinFormatCOFF())
208 return new TargetLoweringObjectFileCOFF();
209 llvm_unreachable("unknown subtarget type");
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216 Subtarget = &TM.getSubtarget<X86Subtarget>();
217 X86ScalarSSEf64 = Subtarget->hasSSE2();
218 X86ScalarSSEf32 = Subtarget->hasSSE1();
219 TD = getDataLayout();
221 resetOperationActions();
224 void X86TargetLowering::resetOperationActions() {
225 const TargetMachine &TM = getTargetMachine();
226 static bool FirstTimeThrough = true;
228 // If none of the target options have changed, then we don't need to reset the
229 // operation actions.
230 if (!FirstTimeThrough && TO == TM.Options) return;
232 if (!FirstTimeThrough) {
233 // Reinitialize the actions.
235 FirstTimeThrough = false;
240 // Set up the TargetLowering object.
241 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243 // X86 is weird, it always uses i8 for shift amounts and setcc results.
244 setBooleanContents(ZeroOrOneBooleanContent);
245 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 // For 64-bit since we have so many registers use the ILP scheduler, for
249 // 32-bit code use the register pressure specific scheduling.
250 // For Atom, always use ILP scheduling.
251 if (Subtarget->isAtom())
252 setSchedulingPreference(Sched::ILP);
253 else if (Subtarget->is64Bit())
254 setSchedulingPreference(Sched::ILP);
256 setSchedulingPreference(Sched::RegPressure);
257 const X86RegisterInfo *RegInfo =
258 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261 // Bypass expensive divides on Atom when compiling with O2
262 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263 addBypassSlowDiv(32, 8);
264 if (Subtarget->is64Bit())
265 addBypassSlowDiv(64, 16);
268 if (Subtarget->isTargetKnownWindowsMSVC()) {
269 // Setup Windows compiler runtime calls.
270 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272 setLibcallName(RTLIB::SREM_I64, "_allrem");
273 setLibcallName(RTLIB::UREM_I64, "_aullrem");
274 setLibcallName(RTLIB::MUL_I64, "_allmul");
275 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281 // The _ftol2 runtime function has an unusual calling conv, which
282 // is modeled by a special pseudo-instruction.
283 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289 if (Subtarget->isTargetDarwin()) {
290 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291 setUseUnderscoreSetJmp(false);
292 setUseUnderscoreLongJmp(false);
293 } else if (Subtarget->isTargetWindowsGNU()) {
294 // MS runtime is weird: it exports _setjmp, but longjmp!
295 setUseUnderscoreSetJmp(true);
296 setUseUnderscoreLongJmp(false);
298 setUseUnderscoreSetJmp(true);
299 setUseUnderscoreLongJmp(true);
302 // Set up the register classes.
303 addRegisterClass(MVT::i8, &X86::GR8RegClass);
304 addRegisterClass(MVT::i16, &X86::GR16RegClass);
305 addRegisterClass(MVT::i32, &X86::GR32RegClass);
306 if (Subtarget->is64Bit())
307 addRegisterClass(MVT::i64, &X86::GR64RegClass);
309 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311 // We don't accept any truncstore of integer registers.
312 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
319 // SETOEQ and SETUNE require checking two conditions.
320 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
330 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
336 } else if (!TM.Options.UseSoftFloat) {
337 // We have an algorithm for SSE2->double, and we turn this into a
338 // 64-bit FILD followed by conditional FADD for other targets.
339 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
340 // We have an algorithm for SSE2, and we turn this into a 64-bit
341 // FILD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
345 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
350 if (!TM.Options.UseSoftFloat) {
351 // SSE has no i16 to fp conversion, only i32
352 if (X86ScalarSSEf32) {
353 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
354 // f32 and f64 cases are Legal, f80 case is not
355 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
357 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
365 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
366 // are Legal, f80 is custom lowered.
367 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
368 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
370 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
375 if (X86ScalarSSEf32) {
376 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
377 // f32 and f64 cases are Legal, f80 case is not
378 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
380 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
384 // Handle FP_TO_UINT by promoting the destination to a larger signed
386 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
387 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
390 if (Subtarget->is64Bit()) {
391 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
393 } else if (!TM.Options.UseSoftFloat) {
394 // Since AVX is a superset of SSE3, only check for SSE here.
395 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396 // Expand FP_TO_UINT into a select.
397 // FIXME: We would like to use a Custom expander here eventually to do
398 // the optimal thing for SSE vs. the default expansion in the legalizer.
399 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
401 // With SSE3 we can use fisttpll to convert to a signed i64; without
402 // SSE, we're stuck with a fistpll.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
406 if (isTargetFTOL()) {
407 // Use the _ftol2 runtime function, which has a pseudo-instruction
408 // to handle its weird calling convention.
409 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
412 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413 if (!X86ScalarSSEf64) {
414 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
415 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
418 // Without SSE, i64->f64 goes through memory.
419 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
423 // Scalar integer divide and remainder are lowered to use operations that
424 // produce two results, to match the available instructions. This exposes
425 // the two-result form to trivial CSE, which is able to combine x/y and x%y
426 // into a single instruction.
428 // Scalar integer multiply-high is also lowered to use two-result
429 // operations, to match the available instructions. However, plain multiply
430 // (low) operations are left as Legal, as there are single-result
431 // instructions for this in x86. Using the two-result multiply instructions
432 // when both high and low results are needed must be arranged by dagcombine.
433 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435 setOperationAction(ISD::MULHS, VT, Expand);
436 setOperationAction(ISD::MULHU, VT, Expand);
437 setOperationAction(ISD::SDIV, VT, Expand);
438 setOperationAction(ISD::UDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UREM, VT, Expand);
442 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443 setOperationAction(ISD::ADDC, VT, Custom);
444 setOperationAction(ISD::ADDE, VT, Custom);
445 setOperationAction(ISD::SUBC, VT, Custom);
446 setOperationAction(ISD::SUBE, VT, Custom);
449 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
450 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
451 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
452 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
454 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
470 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
471 setOperationAction(ISD::FREM , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f64 , Expand);
473 setOperationAction(ISD::FREM , MVT::f80 , Expand);
474 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
476 // Promote the i8 variants and force them on up to i32 which has a shorter
478 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
482 if (Subtarget->hasBMI()) {
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
494 if (Subtarget->hasLZCNT()) {
495 // When promoting the i8 variants, force them to i32 for a shorter
497 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
498 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
500 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
507 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
512 if (Subtarget->is64Bit()) {
513 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518 // Special handling for half-precision floating point conversions.
519 // If we don't have F16C support, then lower half float conversions
520 // into library calls.
521 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
523 setOperationAction(ISD::FP32_TO_FP16, MVT::i16, Expand);
526 if (Subtarget->hasPOPCNT()) {
527 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
529 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
530 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
531 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
532 if (Subtarget->is64Bit())
533 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
536 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
538 if (!Subtarget->hasMOVBE())
539 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
541 // These should be promoted to a larger select which is supported.
542 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
543 // X86 wants to expand cmov itself.
544 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
545 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
546 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
547 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
548 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
549 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
550 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
551 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
552 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
553 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
554 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
555 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
556 if (Subtarget->is64Bit()) {
557 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
558 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
560 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
561 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
562 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
563 // support continuation, user-level threading, and etc.. As a result, no
564 // other SjLj exception interfaces are implemented and please don't build
565 // your own exception handling based on them.
566 // LLVM/Clang supports zero-cost DWARF exception handling.
567 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
568 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
571 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
572 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
573 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
574 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
575 if (Subtarget->is64Bit())
576 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
578 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
579 if (Subtarget->is64Bit()) {
580 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
581 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
582 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
583 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
584 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
586 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
587 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
588 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
589 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
590 if (Subtarget->is64Bit()) {
591 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
592 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
593 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
596 if (Subtarget->hasSSE1())
597 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
599 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
601 // Expand certain atomics
602 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
604 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
605 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
606 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
609 if (Subtarget->hasCmpxchg16b()) {
610 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
613 // FIXME - use subtarget debug flags
614 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
615 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
616 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
619 if (Subtarget->is64Bit()) {
620 setExceptionPointerRegister(X86::RAX);
621 setExceptionSelectorRegister(X86::RDX);
623 setExceptionPointerRegister(X86::EAX);
624 setExceptionSelectorRegister(X86::EDX);
626 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
627 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
629 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
630 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
632 setOperationAction(ISD::TRAP, MVT::Other, Legal);
633 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
635 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
636 setOperationAction(ISD::VASTART , MVT::Other, Custom);
637 setOperationAction(ISD::VAEND , MVT::Other, Expand);
638 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
639 // TargetInfo::X86_64ABIBuiltinVaList
640 setOperationAction(ISD::VAARG , MVT::Other, Custom);
641 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
643 // TargetInfo::CharPtrBuiltinVaList
644 setOperationAction(ISD::VAARG , MVT::Other, Expand);
645 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
648 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
649 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
651 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
652 MVT::i64 : MVT::i32, Custom);
654 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
655 // f32 and f64 use SSE.
656 // Set up the FP register classes.
657 addRegisterClass(MVT::f32, &X86::FR32RegClass);
658 addRegisterClass(MVT::f64, &X86::FR64RegClass);
660 // Use ANDPD to simulate FABS.
661 setOperationAction(ISD::FABS , MVT::f64, Custom);
662 setOperationAction(ISD::FABS , MVT::f32, Custom);
664 // Use XORP to simulate FNEG.
665 setOperationAction(ISD::FNEG , MVT::f64, Custom);
666 setOperationAction(ISD::FNEG , MVT::f32, Custom);
668 // Use ANDPD and ORPD to simulate FCOPYSIGN.
669 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
670 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
672 // Lower this to FGETSIGNx86 plus an AND.
673 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
674 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
676 // We don't support sin/cos/fmod
677 setOperationAction(ISD::FSIN , MVT::f64, Expand);
678 setOperationAction(ISD::FCOS , MVT::f64, Expand);
679 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
680 setOperationAction(ISD::FSIN , MVT::f32, Expand);
681 setOperationAction(ISD::FCOS , MVT::f32, Expand);
682 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
684 // Expand FP immediates into loads from the stack, except for the special
686 addLegalFPImmediate(APFloat(+0.0)); // xorpd
687 addLegalFPImmediate(APFloat(+0.0f)); // xorps
688 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
689 // Use SSE for f32, x87 for f64.
690 // Set up the FP register classes.
691 addRegisterClass(MVT::f32, &X86::FR32RegClass);
692 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
694 // Use ANDPS to simulate FABS.
695 setOperationAction(ISD::FABS , MVT::f32, Custom);
697 // Use XORP to simulate FNEG.
698 setOperationAction(ISD::FNEG , MVT::f32, Custom);
700 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
702 // Use ANDPS and ORPS to simulate FCOPYSIGN.
703 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
704 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
706 // We don't support sin/cos/fmod
707 setOperationAction(ISD::FSIN , MVT::f32, Expand);
708 setOperationAction(ISD::FCOS , MVT::f32, Expand);
709 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
711 // Special cases we handle for FP constants.
712 addLegalFPImmediate(APFloat(+0.0f)); // xorps
713 addLegalFPImmediate(APFloat(+0.0)); // FLD0
714 addLegalFPImmediate(APFloat(+1.0)); // FLD1
715 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
716 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
718 if (!TM.Options.UnsafeFPMath) {
719 setOperationAction(ISD::FSIN , MVT::f64, Expand);
720 setOperationAction(ISD::FCOS , MVT::f64, Expand);
721 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
723 } else if (!TM.Options.UseSoftFloat) {
724 // f32 and f64 in x87.
725 // Set up the FP register classes.
726 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
727 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
729 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
730 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
731 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
732 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
734 if (!TM.Options.UnsafeFPMath) {
735 setOperationAction(ISD::FSIN , MVT::f64, Expand);
736 setOperationAction(ISD::FSIN , MVT::f32, Expand);
737 setOperationAction(ISD::FCOS , MVT::f64, Expand);
738 setOperationAction(ISD::FCOS , MVT::f32, Expand);
739 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
740 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
742 addLegalFPImmediate(APFloat(+0.0)); // FLD0
743 addLegalFPImmediate(APFloat(+1.0)); // FLD1
744 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
745 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
746 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
747 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
748 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
749 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
752 // We don't support FMA.
753 setOperationAction(ISD::FMA, MVT::f64, Expand);
754 setOperationAction(ISD::FMA, MVT::f32, Expand);
756 // Long double always uses X87.
757 if (!TM.Options.UseSoftFloat) {
758 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
759 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
760 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
762 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
763 addLegalFPImmediate(TmpFlt); // FLD0
765 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
768 APFloat TmpFlt2(+1.0);
769 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
771 addLegalFPImmediate(TmpFlt2); // FLD1
772 TmpFlt2.changeSign();
773 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
776 if (!TM.Options.UnsafeFPMath) {
777 setOperationAction(ISD::FSIN , MVT::f80, Expand);
778 setOperationAction(ISD::FCOS , MVT::f80, Expand);
779 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
782 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
783 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
784 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
785 setOperationAction(ISD::FRINT, MVT::f80, Expand);
786 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
787 setOperationAction(ISD::FMA, MVT::f80, Expand);
790 // Always use a library call for pow.
791 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
792 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
793 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
795 setOperationAction(ISD::FLOG, MVT::f80, Expand);
796 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
797 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
798 setOperationAction(ISD::FEXP, MVT::f80, Expand);
799 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
801 // First set operation action for all vector types to either promote
802 // (for widening) or expand (for scalarization). Then we will selectively
803 // turn on ones that can be effectively codegen'd.
804 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806 MVT VT = (MVT::SimpleValueType)i;
807 setOperationAction(ISD::ADD , VT, Expand);
808 setOperationAction(ISD::SUB , VT, Expand);
809 setOperationAction(ISD::FADD, VT, Expand);
810 setOperationAction(ISD::FNEG, VT, Expand);
811 setOperationAction(ISD::FSUB, VT, Expand);
812 setOperationAction(ISD::MUL , VT, Expand);
813 setOperationAction(ISD::FMUL, VT, Expand);
814 setOperationAction(ISD::SDIV, VT, Expand);
815 setOperationAction(ISD::UDIV, VT, Expand);
816 setOperationAction(ISD::FDIV, VT, Expand);
817 setOperationAction(ISD::SREM, VT, Expand);
818 setOperationAction(ISD::UREM, VT, Expand);
819 setOperationAction(ISD::LOAD, VT, Expand);
820 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825 setOperationAction(ISD::FABS, VT, Expand);
826 setOperationAction(ISD::FSIN, VT, Expand);
827 setOperationAction(ISD::FSINCOS, VT, Expand);
828 setOperationAction(ISD::FCOS, VT, Expand);
829 setOperationAction(ISD::FSINCOS, VT, Expand);
830 setOperationAction(ISD::FREM, VT, Expand);
831 setOperationAction(ISD::FMA, VT, Expand);
832 setOperationAction(ISD::FPOWI, VT, Expand);
833 setOperationAction(ISD::FSQRT, VT, Expand);
834 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835 setOperationAction(ISD::FFLOOR, VT, Expand);
836 setOperationAction(ISD::FCEIL, VT, Expand);
837 setOperationAction(ISD::FTRUNC, VT, Expand);
838 setOperationAction(ISD::FRINT, VT, Expand);
839 setOperationAction(ISD::FNEARBYINT, VT, Expand);
840 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841 setOperationAction(ISD::MULHS, VT, Expand);
842 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843 setOperationAction(ISD::MULHU, VT, Expand);
844 setOperationAction(ISD::SDIVREM, VT, Expand);
845 setOperationAction(ISD::UDIVREM, VT, Expand);
846 setOperationAction(ISD::FPOW, VT, Expand);
847 setOperationAction(ISD::CTPOP, VT, Expand);
848 setOperationAction(ISD::CTTZ, VT, Expand);
849 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850 setOperationAction(ISD::CTLZ, VT, Expand);
851 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852 setOperationAction(ISD::SHL, VT, Expand);
853 setOperationAction(ISD::SRA, VT, Expand);
854 setOperationAction(ISD::SRL, VT, Expand);
855 setOperationAction(ISD::ROTL, VT, Expand);
856 setOperationAction(ISD::ROTR, VT, Expand);
857 setOperationAction(ISD::BSWAP, VT, Expand);
858 setOperationAction(ISD::SETCC, VT, Expand);
859 setOperationAction(ISD::FLOG, VT, Expand);
860 setOperationAction(ISD::FLOG2, VT, Expand);
861 setOperationAction(ISD::FLOG10, VT, Expand);
862 setOperationAction(ISD::FEXP, VT, Expand);
863 setOperationAction(ISD::FEXP2, VT, Expand);
864 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869 setOperationAction(ISD::TRUNCATE, VT, Expand);
870 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
873 setOperationAction(ISD::VSELECT, VT, Expand);
874 setOperationAction(ISD::SELECT_CC, VT, Expand);
875 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
876 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
877 setTruncStoreAction(VT,
878 (MVT::SimpleValueType)InnerVT, Expand);
879 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
880 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
881 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
884 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
885 // with -msoft-float, disable use of MMX as well.
886 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
887 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
888 // No operations on x86mmx supported, everything uses intrinsics.
891 // MMX-sized vectors (other than x86mmx) are expected to be expanded
892 // into smaller operations.
893 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
894 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
895 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
896 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
897 setOperationAction(ISD::AND, MVT::v8i8, Expand);
898 setOperationAction(ISD::AND, MVT::v4i16, Expand);
899 setOperationAction(ISD::AND, MVT::v2i32, Expand);
900 setOperationAction(ISD::AND, MVT::v1i64, Expand);
901 setOperationAction(ISD::OR, MVT::v8i8, Expand);
902 setOperationAction(ISD::OR, MVT::v4i16, Expand);
903 setOperationAction(ISD::OR, MVT::v2i32, Expand);
904 setOperationAction(ISD::OR, MVT::v1i64, Expand);
905 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
906 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
907 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
908 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
909 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
911 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
913 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
914 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
915 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
916 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
917 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
918 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
919 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
920 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
921 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
923 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
924 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
926 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
927 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
928 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
929 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
930 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
931 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
932 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
933 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
934 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
935 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
937 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
940 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
941 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
943 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
944 // registers cannot be used even for integer operations.
945 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
946 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
947 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
948 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
950 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
951 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
952 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
953 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
954 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
955 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
956 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
957 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
958 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
959 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
960 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
961 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
962 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
963 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
964 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
965 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
966 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
967 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
968 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
969 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
970 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
971 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
973 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
974 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
975 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
976 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
978 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
979 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
980 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
981 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
982 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
984 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
985 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
986 MVT VT = (MVT::SimpleValueType)i;
987 // Do not attempt to custom lower non-power-of-2 vectors
988 if (!isPowerOf2_32(VT.getVectorNumElements()))
990 // Do not attempt to custom lower non-128-bit vectors
991 if (!VT.is128BitVector())
993 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
994 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
998 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
999 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1000 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1001 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1002 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1003 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1005 if (Subtarget->is64Bit()) {
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1007 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1011 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1012 MVT VT = (MVT::SimpleValueType)i;
1014 // Do not attempt to promote non-128-bit vectors
1015 if (!VT.is128BitVector())
1018 setOperationAction(ISD::AND, VT, Promote);
1019 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1020 setOperationAction(ISD::OR, VT, Promote);
1021 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1022 setOperationAction(ISD::XOR, VT, Promote);
1023 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1024 setOperationAction(ISD::LOAD, VT, Promote);
1025 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1026 setOperationAction(ISD::SELECT, VT, Promote);
1027 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1030 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1032 // Custom lower v2i64 and v2f64 selects.
1033 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1034 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1035 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1036 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1038 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1039 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1041 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1042 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1043 // As there is no 64-bit GPR available, we need build a special custom
1044 // sequence to convert from v2i32 to v2f32.
1045 if (!Subtarget->is64Bit())
1046 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1048 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1049 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1051 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1053 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1054 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1055 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1058 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1059 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1060 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1061 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1062 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1063 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1064 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1065 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1066 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1067 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1068 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1070 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1071 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1072 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1073 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1074 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1075 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1076 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1077 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1078 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1079 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1081 // FIXME: Do we need to handle scalar-to-vector here?
1082 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1084 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1085 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1086 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1087 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1088 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1089 // There is no BLENDI for byte vectors. We don't need to custom lower
1090 // some vselects for now.
1091 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1093 // i8 and i16 vectors are custom , because the source register and source
1094 // source memory operand types are not the same width. f32 vectors are
1095 // custom since the immediate controlling the insert encodes additional
1097 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1098 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1099 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1100 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1105 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1107 // FIXME: these should be Legal but thats only for the case where
1108 // the index is constant. For now custom expand to deal with that.
1109 if (Subtarget->is64Bit()) {
1110 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1111 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1115 if (Subtarget->hasSSE2()) {
1116 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1117 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1119 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1120 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1122 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1123 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1125 // In the customized shift lowering, the legal cases in AVX2 will be
1127 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1128 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1130 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1131 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1133 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1136 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1137 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1138 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1139 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1140 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1141 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1142 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1144 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1145 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1146 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1148 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1149 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1152 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1153 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1154 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1155 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1156 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1157 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1158 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1159 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1161 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1162 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1165 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1167 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1168 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1169 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1170 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1171 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1172 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1174 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1175 // even though v8i16 is a legal type.
1176 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1177 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1178 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1180 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1181 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1182 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1184 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1185 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1187 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1189 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1190 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1193 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1195 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1196 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1198 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1199 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1200 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1201 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1203 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1204 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1205 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1207 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1208 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1209 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1210 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1212 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1213 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1214 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1215 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1216 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1217 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1218 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1219 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1220 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1221 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1222 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1223 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1225 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1226 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1227 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1228 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1229 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1230 setOperationAction(ISD::FMA, MVT::f32, Legal);
1231 setOperationAction(ISD::FMA, MVT::f64, Legal);
1234 if (Subtarget->hasInt256()) {
1235 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1236 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1237 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1238 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1240 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1241 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1242 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1243 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1245 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1246 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1247 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1248 // Don't lower v32i8 because there is no 128-bit byte mul
1250 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1252 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1253 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1255 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1256 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1258 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1259 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1260 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1261 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1263 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1264 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1265 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1266 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1268 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1269 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1270 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1271 // Don't lower v32i8 because there is no 128-bit byte mul
1274 // In the customized shift lowering, the legal cases in AVX2 will be
1276 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1277 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1279 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1280 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1282 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1284 // Custom lower several nodes for 256-bit types.
1285 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1286 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1287 MVT VT = (MVT::SimpleValueType)i;
1289 // Extract subvector is special because the value type
1290 // (result) is 128-bit but the source is 256-bit wide.
1291 if (VT.is128BitVector())
1292 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1294 // Do not attempt to custom lower other non-256-bit vectors
1295 if (!VT.is256BitVector())
1298 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1299 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1300 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1301 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1302 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1303 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1304 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1307 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1308 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1309 MVT VT = (MVT::SimpleValueType)i;
1311 // Do not attempt to promote non-256-bit vectors
1312 if (!VT.is256BitVector())
1315 setOperationAction(ISD::AND, VT, Promote);
1316 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1317 setOperationAction(ISD::OR, VT, Promote);
1318 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1319 setOperationAction(ISD::XOR, VT, Promote);
1320 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1321 setOperationAction(ISD::LOAD, VT, Promote);
1322 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1323 setOperationAction(ISD::SELECT, VT, Promote);
1324 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1328 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1329 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1330 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1331 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1332 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1334 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1335 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1336 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1338 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1339 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1340 setOperationAction(ISD::XOR, MVT::i1, Legal);
1341 setOperationAction(ISD::OR, MVT::i1, Legal);
1342 setOperationAction(ISD::AND, MVT::i1, Legal);
1343 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1344 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1345 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1346 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1348 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1350 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1351 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1357 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1358 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1360 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1363 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1364 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1366 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1367 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1368 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1370 if (Subtarget->is64Bit()) {
1371 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1372 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1373 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1374 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1376 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1377 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1378 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1379 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1380 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1381 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1382 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1384 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1385 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1387 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1388 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1389 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1390 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1391 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1392 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1393 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1394 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1395 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1396 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1397 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1398 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1399 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1401 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1402 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1403 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1404 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1405 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1406 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1408 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1409 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1411 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1413 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1414 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1415 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1416 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1417 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1418 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1419 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1420 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1423 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1424 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1426 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1427 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1429 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1431 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1432 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1434 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1435 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1437 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1438 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1440 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1441 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1442 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1443 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1444 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1445 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1447 if (Subtarget->hasCDI()) {
1448 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1449 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1452 // Custom lower several nodes.
1453 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1454 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1455 MVT VT = (MVT::SimpleValueType)i;
1457 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1458 // Extract subvector is special because the value type
1459 // (result) is 256/128-bit but the source is 512-bit wide.
1460 if (VT.is128BitVector() || VT.is256BitVector())
1461 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1463 if (VT.getVectorElementType() == MVT::i1)
1464 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1466 // Do not attempt to custom lower other non-512-bit vectors
1467 if (!VT.is512BitVector())
1470 if ( EltSize >= 32) {
1471 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1472 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1473 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1474 setOperationAction(ISD::VSELECT, VT, Legal);
1475 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1476 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1477 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1480 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1481 MVT VT = (MVT::SimpleValueType)i;
1483 // Do not attempt to promote non-256-bit vectors
1484 if (!VT.is512BitVector())
1487 setOperationAction(ISD::SELECT, VT, Promote);
1488 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1492 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1493 // of this type with custom code.
1494 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1495 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1496 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1500 // We want to custom lower some of our intrinsics.
1501 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1502 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1503 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1504 if (!Subtarget->is64Bit())
1505 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1507 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1508 // handle type legalization for these operations here.
1510 // FIXME: We really should do custom legalization for addition and
1511 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1512 // than generic legalization for 64-bit multiplication-with-overflow, though.
1513 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1514 // Add/Sub/Mul with overflow operations are custom lowered.
1516 setOperationAction(ISD::SADDO, VT, Custom);
1517 setOperationAction(ISD::UADDO, VT, Custom);
1518 setOperationAction(ISD::SSUBO, VT, Custom);
1519 setOperationAction(ISD::USUBO, VT, Custom);
1520 setOperationAction(ISD::SMULO, VT, Custom);
1521 setOperationAction(ISD::UMULO, VT, Custom);
1524 // There are no 8-bit 3-address imul/mul instructions
1525 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1526 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1528 if (!Subtarget->is64Bit()) {
1529 // These libcalls are not available in 32-bit.
1530 setLibcallName(RTLIB::SHL_I128, nullptr);
1531 setLibcallName(RTLIB::SRL_I128, nullptr);
1532 setLibcallName(RTLIB::SRA_I128, nullptr);
1535 // Combine sin / cos into one node or libcall if possible.
1536 if (Subtarget->hasSinCos()) {
1537 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1538 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1539 if (Subtarget->isTargetDarwin()) {
1540 // For MacOSX, we don't want to the normal expansion of a libcall to
1541 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1543 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1544 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1548 if (Subtarget->isTargetWin64()) {
1549 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1550 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1551 setOperationAction(ISD::SREM, MVT::i128, Custom);
1552 setOperationAction(ISD::UREM, MVT::i128, Custom);
1553 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1554 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1557 // We have target-specific dag combine patterns for the following nodes:
1558 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1559 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1560 setTargetDAGCombine(ISD::VSELECT);
1561 setTargetDAGCombine(ISD::SELECT);
1562 setTargetDAGCombine(ISD::SHL);
1563 setTargetDAGCombine(ISD::SRA);
1564 setTargetDAGCombine(ISD::SRL);
1565 setTargetDAGCombine(ISD::OR);
1566 setTargetDAGCombine(ISD::AND);
1567 setTargetDAGCombine(ISD::ADD);
1568 setTargetDAGCombine(ISD::FADD);
1569 setTargetDAGCombine(ISD::FSUB);
1570 setTargetDAGCombine(ISD::FMA);
1571 setTargetDAGCombine(ISD::SUB);
1572 setTargetDAGCombine(ISD::LOAD);
1573 setTargetDAGCombine(ISD::STORE);
1574 setTargetDAGCombine(ISD::ZERO_EXTEND);
1575 setTargetDAGCombine(ISD::ANY_EXTEND);
1576 setTargetDAGCombine(ISD::SIGN_EXTEND);
1577 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1578 setTargetDAGCombine(ISD::TRUNCATE);
1579 setTargetDAGCombine(ISD::SINT_TO_FP);
1580 setTargetDAGCombine(ISD::SETCC);
1581 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1582 setTargetDAGCombine(ISD::BUILD_VECTOR);
1583 if (Subtarget->is64Bit())
1584 setTargetDAGCombine(ISD::MUL);
1585 setTargetDAGCombine(ISD::XOR);
1587 computeRegisterProperties();
1589 // On Darwin, -Os means optimize for size without hurting performance,
1590 // do not reduce the limit.
1591 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1592 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1593 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1594 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1595 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1596 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1597 setPrefLoopAlignment(4); // 2^4 bytes.
1599 // Predictable cmov don't hurt on atom because it's in-order.
1600 PredictableSelectIsExpensive = !Subtarget->isAtom();
1602 setPrefFunctionAlignment(4); // 2^4 bytes.
1605 TargetLoweringBase::LegalizeTypeAction
1606 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1607 if (ExperimentalVectorWideningLegalization &&
1608 VT.getVectorNumElements() != 1 &&
1609 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1610 return TypeWidenVector;
1612 return TargetLoweringBase::getPreferredVectorAction(VT);
1615 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1617 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1619 if (Subtarget->hasAVX512())
1620 switch(VT.getVectorNumElements()) {
1621 case 8: return MVT::v8i1;
1622 case 16: return MVT::v16i1;
1625 return VT.changeVectorElementTypeToInteger();
1628 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1629 /// the desired ByVal argument alignment.
1630 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1633 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1634 if (VTy->getBitWidth() == 128)
1636 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1637 unsigned EltAlign = 0;
1638 getMaxByValAlign(ATy->getElementType(), EltAlign);
1639 if (EltAlign > MaxAlign)
1640 MaxAlign = EltAlign;
1641 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1642 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1643 unsigned EltAlign = 0;
1644 getMaxByValAlign(STy->getElementType(i), EltAlign);
1645 if (EltAlign > MaxAlign)
1646 MaxAlign = EltAlign;
1653 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1654 /// function arguments in the caller parameter area. For X86, aggregates
1655 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1656 /// are at 4-byte boundaries.
1657 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1658 if (Subtarget->is64Bit()) {
1659 // Max of 8 and alignment of type.
1660 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1667 if (Subtarget->hasSSE1())
1668 getMaxByValAlign(Ty, Align);
1672 /// getOptimalMemOpType - Returns the target specific optimal type for load
1673 /// and store operations as a result of memset, memcpy, and memmove
1674 /// lowering. If DstAlign is zero that means it's safe to destination
1675 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1676 /// means there isn't a need to check it against alignment requirement,
1677 /// probably because the source does not need to be loaded. If 'IsMemset' is
1678 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1679 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1680 /// source is constant so it does not need to be loaded.
1681 /// It returns EVT::Other if the type should be determined using generic
1682 /// target-independent logic.
1684 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1685 unsigned DstAlign, unsigned SrcAlign,
1686 bool IsMemset, bool ZeroMemset,
1688 MachineFunction &MF) const {
1689 const Function *F = MF.getFunction();
1690 if ((!IsMemset || ZeroMemset) &&
1691 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1692 Attribute::NoImplicitFloat)) {
1694 (Subtarget->isUnalignedMemAccessFast() ||
1695 ((DstAlign == 0 || DstAlign >= 16) &&
1696 (SrcAlign == 0 || SrcAlign >= 16)))) {
1698 if (Subtarget->hasInt256())
1700 if (Subtarget->hasFp256())
1703 if (Subtarget->hasSSE2())
1705 if (Subtarget->hasSSE1())
1707 } else if (!MemcpyStrSrc && Size >= 8 &&
1708 !Subtarget->is64Bit() &&
1709 Subtarget->hasSSE2()) {
1710 // Do not use f64 to lower memcpy if source is string constant. It's
1711 // better to use i32 to avoid the loads.
1715 if (Subtarget->is64Bit() && Size >= 8)
1720 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1722 return X86ScalarSSEf32;
1723 else if (VT == MVT::f64)
1724 return X86ScalarSSEf64;
1729 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1733 *Fast = Subtarget->isUnalignedMemAccessFast();
1737 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1738 /// current function. The returned value is a member of the
1739 /// MachineJumpTableInfo::JTEntryKind enum.
1740 unsigned X86TargetLowering::getJumpTableEncoding() const {
1741 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1743 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1744 Subtarget->isPICStyleGOT())
1745 return MachineJumpTableInfo::EK_Custom32;
1747 // Otherwise, use the normal jump table encoding heuristics.
1748 return TargetLowering::getJumpTableEncoding();
1752 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1753 const MachineBasicBlock *MBB,
1754 unsigned uid,MCContext &Ctx) const{
1755 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1756 Subtarget->isPICStyleGOT());
1757 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1759 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1760 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1763 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1765 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1766 SelectionDAG &DAG) const {
1767 if (!Subtarget->is64Bit())
1768 // This doesn't have SDLoc associated with it, but is not really the
1769 // same as a Register.
1770 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1774 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1775 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1777 const MCExpr *X86TargetLowering::
1778 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1779 MCContext &Ctx) const {
1780 // X86-64 uses RIP relative addressing based on the jump table label.
1781 if (Subtarget->isPICStyleRIPRel())
1782 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1784 // Otherwise, the reference is relative to the PIC base.
1785 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1788 // FIXME: Why this routine is here? Move to RegInfo!
1789 std::pair<const TargetRegisterClass*, uint8_t>
1790 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1791 const TargetRegisterClass *RRC = nullptr;
1793 switch (VT.SimpleTy) {
1795 return TargetLowering::findRepresentativeClass(VT);
1796 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1797 RRC = Subtarget->is64Bit() ?
1798 (const TargetRegisterClass*)&X86::GR64RegClass :
1799 (const TargetRegisterClass*)&X86::GR32RegClass;
1802 RRC = &X86::VR64RegClass;
1804 case MVT::f32: case MVT::f64:
1805 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1806 case MVT::v4f32: case MVT::v2f64:
1807 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1809 RRC = &X86::VR128RegClass;
1812 return std::make_pair(RRC, Cost);
1815 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1816 unsigned &Offset) const {
1817 if (!Subtarget->isTargetLinux())
1820 if (Subtarget->is64Bit()) {
1821 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1823 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1835 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1836 unsigned DestAS) const {
1837 assert(SrcAS != DestAS && "Expected different address spaces!");
1839 return SrcAS < 256 && DestAS < 256;
1842 //===----------------------------------------------------------------------===//
1843 // Return Value Calling Convention Implementation
1844 //===----------------------------------------------------------------------===//
1846 #include "X86GenCallingConv.inc"
1849 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1850 MachineFunction &MF, bool isVarArg,
1851 const SmallVectorImpl<ISD::OutputArg> &Outs,
1852 LLVMContext &Context) const {
1853 SmallVector<CCValAssign, 16> RVLocs;
1854 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1856 return CCInfo.CheckReturn(Outs, RetCC_X86);
1859 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1860 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1865 X86TargetLowering::LowerReturn(SDValue Chain,
1866 CallingConv::ID CallConv, bool isVarArg,
1867 const SmallVectorImpl<ISD::OutputArg> &Outs,
1868 const SmallVectorImpl<SDValue> &OutVals,
1869 SDLoc dl, SelectionDAG &DAG) const {
1870 MachineFunction &MF = DAG.getMachineFunction();
1871 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1873 SmallVector<CCValAssign, 16> RVLocs;
1874 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1875 RVLocs, *DAG.getContext());
1876 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1879 SmallVector<SDValue, 6> RetOps;
1880 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1881 // Operand #1 = Bytes To Pop
1882 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1885 // Copy the result values into the output registers.
1886 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1887 CCValAssign &VA = RVLocs[i];
1888 assert(VA.isRegLoc() && "Can only return in registers!");
1889 SDValue ValToCopy = OutVals[i];
1890 EVT ValVT = ValToCopy.getValueType();
1892 // Promote values to the appropriate types
1893 if (VA.getLocInfo() == CCValAssign::SExt)
1894 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1895 else if (VA.getLocInfo() == CCValAssign::ZExt)
1896 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1897 else if (VA.getLocInfo() == CCValAssign::AExt)
1898 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1899 else if (VA.getLocInfo() == CCValAssign::BCvt)
1900 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1902 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1903 "Unexpected FP-extend for return value.");
1905 // If this is x86-64, and we disabled SSE, we can't return FP values,
1906 // or SSE or MMX vectors.
1907 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1908 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1909 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1910 report_fatal_error("SSE register return with SSE disabled");
1912 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1913 // llvm-gcc has never done it right and no one has noticed, so this
1914 // should be OK for now.
1915 if (ValVT == MVT::f64 &&
1916 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1917 report_fatal_error("SSE2 register return with SSE2 disabled");
1919 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1920 // the RET instruction and handled by the FP Stackifier.
1921 if (VA.getLocReg() == X86::ST0 ||
1922 VA.getLocReg() == X86::ST1) {
1923 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1924 // change the value to the FP stack register class.
1925 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1926 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1927 RetOps.push_back(ValToCopy);
1928 // Don't emit a copytoreg.
1932 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1933 // which is returned in RAX / RDX.
1934 if (Subtarget->is64Bit()) {
1935 if (ValVT == MVT::x86mmx) {
1936 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1937 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1938 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1940 // If we don't have SSE2 available, convert to v4f32 so the generated
1941 // register is legal.
1942 if (!Subtarget->hasSSE2())
1943 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1948 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1949 Flag = Chain.getValue(1);
1950 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1953 // The x86-64 ABIs require that for returning structs by value we copy
1954 // the sret argument into %rax/%eax (depending on ABI) for the return.
1955 // Win32 requires us to put the sret argument to %eax as well.
1956 // We saved the argument into a virtual register in the entry block,
1957 // so now we copy the value out and into %rax/%eax.
1958 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1959 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1960 MachineFunction &MF = DAG.getMachineFunction();
1961 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1962 unsigned Reg = FuncInfo->getSRetReturnReg();
1964 "SRetReturnReg should have been set in LowerFormalArguments().");
1965 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1968 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1969 X86::RAX : X86::EAX;
1970 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1971 Flag = Chain.getValue(1);
1973 // RAX/EAX now acts like a return value.
1974 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1977 RetOps[0] = Chain; // Update chain.
1979 // Add the flag if we have it.
1981 RetOps.push_back(Flag);
1983 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1986 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1987 if (N->getNumValues() != 1)
1989 if (!N->hasNUsesOfValue(1, 0))
1992 SDValue TCChain = Chain;
1993 SDNode *Copy = *N->use_begin();
1994 if (Copy->getOpcode() == ISD::CopyToReg) {
1995 // If the copy has a glue operand, we conservatively assume it isn't safe to
1996 // perform a tail call.
1997 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1999 TCChain = Copy->getOperand(0);
2000 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2003 bool HasRet = false;
2004 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2006 if (UI->getOpcode() != X86ISD::RET_FLAG)
2019 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2020 ISD::NodeType ExtendKind) const {
2022 // TODO: Is this also valid on 32-bit?
2023 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2024 ReturnMVT = MVT::i8;
2026 ReturnMVT = MVT::i32;
2028 MVT MinVT = getRegisterType(ReturnMVT);
2029 return VT.bitsLT(MinVT) ? MinVT : VT;
2032 /// LowerCallResult - Lower the result values of a call into the
2033 /// appropriate copies out of appropriate physical registers.
2036 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2037 CallingConv::ID CallConv, bool isVarArg,
2038 const SmallVectorImpl<ISD::InputArg> &Ins,
2039 SDLoc dl, SelectionDAG &DAG,
2040 SmallVectorImpl<SDValue> &InVals) const {
2042 // Assign locations to each value returned by this call.
2043 SmallVector<CCValAssign, 16> RVLocs;
2044 bool Is64Bit = Subtarget->is64Bit();
2045 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2046 DAG.getTarget(), RVLocs, *DAG.getContext());
2047 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2049 // Copy all of the result registers out of their specified physreg.
2050 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2051 CCValAssign &VA = RVLocs[i];
2052 EVT CopyVT = VA.getValVT();
2054 // If this is x86-64, and we disabled SSE, we can't return FP values
2055 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2056 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2057 report_fatal_error("SSE register return with SSE disabled");
2062 // If this is a call to a function that returns an fp value on the floating
2063 // point stack, we must guarantee the value is popped from the stack, so
2064 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2065 // if the return value is not used. We use the FpPOP_RETVAL instruction
2067 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2068 // If we prefer to use the value in xmm registers, copy it out as f80 and
2069 // use a truncate to move it from fp stack reg to xmm reg.
2070 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2071 SDValue Ops[] = { Chain, InFlag };
2072 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2073 MVT::Other, MVT::Glue, Ops), 1);
2074 Val = Chain.getValue(0);
2076 // Round the f80 to the right size, which also moves it to the appropriate
2078 if (CopyVT != VA.getValVT())
2079 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2080 // This truncation won't change the value.
2081 DAG.getIntPtrConstant(1));
2083 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2084 CopyVT, InFlag).getValue(1);
2085 Val = Chain.getValue(0);
2087 InFlag = Chain.getValue(2);
2088 InVals.push_back(Val);
2094 //===----------------------------------------------------------------------===//
2095 // C & StdCall & Fast Calling Convention implementation
2096 //===----------------------------------------------------------------------===//
2097 // StdCall calling convention seems to be standard for many Windows' API
2098 // routines and around. It differs from C calling convention just a little:
2099 // callee should clean up the stack, not caller. Symbols should be also
2100 // decorated in some fancy way :) It doesn't support any vector arguments.
2101 // For info on fast calling convention see Fast Calling Convention (tail call)
2102 // implementation LowerX86_32FastCCCallTo.
2104 /// CallIsStructReturn - Determines whether a call uses struct return
2106 enum StructReturnType {
2111 static StructReturnType
2112 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2114 return NotStructReturn;
2116 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2117 if (!Flags.isSRet())
2118 return NotStructReturn;
2119 if (Flags.isInReg())
2120 return RegStructReturn;
2121 return StackStructReturn;
2124 /// ArgsAreStructReturn - Determines whether a function uses struct
2125 /// return semantics.
2126 static StructReturnType
2127 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2129 return NotStructReturn;
2131 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2132 if (!Flags.isSRet())
2133 return NotStructReturn;
2134 if (Flags.isInReg())
2135 return RegStructReturn;
2136 return StackStructReturn;
2139 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2140 /// by "Src" to address "Dst" with size and alignment information specified by
2141 /// the specific parameter attribute. The copy will be passed as a byval
2142 /// function parameter.
2144 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2145 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2147 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2149 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2150 /*isVolatile*/false, /*AlwaysInline=*/true,
2151 MachinePointerInfo(), MachinePointerInfo());
2154 /// IsTailCallConvention - Return true if the calling convention is one that
2155 /// supports tail call optimization.
2156 static bool IsTailCallConvention(CallingConv::ID CC) {
2157 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2158 CC == CallingConv::HiPE);
2161 /// \brief Return true if the calling convention is a C calling convention.
2162 static bool IsCCallConvention(CallingConv::ID CC) {
2163 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2164 CC == CallingConv::X86_64_SysV);
2167 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2168 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2172 CallingConv::ID CalleeCC = CS.getCallingConv();
2173 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2179 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2180 /// a tailcall target by changing its ABI.
2181 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2182 bool GuaranteedTailCallOpt) {
2183 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2187 X86TargetLowering::LowerMemArgument(SDValue Chain,
2188 CallingConv::ID CallConv,
2189 const SmallVectorImpl<ISD::InputArg> &Ins,
2190 SDLoc dl, SelectionDAG &DAG,
2191 const CCValAssign &VA,
2192 MachineFrameInfo *MFI,
2194 // Create the nodes corresponding to a load from this parameter slot.
2195 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2196 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2197 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2198 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2201 // If value is passed by pointer we have address passed instead of the value
2203 if (VA.getLocInfo() == CCValAssign::Indirect)
2204 ValVT = VA.getLocVT();
2206 ValVT = VA.getValVT();
2208 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2209 // changed with more analysis.
2210 // In case of tail call optimization mark all arguments mutable. Since they
2211 // could be overwritten by lowering of arguments in case of a tail call.
2212 if (Flags.isByVal()) {
2213 unsigned Bytes = Flags.getByValSize();
2214 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2215 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2216 return DAG.getFrameIndex(FI, getPointerTy());
2218 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2219 VA.getLocMemOffset(), isImmutable);
2220 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2221 return DAG.getLoad(ValVT, dl, Chain, FIN,
2222 MachinePointerInfo::getFixedStack(FI),
2223 false, false, false, 0);
2228 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2229 CallingConv::ID CallConv,
2231 const SmallVectorImpl<ISD::InputArg> &Ins,
2234 SmallVectorImpl<SDValue> &InVals)
2236 MachineFunction &MF = DAG.getMachineFunction();
2237 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2239 const Function* Fn = MF.getFunction();
2240 if (Fn->hasExternalLinkage() &&
2241 Subtarget->isTargetCygMing() &&
2242 Fn->getName() == "main")
2243 FuncInfo->setForceFramePointer(true);
2245 MachineFrameInfo *MFI = MF.getFrameInfo();
2246 bool Is64Bit = Subtarget->is64Bit();
2247 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2249 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2250 "Var args not supported with calling convention fastcc, ghc or hipe");
2252 // Assign locations to all of the incoming arguments.
2253 SmallVector<CCValAssign, 16> ArgLocs;
2254 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2255 ArgLocs, *DAG.getContext());
2257 // Allocate shadow area for Win64
2259 CCInfo.AllocateStack(32, 8);
2261 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2263 unsigned LastVal = ~0U;
2265 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2266 CCValAssign &VA = ArgLocs[i];
2267 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2269 assert(VA.getValNo() != LastVal &&
2270 "Don't support value assigned to multiple locs yet");
2272 LastVal = VA.getValNo();
2274 if (VA.isRegLoc()) {
2275 EVT RegVT = VA.getLocVT();
2276 const TargetRegisterClass *RC;
2277 if (RegVT == MVT::i32)
2278 RC = &X86::GR32RegClass;
2279 else if (Is64Bit && RegVT == MVT::i64)
2280 RC = &X86::GR64RegClass;
2281 else if (RegVT == MVT::f32)
2282 RC = &X86::FR32RegClass;
2283 else if (RegVT == MVT::f64)
2284 RC = &X86::FR64RegClass;
2285 else if (RegVT.is512BitVector())
2286 RC = &X86::VR512RegClass;
2287 else if (RegVT.is256BitVector())
2288 RC = &X86::VR256RegClass;
2289 else if (RegVT.is128BitVector())
2290 RC = &X86::VR128RegClass;
2291 else if (RegVT == MVT::x86mmx)
2292 RC = &X86::VR64RegClass;
2293 else if (RegVT == MVT::i1)
2294 RC = &X86::VK1RegClass;
2295 else if (RegVT == MVT::v8i1)
2296 RC = &X86::VK8RegClass;
2297 else if (RegVT == MVT::v16i1)
2298 RC = &X86::VK16RegClass;
2300 llvm_unreachable("Unknown argument type!");
2302 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2303 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2305 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2306 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2308 if (VA.getLocInfo() == CCValAssign::SExt)
2309 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2310 DAG.getValueType(VA.getValVT()));
2311 else if (VA.getLocInfo() == CCValAssign::ZExt)
2312 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2313 DAG.getValueType(VA.getValVT()));
2314 else if (VA.getLocInfo() == CCValAssign::BCvt)
2315 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2317 if (VA.isExtInLoc()) {
2318 // Handle MMX values passed in XMM regs.
2319 if (RegVT.isVector())
2320 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2322 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2325 assert(VA.isMemLoc());
2326 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2329 // If value is passed via pointer - do a load.
2330 if (VA.getLocInfo() == CCValAssign::Indirect)
2331 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2332 MachinePointerInfo(), false, false, false, 0);
2334 InVals.push_back(ArgValue);
2337 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2338 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2339 // The x86-64 ABIs require that for returning structs by value we copy
2340 // the sret argument into %rax/%eax (depending on ABI) for the return.
2341 // Win32 requires us to put the sret argument to %eax as well.
2342 // Save the argument into a virtual register so that we can access it
2343 // from the return points.
2344 if (Ins[i].Flags.isSRet()) {
2345 unsigned Reg = FuncInfo->getSRetReturnReg();
2347 MVT PtrTy = getPointerTy();
2348 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2349 FuncInfo->setSRetReturnReg(Reg);
2351 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2352 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2358 unsigned StackSize = CCInfo.getNextStackOffset();
2359 // Align stack specially for tail calls.
2360 if (FuncIsMadeTailCallSafe(CallConv,
2361 MF.getTarget().Options.GuaranteedTailCallOpt))
2362 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2364 // If the function takes variable number of arguments, make a frame index for
2365 // the start of the first vararg value... for expansion of llvm.va_start.
2367 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2368 CallConv != CallingConv::X86_ThisCall)) {
2369 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2372 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2374 // FIXME: We should really autogenerate these arrays
2375 static const MCPhysReg GPR64ArgRegsWin64[] = {
2376 X86::RCX, X86::RDX, X86::R8, X86::R9
2378 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2379 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2381 static const MCPhysReg XMMArgRegs64Bit[] = {
2382 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2383 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2385 const MCPhysReg *GPR64ArgRegs;
2386 unsigned NumXMMRegs = 0;
2389 // The XMM registers which might contain var arg parameters are shadowed
2390 // in their paired GPR. So we only need to save the GPR to their home
2392 TotalNumIntRegs = 4;
2393 GPR64ArgRegs = GPR64ArgRegsWin64;
2395 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2396 GPR64ArgRegs = GPR64ArgRegs64Bit;
2398 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2401 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2404 bool NoImplicitFloatOps = Fn->getAttributes().
2405 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2406 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2407 "SSE register cannot be used when SSE is disabled!");
2408 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2409 NoImplicitFloatOps) &&
2410 "SSE register cannot be used when SSE is disabled!");
2411 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2412 !Subtarget->hasSSE1())
2413 // Kernel mode asks for SSE to be disabled, so don't push them
2415 TotalNumXMMRegs = 0;
2418 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2419 // Get to the caller-allocated home save location. Add 8 to account
2420 // for the return address.
2421 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2422 FuncInfo->setRegSaveFrameIndex(
2423 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2424 // Fixup to set vararg frame on shadow area (4 x i64).
2426 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2428 // For X86-64, if there are vararg parameters that are passed via
2429 // registers, then we must store them to their spots on the stack so
2430 // they may be loaded by deferencing the result of va_next.
2431 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2432 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2433 FuncInfo->setRegSaveFrameIndex(
2434 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2438 // Store the integer parameter registers.
2439 SmallVector<SDValue, 8> MemOps;
2440 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2442 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2443 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2444 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2445 DAG.getIntPtrConstant(Offset));
2446 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2447 &X86::GR64RegClass);
2448 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2450 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2451 MachinePointerInfo::getFixedStack(
2452 FuncInfo->getRegSaveFrameIndex(), Offset),
2454 MemOps.push_back(Store);
2458 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2459 // Now store the XMM (fp + vector) parameter registers.
2460 SmallVector<SDValue, 11> SaveXMMOps;
2461 SaveXMMOps.push_back(Chain);
2463 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2464 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2465 SaveXMMOps.push_back(ALVal);
2467 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2468 FuncInfo->getRegSaveFrameIndex()));
2469 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2470 FuncInfo->getVarArgsFPOffset()));
2472 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2473 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2474 &X86::VR128RegClass);
2475 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2476 SaveXMMOps.push_back(Val);
2478 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2479 MVT::Other, SaveXMMOps));
2482 if (!MemOps.empty())
2483 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2487 // Some CCs need callee pop.
2488 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2489 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2490 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2492 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2493 // If this is an sret function, the return should pop the hidden pointer.
2494 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2495 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2496 argsAreStructReturn(Ins) == StackStructReturn)
2497 FuncInfo->setBytesToPopOnReturn(4);
2501 // RegSaveFrameIndex is X86-64 only.
2502 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2503 if (CallConv == CallingConv::X86_FastCall ||
2504 CallConv == CallingConv::X86_ThisCall)
2505 // fastcc functions can't have varargs.
2506 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2509 FuncInfo->setArgumentStackSize(StackSize);
2515 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2516 SDValue StackPtr, SDValue Arg,
2517 SDLoc dl, SelectionDAG &DAG,
2518 const CCValAssign &VA,
2519 ISD::ArgFlagsTy Flags) const {
2520 unsigned LocMemOffset = VA.getLocMemOffset();
2521 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2522 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2523 if (Flags.isByVal())
2524 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2526 return DAG.getStore(Chain, dl, Arg, PtrOff,
2527 MachinePointerInfo::getStack(LocMemOffset),
2531 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2532 /// optimization is performed and it is required.
2534 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2535 SDValue &OutRetAddr, SDValue Chain,
2536 bool IsTailCall, bool Is64Bit,
2537 int FPDiff, SDLoc dl) const {
2538 // Adjust the Return address stack slot.
2539 EVT VT = getPointerTy();
2540 OutRetAddr = getReturnAddressFrameIndex(DAG);
2542 // Load the "old" Return address.
2543 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2544 false, false, false, 0);
2545 return SDValue(OutRetAddr.getNode(), 1);
2548 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2549 /// optimization is performed and it is required (FPDiff!=0).
2550 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2551 SDValue Chain, SDValue RetAddrFrIdx,
2552 EVT PtrVT, unsigned SlotSize,
2553 int FPDiff, SDLoc dl) {
2554 // Store the return address to the appropriate stack slot.
2555 if (!FPDiff) return Chain;
2556 // Calculate the new stack slot for the return address.
2557 int NewReturnAddrFI =
2558 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2560 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2561 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2562 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2568 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2569 SmallVectorImpl<SDValue> &InVals) const {
2570 SelectionDAG &DAG = CLI.DAG;
2572 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2573 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2574 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2575 SDValue Chain = CLI.Chain;
2576 SDValue Callee = CLI.Callee;
2577 CallingConv::ID CallConv = CLI.CallConv;
2578 bool &isTailCall = CLI.IsTailCall;
2579 bool isVarArg = CLI.IsVarArg;
2581 MachineFunction &MF = DAG.getMachineFunction();
2582 bool Is64Bit = Subtarget->is64Bit();
2583 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2584 StructReturnType SR = callIsStructReturn(Outs);
2585 bool IsSibcall = false;
2587 if (MF.getTarget().Options.DisableTailCalls)
2590 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2592 // Force this to be a tail call. The verifier rules are enough to ensure
2593 // that we can lower this successfully without moving the return address
2596 } else if (isTailCall) {
2597 // Check if it's really possible to do a tail call.
2598 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2599 isVarArg, SR != NotStructReturn,
2600 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2601 Outs, OutVals, Ins, DAG);
2603 // Sibcalls are automatically detected tailcalls which do not require
2605 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2612 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2613 "Var args not supported with calling convention fastcc, ghc or hipe");
2615 // Analyze operands of the call, assigning locations to each operand.
2616 SmallVector<CCValAssign, 16> ArgLocs;
2617 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2618 ArgLocs, *DAG.getContext());
2620 // Allocate shadow area for Win64
2622 CCInfo.AllocateStack(32, 8);
2624 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2626 // Get a count of how many bytes are to be pushed on the stack.
2627 unsigned NumBytes = CCInfo.getNextStackOffset();
2629 // This is a sibcall. The memory operands are available in caller's
2630 // own caller's stack.
2632 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2633 IsTailCallConvention(CallConv))
2634 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2637 if (isTailCall && !IsSibcall && !IsMustTail) {
2638 // Lower arguments at fp - stackoffset + fpdiff.
2639 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2640 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2642 FPDiff = NumBytesCallerPushed - NumBytes;
2644 // Set the delta of movement of the returnaddr stackslot.
2645 // But only set if delta is greater than previous delta.
2646 if (FPDiff < X86Info->getTCReturnAddrDelta())
2647 X86Info->setTCReturnAddrDelta(FPDiff);
2650 unsigned NumBytesToPush = NumBytes;
2651 unsigned NumBytesToPop = NumBytes;
2653 // If we have an inalloca argument, all stack space has already been allocated
2654 // for us and be right at the top of the stack. We don't support multiple
2655 // arguments passed in memory when using inalloca.
2656 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2658 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2659 "an inalloca argument must be the only memory argument");
2663 Chain = DAG.getCALLSEQ_START(
2664 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2666 SDValue RetAddrFrIdx;
2667 // Load return address for tail calls.
2668 if (isTailCall && FPDiff)
2669 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2670 Is64Bit, FPDiff, dl);
2672 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2673 SmallVector<SDValue, 8> MemOpChains;
2676 // Walk the register/memloc assignments, inserting copies/loads. In the case
2677 // of tail call optimization arguments are handle later.
2678 const X86RegisterInfo *RegInfo =
2679 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2680 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2681 // Skip inalloca arguments, they have already been written.
2682 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2683 if (Flags.isInAlloca())
2686 CCValAssign &VA = ArgLocs[i];
2687 EVT RegVT = VA.getLocVT();
2688 SDValue Arg = OutVals[i];
2689 bool isByVal = Flags.isByVal();
2691 // Promote the value if needed.
2692 switch (VA.getLocInfo()) {
2693 default: llvm_unreachable("Unknown loc info!");
2694 case CCValAssign::Full: break;
2695 case CCValAssign::SExt:
2696 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2698 case CCValAssign::ZExt:
2699 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2701 case CCValAssign::AExt:
2702 if (RegVT.is128BitVector()) {
2703 // Special case: passing MMX values in XMM registers.
2704 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2705 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2706 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2708 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2710 case CCValAssign::BCvt:
2711 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2713 case CCValAssign::Indirect: {
2714 // Store the argument.
2715 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2716 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2717 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2718 MachinePointerInfo::getFixedStack(FI),
2725 if (VA.isRegLoc()) {
2726 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2727 if (isVarArg && IsWin64) {
2728 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2729 // shadow reg if callee is a varargs function.
2730 unsigned ShadowReg = 0;
2731 switch (VA.getLocReg()) {
2732 case X86::XMM0: ShadowReg = X86::RCX; break;
2733 case X86::XMM1: ShadowReg = X86::RDX; break;
2734 case X86::XMM2: ShadowReg = X86::R8; break;
2735 case X86::XMM3: ShadowReg = X86::R9; break;
2738 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2740 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2741 assert(VA.isMemLoc());
2742 if (!StackPtr.getNode())
2743 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2745 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2746 dl, DAG, VA, Flags));
2750 if (!MemOpChains.empty())
2751 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2753 if (Subtarget->isPICStyleGOT()) {
2754 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2757 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2758 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2760 // If we are tail calling and generating PIC/GOT style code load the
2761 // address of the callee into ECX. The value in ecx is used as target of
2762 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2763 // for tail calls on PIC/GOT architectures. Normally we would just put the
2764 // address of GOT into ebx and then call target@PLT. But for tail calls
2765 // ebx would be restored (since ebx is callee saved) before jumping to the
2768 // Note: The actual moving to ECX is done further down.
2769 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2770 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2771 !G->getGlobal()->hasProtectedVisibility())
2772 Callee = LowerGlobalAddress(Callee, DAG);
2773 else if (isa<ExternalSymbolSDNode>(Callee))
2774 Callee = LowerExternalSymbol(Callee, DAG);
2778 if (Is64Bit && isVarArg && !IsWin64) {
2779 // From AMD64 ABI document:
2780 // For calls that may call functions that use varargs or stdargs
2781 // (prototype-less calls or calls to functions containing ellipsis (...) in
2782 // the declaration) %al is used as hidden argument to specify the number
2783 // of SSE registers used. The contents of %al do not need to match exactly
2784 // the number of registers, but must be an ubound on the number of SSE
2785 // registers used and is in the range 0 - 8 inclusive.
2787 // Count the number of XMM registers allocated.
2788 static const MCPhysReg XMMArgRegs[] = {
2789 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2790 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2792 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2793 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2794 && "SSE registers cannot be used when SSE is disabled");
2796 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2797 DAG.getConstant(NumXMMRegs, MVT::i8)));
2800 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2801 // don't need this because the eligibility check rejects calls that require
2802 // shuffling arguments passed in memory.
2803 if (!IsSibcall && isTailCall) {
2804 // Force all the incoming stack arguments to be loaded from the stack
2805 // before any new outgoing arguments are stored to the stack, because the
2806 // outgoing stack slots may alias the incoming argument stack slots, and
2807 // the alias isn't otherwise explicit. This is slightly more conservative
2808 // than necessary, because it means that each store effectively depends
2809 // on every argument instead of just those arguments it would clobber.
2810 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2812 SmallVector<SDValue, 8> MemOpChains2;
2815 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2816 CCValAssign &VA = ArgLocs[i];
2819 assert(VA.isMemLoc());
2820 SDValue Arg = OutVals[i];
2821 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2822 // Skip inalloca arguments. They don't require any work.
2823 if (Flags.isInAlloca())
2825 // Create frame index.
2826 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2827 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2828 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2829 FIN = DAG.getFrameIndex(FI, getPointerTy());
2831 if (Flags.isByVal()) {
2832 // Copy relative to framepointer.
2833 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2834 if (!StackPtr.getNode())
2835 StackPtr = DAG.getCopyFromReg(Chain, dl,
2836 RegInfo->getStackRegister(),
2838 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2840 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2844 // Store relative to framepointer.
2845 MemOpChains2.push_back(
2846 DAG.getStore(ArgChain, dl, Arg, FIN,
2847 MachinePointerInfo::getFixedStack(FI),
2852 if (!MemOpChains2.empty())
2853 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2855 // Store the return address to the appropriate stack slot.
2856 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2857 getPointerTy(), RegInfo->getSlotSize(),
2861 // Build a sequence of copy-to-reg nodes chained together with token chain
2862 // and flag operands which copy the outgoing args into registers.
2864 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2865 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2866 RegsToPass[i].second, InFlag);
2867 InFlag = Chain.getValue(1);
2870 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2871 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2872 // In the 64-bit large code model, we have to make all calls
2873 // through a register, since the call instruction's 32-bit
2874 // pc-relative offset may not be large enough to hold the whole
2876 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2877 // If the callee is a GlobalAddress node (quite common, every direct call
2878 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2881 // We should use extra load for direct calls to dllimported functions in
2883 const GlobalValue *GV = G->getGlobal();
2884 if (!GV->hasDLLImportStorageClass()) {
2885 unsigned char OpFlags = 0;
2886 bool ExtraLoad = false;
2887 unsigned WrapperKind = ISD::DELETED_NODE;
2889 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2890 // external symbols most go through the PLT in PIC mode. If the symbol
2891 // has hidden or protected visibility, or if it is static or local, then
2892 // we don't need to use the PLT - we can directly call it.
2893 if (Subtarget->isTargetELF() &&
2894 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2895 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2896 OpFlags = X86II::MO_PLT;
2897 } else if (Subtarget->isPICStyleStubAny() &&
2898 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2899 (!Subtarget->getTargetTriple().isMacOSX() ||
2900 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2901 // PC-relative references to external symbols should go through $stub,
2902 // unless we're building with the leopard linker or later, which
2903 // automatically synthesizes these stubs.
2904 OpFlags = X86II::MO_DARWIN_STUB;
2905 } else if (Subtarget->isPICStyleRIPRel() &&
2906 isa<Function>(GV) &&
2907 cast<Function>(GV)->getAttributes().
2908 hasAttribute(AttributeSet::FunctionIndex,
2909 Attribute::NonLazyBind)) {
2910 // If the function is marked as non-lazy, generate an indirect call
2911 // which loads from the GOT directly. This avoids runtime overhead
2912 // at the cost of eager binding (and one extra byte of encoding).
2913 OpFlags = X86II::MO_GOTPCREL;
2914 WrapperKind = X86ISD::WrapperRIP;
2918 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2919 G->getOffset(), OpFlags);
2921 // Add a wrapper if needed.
2922 if (WrapperKind != ISD::DELETED_NODE)
2923 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2924 // Add extra indirection if needed.
2926 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2927 MachinePointerInfo::getGOT(),
2928 false, false, false, 0);
2930 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2931 unsigned char OpFlags = 0;
2933 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2934 // external symbols should go through the PLT.
2935 if (Subtarget->isTargetELF() &&
2936 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2937 OpFlags = X86II::MO_PLT;
2938 } else if (Subtarget->isPICStyleStubAny() &&
2939 (!Subtarget->getTargetTriple().isMacOSX() ||
2940 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2941 // PC-relative references to external symbols should go through $stub,
2942 // unless we're building with the leopard linker or later, which
2943 // automatically synthesizes these stubs.
2944 OpFlags = X86II::MO_DARWIN_STUB;
2947 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2951 // Returns a chain & a flag for retval copy to use.
2952 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2953 SmallVector<SDValue, 8> Ops;
2955 if (!IsSibcall && isTailCall) {
2956 Chain = DAG.getCALLSEQ_END(Chain,
2957 DAG.getIntPtrConstant(NumBytesToPop, true),
2958 DAG.getIntPtrConstant(0, true), InFlag, dl);
2959 InFlag = Chain.getValue(1);
2962 Ops.push_back(Chain);
2963 Ops.push_back(Callee);
2966 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2968 // Add argument registers to the end of the list so that they are known live
2970 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2971 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2972 RegsToPass[i].second.getValueType()));
2974 // Add a register mask operand representing the call-preserved registers.
2975 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2976 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2977 assert(Mask && "Missing call preserved mask for calling convention");
2978 Ops.push_back(DAG.getRegisterMask(Mask));
2980 if (InFlag.getNode())
2981 Ops.push_back(InFlag);
2985 //// If this is the first return lowered for this function, add the regs
2986 //// to the liveout set for the function.
2987 // This isn't right, although it's probably harmless on x86; liveouts
2988 // should be computed from returns not tail calls. Consider a void
2989 // function making a tail call to a function returning int.
2990 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2993 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2994 InFlag = Chain.getValue(1);
2996 // Create the CALLSEQ_END node.
2997 unsigned NumBytesForCalleeToPop;
2998 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2999 DAG.getTarget().Options.GuaranteedTailCallOpt))
3000 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3001 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3002 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3003 SR == StackStructReturn)
3004 // If this is a call to a struct-return function, the callee
3005 // pops the hidden struct pointer, so we have to push it back.
3006 // This is common for Darwin/X86, Linux & Mingw32 targets.
3007 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3008 NumBytesForCalleeToPop = 4;
3010 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3012 // Returns a flag for retval copy to use.
3014 Chain = DAG.getCALLSEQ_END(Chain,
3015 DAG.getIntPtrConstant(NumBytesToPop, true),
3016 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3019 InFlag = Chain.getValue(1);
3022 // Handle result values, copying them out of physregs into vregs that we
3024 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3025 Ins, dl, DAG, InVals);
3028 //===----------------------------------------------------------------------===//
3029 // Fast Calling Convention (tail call) implementation
3030 //===----------------------------------------------------------------------===//
3032 // Like std call, callee cleans arguments, convention except that ECX is
3033 // reserved for storing the tail called function address. Only 2 registers are
3034 // free for argument passing (inreg). Tail call optimization is performed
3036 // * tailcallopt is enabled
3037 // * caller/callee are fastcc
3038 // On X86_64 architecture with GOT-style position independent code only local
3039 // (within module) calls are supported at the moment.
3040 // To keep the stack aligned according to platform abi the function
3041 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3042 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3043 // If a tail called function callee has more arguments than the caller the
3044 // caller needs to make sure that there is room to move the RETADDR to. This is
3045 // achieved by reserving an area the size of the argument delta right after the
3046 // original REtADDR, but before the saved framepointer or the spilled registers
3047 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3059 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3060 /// for a 16 byte align requirement.
3062 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3063 SelectionDAG& DAG) const {
3064 MachineFunction &MF = DAG.getMachineFunction();
3065 const TargetMachine &TM = MF.getTarget();
3066 const X86RegisterInfo *RegInfo =
3067 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3068 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3069 unsigned StackAlignment = TFI.getStackAlignment();
3070 uint64_t AlignMask = StackAlignment - 1;
3071 int64_t Offset = StackSize;
3072 unsigned SlotSize = RegInfo->getSlotSize();
3073 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3074 // Number smaller than 12 so just add the difference.
3075 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3077 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3078 Offset = ((~AlignMask) & Offset) + StackAlignment +
3079 (StackAlignment-SlotSize);
3084 /// MatchingStackOffset - Return true if the given stack call argument is
3085 /// already available in the same position (relatively) of the caller's
3086 /// incoming argument stack.
3088 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3089 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3090 const X86InstrInfo *TII) {
3091 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3093 if (Arg.getOpcode() == ISD::CopyFromReg) {
3094 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3095 if (!TargetRegisterInfo::isVirtualRegister(VR))
3097 MachineInstr *Def = MRI->getVRegDef(VR);
3100 if (!Flags.isByVal()) {
3101 if (!TII->isLoadFromStackSlot(Def, FI))
3104 unsigned Opcode = Def->getOpcode();
3105 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3106 Def->getOperand(1).isFI()) {
3107 FI = Def->getOperand(1).getIndex();
3108 Bytes = Flags.getByValSize();
3112 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3113 if (Flags.isByVal())
3114 // ByVal argument is passed in as a pointer but it's now being
3115 // dereferenced. e.g.
3116 // define @foo(%struct.X* %A) {
3117 // tail call @bar(%struct.X* byval %A)
3120 SDValue Ptr = Ld->getBasePtr();
3121 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3124 FI = FINode->getIndex();
3125 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3126 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3127 FI = FINode->getIndex();
3128 Bytes = Flags.getByValSize();
3132 assert(FI != INT_MAX);
3133 if (!MFI->isFixedObjectIndex(FI))
3135 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3138 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3139 /// for tail call optimization. Targets which want to do tail call
3140 /// optimization should implement this function.
3142 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3143 CallingConv::ID CalleeCC,
3145 bool isCalleeStructRet,
3146 bool isCallerStructRet,
3148 const SmallVectorImpl<ISD::OutputArg> &Outs,
3149 const SmallVectorImpl<SDValue> &OutVals,
3150 const SmallVectorImpl<ISD::InputArg> &Ins,
3151 SelectionDAG &DAG) const {
3152 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3155 // If -tailcallopt is specified, make fastcc functions tail-callable.
3156 const MachineFunction &MF = DAG.getMachineFunction();
3157 const Function *CallerF = MF.getFunction();
3159 // If the function return type is x86_fp80 and the callee return type is not,
3160 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3161 // perform a tailcall optimization here.
3162 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3165 CallingConv::ID CallerCC = CallerF->getCallingConv();
3166 bool CCMatch = CallerCC == CalleeCC;
3167 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3168 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3170 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3171 if (IsTailCallConvention(CalleeCC) && CCMatch)
3176 // Look for obvious safe cases to perform tail call optimization that do not
3177 // require ABI changes. This is what gcc calls sibcall.
3179 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3180 // emit a special epilogue.
3181 const X86RegisterInfo *RegInfo =
3182 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3183 if (RegInfo->needsStackRealignment(MF))
3186 // Also avoid sibcall optimization if either caller or callee uses struct
3187 // return semantics.
3188 if (isCalleeStructRet || isCallerStructRet)
3191 // An stdcall/thiscall caller is expected to clean up its arguments; the
3192 // callee isn't going to do that.
3193 // FIXME: this is more restrictive than needed. We could produce a tailcall
3194 // when the stack adjustment matches. For example, with a thiscall that takes
3195 // only one argument.
3196 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3197 CallerCC == CallingConv::X86_ThisCall))
3200 // Do not sibcall optimize vararg calls unless all arguments are passed via
3202 if (isVarArg && !Outs.empty()) {
3204 // Optimizing for varargs on Win64 is unlikely to be safe without
3205 // additional testing.
3206 if (IsCalleeWin64 || IsCallerWin64)
3209 SmallVector<CCValAssign, 16> ArgLocs;
3210 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3211 DAG.getTarget(), ArgLocs, *DAG.getContext());
3213 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3214 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3215 if (!ArgLocs[i].isRegLoc())
3219 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3220 // stack. Therefore, if it's not used by the call it is not safe to optimize
3221 // this into a sibcall.
3222 bool Unused = false;
3223 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3230 SmallVector<CCValAssign, 16> RVLocs;
3231 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3232 DAG.getTarget(), RVLocs, *DAG.getContext());
3233 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3234 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3235 CCValAssign &VA = RVLocs[i];
3236 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3241 // If the calling conventions do not match, then we'd better make sure the
3242 // results are returned in the same way as what the caller expects.
3244 SmallVector<CCValAssign, 16> RVLocs1;
3245 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3246 DAG.getTarget(), RVLocs1, *DAG.getContext());
3247 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3249 SmallVector<CCValAssign, 16> RVLocs2;
3250 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3251 DAG.getTarget(), RVLocs2, *DAG.getContext());
3252 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3254 if (RVLocs1.size() != RVLocs2.size())
3256 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3257 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3259 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3261 if (RVLocs1[i].isRegLoc()) {
3262 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3265 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3271 // If the callee takes no arguments then go on to check the results of the
3273 if (!Outs.empty()) {
3274 // Check if stack adjustment is needed. For now, do not do this if any
3275 // argument is passed on the stack.
3276 SmallVector<CCValAssign, 16> ArgLocs;
3277 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3278 DAG.getTarget(), ArgLocs, *DAG.getContext());
3280 // Allocate shadow area for Win64
3282 CCInfo.AllocateStack(32, 8);
3284 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3285 if (CCInfo.getNextStackOffset()) {
3286 MachineFunction &MF = DAG.getMachineFunction();
3287 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3290 // Check if the arguments are already laid out in the right way as
3291 // the caller's fixed stack objects.
3292 MachineFrameInfo *MFI = MF.getFrameInfo();
3293 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3294 const X86InstrInfo *TII =
3295 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3296 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3297 CCValAssign &VA = ArgLocs[i];
3298 SDValue Arg = OutVals[i];
3299 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3300 if (VA.getLocInfo() == CCValAssign::Indirect)
3302 if (!VA.isRegLoc()) {
3303 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3310 // If the tailcall address may be in a register, then make sure it's
3311 // possible to register allocate for it. In 32-bit, the call address can
3312 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3313 // callee-saved registers are restored. These happen to be the same
3314 // registers used to pass 'inreg' arguments so watch out for those.
3315 if (!Subtarget->is64Bit() &&
3316 ((!isa<GlobalAddressSDNode>(Callee) &&
3317 !isa<ExternalSymbolSDNode>(Callee)) ||
3318 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3319 unsigned NumInRegs = 0;
3320 // In PIC we need an extra register to formulate the address computation
3322 unsigned MaxInRegs =
3323 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3325 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3326 CCValAssign &VA = ArgLocs[i];
3329 unsigned Reg = VA.getLocReg();
3332 case X86::EAX: case X86::EDX: case X86::ECX:
3333 if (++NumInRegs == MaxInRegs)
3345 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3346 const TargetLibraryInfo *libInfo) const {
3347 return X86::createFastISel(funcInfo, libInfo);
3350 //===----------------------------------------------------------------------===//
3351 // Other Lowering Hooks
3352 //===----------------------------------------------------------------------===//
3354 static bool MayFoldLoad(SDValue Op) {
3355 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3358 static bool MayFoldIntoStore(SDValue Op) {
3359 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3362 static bool isTargetShuffle(unsigned Opcode) {
3364 default: return false;
3365 case X86ISD::PSHUFD:
3366 case X86ISD::PSHUFHW:
3367 case X86ISD::PSHUFLW:
3369 case X86ISD::PALIGNR:
3370 case X86ISD::MOVLHPS:
3371 case X86ISD::MOVLHPD:
3372 case X86ISD::MOVHLPS:
3373 case X86ISD::MOVLPS:
3374 case X86ISD::MOVLPD:
3375 case X86ISD::MOVSHDUP:
3376 case X86ISD::MOVSLDUP:
3377 case X86ISD::MOVDDUP:
3380 case X86ISD::UNPCKL:
3381 case X86ISD::UNPCKH:
3382 case X86ISD::VPERMILP:
3383 case X86ISD::VPERM2X128:
3384 case X86ISD::VPERMI:
3389 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3390 SDValue V1, SelectionDAG &DAG) {
3392 default: llvm_unreachable("Unknown x86 shuffle node");
3393 case X86ISD::MOVSHDUP:
3394 case X86ISD::MOVSLDUP:
3395 case X86ISD::MOVDDUP:
3396 return DAG.getNode(Opc, dl, VT, V1);
3400 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3401 SDValue V1, unsigned TargetMask,
3402 SelectionDAG &DAG) {
3404 default: llvm_unreachable("Unknown x86 shuffle node");
3405 case X86ISD::PSHUFD:
3406 case X86ISD::PSHUFHW:
3407 case X86ISD::PSHUFLW:
3408 case X86ISD::VPERMILP:
3409 case X86ISD::VPERMI:
3410 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3414 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3415 SDValue V1, SDValue V2, unsigned TargetMask,
3416 SelectionDAG &DAG) {
3418 default: llvm_unreachable("Unknown x86 shuffle node");
3419 case X86ISD::PALIGNR:
3421 case X86ISD::VPERM2X128:
3422 return DAG.getNode(Opc, dl, VT, V1, V2,
3423 DAG.getConstant(TargetMask, MVT::i8));
3427 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3428 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3430 default: llvm_unreachable("Unknown x86 shuffle node");
3431 case X86ISD::MOVLHPS:
3432 case X86ISD::MOVLHPD:
3433 case X86ISD::MOVHLPS:
3434 case X86ISD::MOVLPS:
3435 case X86ISD::MOVLPD:
3438 case X86ISD::UNPCKL:
3439 case X86ISD::UNPCKH:
3440 return DAG.getNode(Opc, dl, VT, V1, V2);
3444 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3445 MachineFunction &MF = DAG.getMachineFunction();
3446 const X86RegisterInfo *RegInfo =
3447 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3448 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3449 int ReturnAddrIndex = FuncInfo->getRAIndex();
3451 if (ReturnAddrIndex == 0) {
3452 // Set up a frame object for the return address.
3453 unsigned SlotSize = RegInfo->getSlotSize();
3454 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3457 FuncInfo->setRAIndex(ReturnAddrIndex);
3460 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3463 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3464 bool hasSymbolicDisplacement) {
3465 // Offset should fit into 32 bit immediate field.
3466 if (!isInt<32>(Offset))
3469 // If we don't have a symbolic displacement - we don't have any extra
3471 if (!hasSymbolicDisplacement)
3474 // FIXME: Some tweaks might be needed for medium code model.
3475 if (M != CodeModel::Small && M != CodeModel::Kernel)
3478 // For small code model we assume that latest object is 16MB before end of 31
3479 // bits boundary. We may also accept pretty large negative constants knowing
3480 // that all objects are in the positive half of address space.
3481 if (M == CodeModel::Small && Offset < 16*1024*1024)
3484 // For kernel code model we know that all object resist in the negative half
3485 // of 32bits address space. We may not accept negative offsets, since they may
3486 // be just off and we may accept pretty large positive ones.
3487 if (M == CodeModel::Kernel && Offset > 0)
3493 /// isCalleePop - Determines whether the callee is required to pop its
3494 /// own arguments. Callee pop is necessary to support tail calls.
3495 bool X86::isCalleePop(CallingConv::ID CallingConv,
3496 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3500 switch (CallingConv) {
3503 case CallingConv::X86_StdCall:
3505 case CallingConv::X86_FastCall:
3507 case CallingConv::X86_ThisCall:
3509 case CallingConv::Fast:
3511 case CallingConv::GHC:
3513 case CallingConv::HiPE:
3518 /// \brief Return true if the condition is an unsigned comparison operation.
3519 static bool isX86CCUnsigned(unsigned X86CC) {
3521 default: llvm_unreachable("Invalid integer condition!");
3522 case X86::COND_E: return true;
3523 case X86::COND_G: return false;
3524 case X86::COND_GE: return false;
3525 case X86::COND_L: return false;
3526 case X86::COND_LE: return false;
3527 case X86::COND_NE: return true;
3528 case X86::COND_B: return true;
3529 case X86::COND_A: return true;
3530 case X86::COND_BE: return true;
3531 case X86::COND_AE: return true;
3533 llvm_unreachable("covered switch fell through?!");
3536 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3537 /// specific condition code, returning the condition code and the LHS/RHS of the
3538 /// comparison to make.
3539 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3540 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3542 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3543 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3544 // X > -1 -> X == 0, jump !sign.
3545 RHS = DAG.getConstant(0, RHS.getValueType());
3546 return X86::COND_NS;
3548 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3549 // X < 0 -> X == 0, jump on sign.
3552 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3554 RHS = DAG.getConstant(0, RHS.getValueType());
3555 return X86::COND_LE;
3559 switch (SetCCOpcode) {
3560 default: llvm_unreachable("Invalid integer condition!");
3561 case ISD::SETEQ: return X86::COND_E;
3562 case ISD::SETGT: return X86::COND_G;
3563 case ISD::SETGE: return X86::COND_GE;
3564 case ISD::SETLT: return X86::COND_L;
3565 case ISD::SETLE: return X86::COND_LE;
3566 case ISD::SETNE: return X86::COND_NE;
3567 case ISD::SETULT: return X86::COND_B;
3568 case ISD::SETUGT: return X86::COND_A;
3569 case ISD::SETULE: return X86::COND_BE;
3570 case ISD::SETUGE: return X86::COND_AE;
3574 // First determine if it is required or is profitable to flip the operands.
3576 // If LHS is a foldable load, but RHS is not, flip the condition.
3577 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3578 !ISD::isNON_EXTLoad(RHS.getNode())) {
3579 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3580 std::swap(LHS, RHS);
3583 switch (SetCCOpcode) {
3589 std::swap(LHS, RHS);
3593 // On a floating point condition, the flags are set as follows:
3595 // 0 | 0 | 0 | X > Y
3596 // 0 | 0 | 1 | X < Y
3597 // 1 | 0 | 0 | X == Y
3598 // 1 | 1 | 1 | unordered
3599 switch (SetCCOpcode) {
3600 default: llvm_unreachable("Condcode should be pre-legalized away");
3602 case ISD::SETEQ: return X86::COND_E;
3603 case ISD::SETOLT: // flipped
3605 case ISD::SETGT: return X86::COND_A;
3606 case ISD::SETOLE: // flipped
3608 case ISD::SETGE: return X86::COND_AE;
3609 case ISD::SETUGT: // flipped
3611 case ISD::SETLT: return X86::COND_B;
3612 case ISD::SETUGE: // flipped
3614 case ISD::SETLE: return X86::COND_BE;
3616 case ISD::SETNE: return X86::COND_NE;
3617 case ISD::SETUO: return X86::COND_P;
3618 case ISD::SETO: return X86::COND_NP;
3620 case ISD::SETUNE: return X86::COND_INVALID;
3624 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3625 /// code. Current x86 isa includes the following FP cmov instructions:
3626 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3627 static bool hasFPCMov(unsigned X86CC) {
3643 /// isFPImmLegal - Returns true if the target can instruction select the
3644 /// specified FP immediate natively. If false, the legalizer will
3645 /// materialize the FP immediate as a load from a constant pool.
3646 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3647 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3648 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3654 /// \brief Returns true if it is beneficial to convert a load of a constant
3655 /// to just the constant itself.
3656 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3658 assert(Ty->isIntegerTy());
3660 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3661 if (BitSize == 0 || BitSize > 64)
3666 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3667 /// the specified range (L, H].
3668 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3669 return (Val < 0) || (Val >= Low && Val < Hi);
3672 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3673 /// specified value.
3674 static bool isUndefOrEqual(int Val, int CmpVal) {
3675 return (Val < 0 || Val == CmpVal);
3678 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3679 /// from position Pos and ending in Pos+Size, falls within the specified
3680 /// sequential range (L, L+Pos]. or is undef.
3681 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3682 unsigned Pos, unsigned Size, int Low) {
3683 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3684 if (!isUndefOrEqual(Mask[i], Low))
3689 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3690 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3691 /// the second operand.
3692 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3693 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3694 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3695 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3696 return (Mask[0] < 2 && Mask[1] < 2);
3700 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3701 /// is suitable for input to PSHUFHW.
3702 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3703 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3706 // Lower quadword copied in order or undef.
3707 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3710 // Upper quadword shuffled.
3711 for (unsigned i = 4; i != 8; ++i)
3712 if (!isUndefOrInRange(Mask[i], 4, 8))
3715 if (VT == MVT::v16i16) {
3716 // Lower quadword copied in order or undef.
3717 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3720 // Upper quadword shuffled.
3721 for (unsigned i = 12; i != 16; ++i)
3722 if (!isUndefOrInRange(Mask[i], 12, 16))
3729 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3730 /// is suitable for input to PSHUFLW.
3731 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3732 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3735 // Upper quadword copied in order.
3736 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3739 // Lower quadword shuffled.
3740 for (unsigned i = 0; i != 4; ++i)
3741 if (!isUndefOrInRange(Mask[i], 0, 4))
3744 if (VT == MVT::v16i16) {
3745 // Upper quadword copied in order.
3746 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3749 // Lower quadword shuffled.
3750 for (unsigned i = 8; i != 12; ++i)
3751 if (!isUndefOrInRange(Mask[i], 8, 12))
3758 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3759 /// is suitable for input to PALIGNR.
3760 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3761 const X86Subtarget *Subtarget) {
3762 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3763 (VT.is256BitVector() && !Subtarget->hasInt256()))
3766 unsigned NumElts = VT.getVectorNumElements();
3767 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3768 unsigned NumLaneElts = NumElts/NumLanes;
3770 // Do not handle 64-bit element shuffles with palignr.
3771 if (NumLaneElts == 2)
3774 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3776 for (i = 0; i != NumLaneElts; ++i) {
3781 // Lane is all undef, go to next lane
3782 if (i == NumLaneElts)
3785 int Start = Mask[i+l];
3787 // Make sure its in this lane in one of the sources
3788 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3789 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3792 // If not lane 0, then we must match lane 0
3793 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3796 // Correct second source to be contiguous with first source
3797 if (Start >= (int)NumElts)
3798 Start -= NumElts - NumLaneElts;
3800 // Make sure we're shifting in the right direction.
3801 if (Start <= (int)(i+l))
3806 // Check the rest of the elements to see if they are consecutive.
3807 for (++i; i != NumLaneElts; ++i) {
3808 int Idx = Mask[i+l];
3810 // Make sure its in this lane
3811 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3812 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3815 // If not lane 0, then we must match lane 0
3816 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3819 if (Idx >= (int)NumElts)
3820 Idx -= NumElts - NumLaneElts;
3822 if (!isUndefOrEqual(Idx, Start+i))
3831 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3832 /// the two vector operands have swapped position.
3833 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3834 unsigned NumElems) {
3835 for (unsigned i = 0; i != NumElems; ++i) {
3839 else if (idx < (int)NumElems)
3840 Mask[i] = idx + NumElems;
3842 Mask[i] = idx - NumElems;
3846 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3848 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3849 /// reverse of what x86 shuffles want.
3850 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3852 unsigned NumElems = VT.getVectorNumElements();
3853 unsigned NumLanes = VT.getSizeInBits()/128;
3854 unsigned NumLaneElems = NumElems/NumLanes;
3856 if (NumLaneElems != 2 && NumLaneElems != 4)
3859 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3860 bool symetricMaskRequired =
3861 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3863 // VSHUFPSY divides the resulting vector into 4 chunks.
3864 // The sources are also splitted into 4 chunks, and each destination
3865 // chunk must come from a different source chunk.
3867 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3868 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3870 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3871 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3873 // VSHUFPDY divides the resulting vector into 4 chunks.
3874 // The sources are also splitted into 4 chunks, and each destination
3875 // chunk must come from a different source chunk.
3877 // SRC1 => X3 X2 X1 X0
3878 // SRC2 => Y3 Y2 Y1 Y0
3880 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3882 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3883 unsigned HalfLaneElems = NumLaneElems/2;
3884 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3885 for (unsigned i = 0; i != NumLaneElems; ++i) {
3886 int Idx = Mask[i+l];
3887 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3888 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3890 // For VSHUFPSY, the mask of the second half must be the same as the
3891 // first but with the appropriate offsets. This works in the same way as
3892 // VPERMILPS works with masks.
3893 if (!symetricMaskRequired || Idx < 0)
3895 if (MaskVal[i] < 0) {
3896 MaskVal[i] = Idx - l;
3899 if ((signed)(Idx - l) != MaskVal[i])
3907 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3909 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3910 if (!VT.is128BitVector())
3913 unsigned NumElems = VT.getVectorNumElements();
3918 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3919 return isUndefOrEqual(Mask[0], 6) &&
3920 isUndefOrEqual(Mask[1], 7) &&
3921 isUndefOrEqual(Mask[2], 2) &&
3922 isUndefOrEqual(Mask[3], 3);
3925 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3926 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3928 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3929 if (!VT.is128BitVector())
3932 unsigned NumElems = VT.getVectorNumElements();
3937 return isUndefOrEqual(Mask[0], 2) &&
3938 isUndefOrEqual(Mask[1], 3) &&
3939 isUndefOrEqual(Mask[2], 2) &&
3940 isUndefOrEqual(Mask[3], 3);
3943 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3945 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3946 if (!VT.is128BitVector())
3949 unsigned NumElems = VT.getVectorNumElements();
3951 if (NumElems != 2 && NumElems != 4)
3954 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3955 if (!isUndefOrEqual(Mask[i], i + NumElems))
3958 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3959 if (!isUndefOrEqual(Mask[i], i))
3965 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3967 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3968 if (!VT.is128BitVector())
3971 unsigned NumElems = VT.getVectorNumElements();
3973 if (NumElems != 2 && NumElems != 4)
3976 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3977 if (!isUndefOrEqual(Mask[i], i))
3980 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3981 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3987 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3988 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3989 /// i. e: If all but one element come from the same vector.
3990 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3991 // TODO: Deal with AVX's VINSERTPS
3992 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3995 unsigned CorrectPosV1 = 0;
3996 unsigned CorrectPosV2 = 0;
3997 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3998 if (Mask[i] == -1) {
4006 else if (Mask[i] == i + 4)
4010 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4011 // We have 3 elements (undefs count as elements from any vector) from one
4012 // vector, and one from another.
4019 // Some special combinations that can be optimized.
4022 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4023 SelectionDAG &DAG) {
4024 MVT VT = SVOp->getSimpleValueType(0);
4027 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4030 ArrayRef<int> Mask = SVOp->getMask();
4032 // These are the special masks that may be optimized.
4033 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4034 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4035 bool MatchEvenMask = true;
4036 bool MatchOddMask = true;
4037 for (int i=0; i<8; ++i) {
4038 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4039 MatchEvenMask = false;
4040 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4041 MatchOddMask = false;
4044 if (!MatchEvenMask && !MatchOddMask)
4047 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4049 SDValue Op0 = SVOp->getOperand(0);
4050 SDValue Op1 = SVOp->getOperand(1);
4052 if (MatchEvenMask) {
4053 // Shift the second operand right to 32 bits.
4054 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4055 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4057 // Shift the first operand left to 32 bits.
4058 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4059 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4061 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4062 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4065 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4066 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4067 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4068 bool HasInt256, bool V2IsSplat = false) {
4070 assert(VT.getSizeInBits() >= 128 &&
4071 "Unsupported vector type for unpckl");
4073 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4075 unsigned NumOf256BitLanes;
4076 unsigned NumElts = VT.getVectorNumElements();
4077 if (VT.is256BitVector()) {
4078 if (NumElts != 4 && NumElts != 8 &&
4079 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4082 NumOf256BitLanes = 1;
4083 } else if (VT.is512BitVector()) {
4084 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4085 "Unsupported vector type for unpckh");
4087 NumOf256BitLanes = 2;
4090 NumOf256BitLanes = 1;
4093 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4094 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4096 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4097 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4098 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4099 int BitI = Mask[l256*NumEltsInStride+l+i];
4100 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4101 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4103 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4105 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4113 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4114 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4115 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4116 bool HasInt256, bool V2IsSplat = false) {
4117 assert(VT.getSizeInBits() >= 128 &&
4118 "Unsupported vector type for unpckh");
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+NumLaneElts/2; 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 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4161 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4163 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4164 unsigned NumElts = VT.getVectorNumElements();
4165 bool Is256BitVec = VT.is256BitVector();
4167 if (VT.is512BitVector())
4169 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4170 "Unsupported vector type for unpckh");
4172 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4173 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4176 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4177 // FIXME: Need a better way to get rid of this, there's no latency difference
4178 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4179 // the former later. We should also remove the "_undef" special mask.
4180 if (NumElts == 4 && Is256BitVec)
4183 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4184 // independently on 128-bit lanes.
4185 unsigned NumLanes = VT.getSizeInBits()/128;
4186 unsigned NumLaneElts = NumElts/NumLanes;
4188 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4189 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4190 int BitI = Mask[l+i];
4191 int BitI1 = Mask[l+i+1];
4193 if (!isUndefOrEqual(BitI, j))
4195 if (!isUndefOrEqual(BitI1, j))
4203 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4204 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4206 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4207 unsigned NumElts = VT.getVectorNumElements();
4209 if (VT.is512BitVector())
4212 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4213 "Unsupported vector type for unpckh");
4215 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4216 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4219 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4220 // independently on 128-bit lanes.
4221 unsigned NumLanes = VT.getSizeInBits()/128;
4222 unsigned NumLaneElts = NumElts/NumLanes;
4224 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4225 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4226 int BitI = Mask[l+i];
4227 int BitI1 = Mask[l+i+1];
4228 if (!isUndefOrEqual(BitI, j))
4230 if (!isUndefOrEqual(BitI1, j))
4237 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4238 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4239 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4240 if (!VT.is512BitVector())
4243 unsigned NumElts = VT.getVectorNumElements();
4244 unsigned HalfSize = NumElts/2;
4245 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4246 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4251 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4252 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4260 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4261 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4262 /// MOVSD, and MOVD, i.e. setting the lowest element.
4263 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4264 if (VT.getVectorElementType().getSizeInBits() < 32)
4266 if (!VT.is128BitVector())
4269 unsigned NumElts = VT.getVectorNumElements();
4271 if (!isUndefOrEqual(Mask[0], NumElts))
4274 for (unsigned i = 1; i != NumElts; ++i)
4275 if (!isUndefOrEqual(Mask[i], i))
4281 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4282 /// as permutations between 128-bit chunks or halves. As an example: this
4284 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4285 /// The first half comes from the second half of V1 and the second half from the
4286 /// the second half of V2.
4287 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4288 if (!HasFp256 || !VT.is256BitVector())
4291 // The shuffle result is divided into half A and half B. In total the two
4292 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4293 // B must come from C, D, E or F.
4294 unsigned HalfSize = VT.getVectorNumElements()/2;
4295 bool MatchA = false, MatchB = false;
4297 // Check if A comes from one of C, D, E, F.
4298 for (unsigned Half = 0; Half != 4; ++Half) {
4299 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4305 // Check if B comes from one of C, D, E, F.
4306 for (unsigned Half = 0; Half != 4; ++Half) {
4307 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4313 return MatchA && MatchB;
4316 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4317 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4318 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4319 MVT VT = SVOp->getSimpleValueType(0);
4321 unsigned HalfSize = VT.getVectorNumElements()/2;
4323 unsigned FstHalf = 0, SndHalf = 0;
4324 for (unsigned i = 0; i < HalfSize; ++i) {
4325 if (SVOp->getMaskElt(i) > 0) {
4326 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4330 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4331 if (SVOp->getMaskElt(i) > 0) {
4332 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4337 return (FstHalf | (SndHalf << 4));
4340 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4341 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4342 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4346 unsigned NumElts = VT.getVectorNumElements();
4348 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4349 for (unsigned i = 0; i != NumElts; ++i) {
4352 Imm8 |= Mask[i] << (i*2);
4357 unsigned LaneSize = 4;
4358 SmallVector<int, 4> MaskVal(LaneSize, -1);
4360 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4361 for (unsigned i = 0; i != LaneSize; ++i) {
4362 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4366 if (MaskVal[i] < 0) {
4367 MaskVal[i] = Mask[i+l] - l;
4368 Imm8 |= MaskVal[i] << (i*2);
4371 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4378 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4379 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4380 /// Note that VPERMIL mask matching is different depending whether theunderlying
4381 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4382 /// to the same elements of the low, but to the higher half of the source.
4383 /// In VPERMILPD the two lanes could be shuffled independently of each other
4384 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4385 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4386 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4387 if (VT.getSizeInBits() < 256 || EltSize < 32)
4389 bool symetricMaskRequired = (EltSize == 32);
4390 unsigned NumElts = VT.getVectorNumElements();
4392 unsigned NumLanes = VT.getSizeInBits()/128;
4393 unsigned LaneSize = NumElts/NumLanes;
4394 // 2 or 4 elements in one lane
4396 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4397 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4398 for (unsigned i = 0; i != LaneSize; ++i) {
4399 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4401 if (symetricMaskRequired) {
4402 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4403 ExpectedMaskVal[i] = Mask[i+l] - l;
4406 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4414 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4415 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4416 /// element of vector 2 and the other elements to come from vector 1 in order.
4417 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4418 bool V2IsSplat = false, bool V2IsUndef = false) {
4419 if (!VT.is128BitVector())
4422 unsigned NumOps = VT.getVectorNumElements();
4423 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4426 if (!isUndefOrEqual(Mask[0], 0))
4429 for (unsigned i = 1; i != NumOps; ++i)
4430 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4431 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4432 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4438 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4439 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4440 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4441 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4442 const X86Subtarget *Subtarget) {
4443 if (!Subtarget->hasSSE3())
4446 unsigned NumElems = VT.getVectorNumElements();
4448 if ((VT.is128BitVector() && NumElems != 4) ||
4449 (VT.is256BitVector() && NumElems != 8) ||
4450 (VT.is512BitVector() && NumElems != 16))
4453 // "i+1" is the value the indexed mask element must have
4454 for (unsigned i = 0; i != NumElems; i += 2)
4455 if (!isUndefOrEqual(Mask[i], i+1) ||
4456 !isUndefOrEqual(Mask[i+1], i+1))
4462 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4463 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4464 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4465 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4466 const X86Subtarget *Subtarget) {
4467 if (!Subtarget->hasSSE3())
4470 unsigned NumElems = VT.getVectorNumElements();
4472 if ((VT.is128BitVector() && NumElems != 4) ||
4473 (VT.is256BitVector() && NumElems != 8) ||
4474 (VT.is512BitVector() && NumElems != 16))
4477 // "i" is the value the indexed mask element must have
4478 for (unsigned i = 0; i != NumElems; i += 2)
4479 if (!isUndefOrEqual(Mask[i], i) ||
4480 !isUndefOrEqual(Mask[i+1], i))
4486 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4487 /// specifies a shuffle of elements that is suitable for input to 256-bit
4488 /// version of MOVDDUP.
4489 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4490 if (!HasFp256 || !VT.is256BitVector())
4493 unsigned NumElts = VT.getVectorNumElements();
4497 for (unsigned i = 0; i != NumElts/2; ++i)
4498 if (!isUndefOrEqual(Mask[i], 0))
4500 for (unsigned i = NumElts/2; i != NumElts; ++i)
4501 if (!isUndefOrEqual(Mask[i], NumElts/2))
4506 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4507 /// specifies a shuffle of elements that is suitable for input to 128-bit
4508 /// version of MOVDDUP.
4509 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4510 if (!VT.is128BitVector())
4513 unsigned e = VT.getVectorNumElements() / 2;
4514 for (unsigned i = 0; i != e; ++i)
4515 if (!isUndefOrEqual(Mask[i], i))
4517 for (unsigned i = 0; i != e; ++i)
4518 if (!isUndefOrEqual(Mask[e+i], i))
4523 /// isVEXTRACTIndex - Return true if the specified
4524 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4525 /// suitable for instruction that extract 128 or 256 bit vectors
4526 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4527 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4528 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4531 // The index should be aligned on a vecWidth-bit boundary.
4533 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4535 MVT VT = N->getSimpleValueType(0);
4536 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4537 bool Result = (Index * ElSize) % vecWidth == 0;
4542 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4543 /// operand specifies a subvector insert that is suitable for input to
4544 /// insertion of 128 or 256-bit subvectors
4545 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4546 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4547 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4549 // The index should be aligned on a vecWidth-bit boundary.
4551 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4553 MVT VT = N->getSimpleValueType(0);
4554 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4555 bool Result = (Index * ElSize) % vecWidth == 0;
4560 bool X86::isVINSERT128Index(SDNode *N) {
4561 return isVINSERTIndex(N, 128);
4564 bool X86::isVINSERT256Index(SDNode *N) {
4565 return isVINSERTIndex(N, 256);
4568 bool X86::isVEXTRACT128Index(SDNode *N) {
4569 return isVEXTRACTIndex(N, 128);
4572 bool X86::isVEXTRACT256Index(SDNode *N) {
4573 return isVEXTRACTIndex(N, 256);
4576 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4577 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4578 /// Handles 128-bit and 256-bit.
4579 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4580 MVT VT = N->getSimpleValueType(0);
4582 assert((VT.getSizeInBits() >= 128) &&
4583 "Unsupported vector type for PSHUF/SHUFP");
4585 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4586 // independently on 128-bit lanes.
4587 unsigned NumElts = VT.getVectorNumElements();
4588 unsigned NumLanes = VT.getSizeInBits()/128;
4589 unsigned NumLaneElts = NumElts/NumLanes;
4591 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4592 "Only supports 2, 4 or 8 elements per lane");
4594 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4596 for (unsigned i = 0; i != NumElts; ++i) {
4597 int Elt = N->getMaskElt(i);
4598 if (Elt < 0) continue;
4599 Elt &= NumLaneElts - 1;
4600 unsigned ShAmt = (i << Shift) % 8;
4601 Mask |= Elt << ShAmt;
4607 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4608 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4609 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4610 MVT VT = N->getSimpleValueType(0);
4612 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4613 "Unsupported vector type for PSHUFHW");
4615 unsigned NumElts = VT.getVectorNumElements();
4618 for (unsigned l = 0; l != NumElts; l += 8) {
4619 // 8 nodes per lane, but we only care about the last 4.
4620 for (unsigned i = 0; i < 4; ++i) {
4621 int Elt = N->getMaskElt(l+i+4);
4622 if (Elt < 0) continue;
4623 Elt &= 0x3; // only 2-bits.
4624 Mask |= Elt << (i * 2);
4631 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4632 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4633 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4634 MVT VT = N->getSimpleValueType(0);
4636 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4637 "Unsupported vector type for PSHUFHW");
4639 unsigned NumElts = VT.getVectorNumElements();
4642 for (unsigned l = 0; l != NumElts; l += 8) {
4643 // 8 nodes per lane, but we only care about the first 4.
4644 for (unsigned i = 0; i < 4; ++i) {
4645 int Elt = N->getMaskElt(l+i);
4646 if (Elt < 0) continue;
4647 Elt &= 0x3; // only 2-bits
4648 Mask |= Elt << (i * 2);
4655 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4656 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4657 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4658 MVT VT = SVOp->getSimpleValueType(0);
4659 unsigned EltSize = VT.is512BitVector() ? 1 :
4660 VT.getVectorElementType().getSizeInBits() >> 3;
4662 unsigned NumElts = VT.getVectorNumElements();
4663 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4664 unsigned NumLaneElts = NumElts/NumLanes;
4668 for (i = 0; i != NumElts; ++i) {
4669 Val = SVOp->getMaskElt(i);
4673 if (Val >= (int)NumElts)
4674 Val -= NumElts - NumLaneElts;
4676 assert(Val - i > 0 && "PALIGNR imm should be positive");
4677 return (Val - i) * EltSize;
4680 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4681 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4682 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4683 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4686 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4688 MVT VecVT = N->getOperand(0).getSimpleValueType();
4689 MVT ElVT = VecVT.getVectorElementType();
4691 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4692 return Index / NumElemsPerChunk;
4695 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4696 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4697 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4698 llvm_unreachable("Illegal insert subvector for VINSERT");
4701 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4703 MVT VecVT = N->getSimpleValueType(0);
4704 MVT ElVT = VecVT.getVectorElementType();
4706 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4707 return Index / NumElemsPerChunk;
4710 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4711 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4712 /// and VINSERTI128 instructions.
4713 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4714 return getExtractVEXTRACTImmediate(N, 128);
4717 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4718 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4719 /// and VINSERTI64x4 instructions.
4720 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4721 return getExtractVEXTRACTImmediate(N, 256);
4724 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4725 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4726 /// and VINSERTI128 instructions.
4727 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4728 return getInsertVINSERTImmediate(N, 128);
4731 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4732 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4733 /// and VINSERTI64x4 instructions.
4734 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4735 return getInsertVINSERTImmediate(N, 256);
4738 /// isZero - Returns true if Elt is a constant integer zero
4739 static bool isZero(SDValue V) {
4740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4741 return C && C->isNullValue();
4744 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4746 bool X86::isZeroNode(SDValue Elt) {
4749 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4750 return CFP->getValueAPF().isPosZero();
4754 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4755 /// their permute mask.
4756 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4757 SelectionDAG &DAG) {
4758 MVT VT = SVOp->getSimpleValueType(0);
4759 unsigned NumElems = VT.getVectorNumElements();
4760 SmallVector<int, 8> MaskVec;
4762 for (unsigned i = 0; i != NumElems; ++i) {
4763 int Idx = SVOp->getMaskElt(i);
4765 if (Idx < (int)NumElems)
4770 MaskVec.push_back(Idx);
4772 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4773 SVOp->getOperand(0), &MaskVec[0]);
4776 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4777 /// match movhlps. The lower half elements should come from upper half of
4778 /// V1 (and in order), and the upper half elements should come from the upper
4779 /// half of V2 (and in order).
4780 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4781 if (!VT.is128BitVector())
4783 if (VT.getVectorNumElements() != 4)
4785 for (unsigned i = 0, e = 2; i != e; ++i)
4786 if (!isUndefOrEqual(Mask[i], i+2))
4788 for (unsigned i = 2; i != 4; ++i)
4789 if (!isUndefOrEqual(Mask[i], i+4))
4794 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4795 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4797 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4798 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4800 N = N->getOperand(0).getNode();
4801 if (!ISD::isNON_EXTLoad(N))
4804 *LD = cast<LoadSDNode>(N);
4808 // Test whether the given value is a vector value which will be legalized
4810 static bool WillBeConstantPoolLoad(SDNode *N) {
4811 if (N->getOpcode() != ISD::BUILD_VECTOR)
4814 // Check for any non-constant elements.
4815 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4816 switch (N->getOperand(i).getNode()->getOpcode()) {
4818 case ISD::ConstantFP:
4825 // Vectors of all-zeros and all-ones are materialized with special
4826 // instructions rather than being loaded.
4827 return !ISD::isBuildVectorAllZeros(N) &&
4828 !ISD::isBuildVectorAllOnes(N);
4831 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4832 /// match movlp{s|d}. The lower half elements should come from lower half of
4833 /// V1 (and in order), and the upper half elements should come from the upper
4834 /// half of V2 (and in order). And since V1 will become the source of the
4835 /// MOVLP, it must be either a vector load or a scalar load to vector.
4836 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4837 ArrayRef<int> Mask, MVT VT) {
4838 if (!VT.is128BitVector())
4841 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4843 // Is V2 is a vector load, don't do this transformation. We will try to use
4844 // load folding shufps op.
4845 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4848 unsigned NumElems = VT.getVectorNumElements();
4850 if (NumElems != 2 && NumElems != 4)
4852 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4853 if (!isUndefOrEqual(Mask[i], i))
4855 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4856 if (!isUndefOrEqual(Mask[i], i+NumElems))
4861 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4862 /// to an zero vector.
4863 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4864 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4865 SDValue V1 = N->getOperand(0);
4866 SDValue V2 = N->getOperand(1);
4867 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4868 for (unsigned i = 0; i != NumElems; ++i) {
4869 int Idx = N->getMaskElt(i);
4870 if (Idx >= (int)NumElems) {
4871 unsigned Opc = V2.getOpcode();
4872 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4874 if (Opc != ISD::BUILD_VECTOR ||
4875 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4877 } else if (Idx >= 0) {
4878 unsigned Opc = V1.getOpcode();
4879 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4881 if (Opc != ISD::BUILD_VECTOR ||
4882 !X86::isZeroNode(V1.getOperand(Idx)))
4889 /// getZeroVector - Returns a vector of specified type with all zero elements.
4891 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4892 SelectionDAG &DAG, SDLoc dl) {
4893 assert(VT.isVector() && "Expected a vector type");
4895 // Always build SSE zero vectors as <4 x i32> bitcasted
4896 // to their dest type. This ensures they get CSE'd.
4898 if (VT.is128BitVector()) { // SSE
4899 if (Subtarget->hasSSE2()) { // SSE2
4900 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4901 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4903 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4904 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4906 } else if (VT.is256BitVector()) { // AVX
4907 if (Subtarget->hasInt256()) { // AVX2
4908 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4909 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4910 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4912 // 256-bit logic and arithmetic instructions in AVX are all
4913 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4914 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4915 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4916 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4918 } else if (VT.is512BitVector()) { // AVX-512
4919 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4920 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4921 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4922 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4923 } else if (VT.getScalarType() == MVT::i1) {
4924 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4925 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4926 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4927 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4929 llvm_unreachable("Unexpected vector type");
4931 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4934 /// getOnesVector - Returns a vector of specified type with all bits set.
4935 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4936 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4937 /// Then bitcast to their original type, ensuring they get CSE'd.
4938 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4940 assert(VT.isVector() && "Expected a vector type");
4942 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4944 if (VT.is256BitVector()) {
4945 if (HasInt256) { // AVX2
4946 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4947 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4949 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4950 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4952 } else if (VT.is128BitVector()) {
4953 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4955 llvm_unreachable("Unexpected vector type");
4957 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4960 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4961 /// that point to V2 points to its first element.
4962 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4963 for (unsigned i = 0; i != NumElems; ++i) {
4964 if (Mask[i] > (int)NumElems) {
4970 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4971 /// operation of specified width.
4972 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4974 unsigned NumElems = VT.getVectorNumElements();
4975 SmallVector<int, 8> Mask;
4976 Mask.push_back(NumElems);
4977 for (unsigned i = 1; i != NumElems; ++i)
4979 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4982 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4983 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4985 unsigned NumElems = VT.getVectorNumElements();
4986 SmallVector<int, 8> Mask;
4987 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4989 Mask.push_back(i + NumElems);
4991 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4994 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4995 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4997 unsigned NumElems = VT.getVectorNumElements();
4998 SmallVector<int, 8> Mask;
4999 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5000 Mask.push_back(i + Half);
5001 Mask.push_back(i + NumElems + Half);
5003 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5006 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5007 // a generic shuffle instruction because the target has no such instructions.
5008 // Generate shuffles which repeat i16 and i8 several times until they can be
5009 // represented by v4f32 and then be manipulated by target suported shuffles.
5010 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5011 MVT VT = V.getSimpleValueType();
5012 int NumElems = VT.getVectorNumElements();
5015 while (NumElems > 4) {
5016 if (EltNo < NumElems/2) {
5017 V = getUnpackl(DAG, dl, VT, V, V);
5019 V = getUnpackh(DAG, dl, VT, V, V);
5020 EltNo -= NumElems/2;
5027 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5028 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5029 MVT VT = V.getSimpleValueType();
5032 if (VT.is128BitVector()) {
5033 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5034 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5035 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5037 } else if (VT.is256BitVector()) {
5038 // To use VPERMILPS to splat scalars, the second half of indicies must
5039 // refer to the higher part, which is a duplication of the lower one,
5040 // because VPERMILPS can only handle in-lane permutations.
5041 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5042 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5044 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5045 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5048 llvm_unreachable("Vector size not supported");
5050 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5053 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5054 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5055 MVT SrcVT = SV->getSimpleValueType(0);
5056 SDValue V1 = SV->getOperand(0);
5059 int EltNo = SV->getSplatIndex();
5060 int NumElems = SrcVT.getVectorNumElements();
5061 bool Is256BitVec = SrcVT.is256BitVector();
5063 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5064 "Unknown how to promote splat for type");
5066 // Extract the 128-bit part containing the splat element and update
5067 // the splat element index when it refers to the higher register.
5069 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5070 if (EltNo >= NumElems/2)
5071 EltNo -= NumElems/2;
5074 // All i16 and i8 vector types can't be used directly by a generic shuffle
5075 // instruction because the target has no such instruction. Generate shuffles
5076 // which repeat i16 and i8 several times until they fit in i32, and then can
5077 // be manipulated by target suported shuffles.
5078 MVT EltVT = SrcVT.getVectorElementType();
5079 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5080 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5082 // Recreate the 256-bit vector and place the same 128-bit vector
5083 // into the low and high part. This is necessary because we want
5084 // to use VPERM* to shuffle the vectors
5086 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5089 return getLegalSplat(DAG, V1, EltNo);
5092 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5093 /// vector of zero or undef vector. This produces a shuffle where the low
5094 /// element of V2 is swizzled into the zero/undef vector, landing at element
5095 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5096 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5098 const X86Subtarget *Subtarget,
5099 SelectionDAG &DAG) {
5100 MVT VT = V2.getSimpleValueType();
5102 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5103 unsigned NumElems = VT.getVectorNumElements();
5104 SmallVector<int, 16> MaskVec;
5105 for (unsigned i = 0; i != NumElems; ++i)
5106 // If this is the insertion idx, put the low elt of V2 here.
5107 MaskVec.push_back(i == Idx ? NumElems : i);
5108 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5111 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5112 /// target specific opcode. Returns true if the Mask could be calculated.
5113 /// Sets IsUnary to true if only uses one source.
5114 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5115 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5116 unsigned NumElems = VT.getVectorNumElements();
5120 switch(N->getOpcode()) {
5122 ImmN = N->getOperand(N->getNumOperands()-1);
5123 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5125 case X86ISD::UNPCKH:
5126 DecodeUNPCKHMask(VT, Mask);
5128 case X86ISD::UNPCKL:
5129 DecodeUNPCKLMask(VT, Mask);
5131 case X86ISD::MOVHLPS:
5132 DecodeMOVHLPSMask(NumElems, Mask);
5134 case X86ISD::MOVLHPS:
5135 DecodeMOVLHPSMask(NumElems, Mask);
5137 case X86ISD::PALIGNR:
5138 ImmN = N->getOperand(N->getNumOperands()-1);
5139 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5141 case X86ISD::PSHUFD:
5142 case X86ISD::VPERMILP:
5143 ImmN = N->getOperand(N->getNumOperands()-1);
5144 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5147 case X86ISD::PSHUFHW:
5148 ImmN = N->getOperand(N->getNumOperands()-1);
5149 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152 case X86ISD::PSHUFLW:
5153 ImmN = N->getOperand(N->getNumOperands()-1);
5154 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5157 case X86ISD::VPERMI:
5158 ImmN = N->getOperand(N->getNumOperands()-1);
5159 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5163 case X86ISD::MOVSD: {
5164 // The index 0 always comes from the first element of the second source,
5165 // this is why MOVSS and MOVSD are used in the first place. The other
5166 // elements come from the other positions of the first source vector
5167 Mask.push_back(NumElems);
5168 for (unsigned i = 1; i != NumElems; ++i) {
5173 case X86ISD::VPERM2X128:
5174 ImmN = N->getOperand(N->getNumOperands()-1);
5175 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5176 if (Mask.empty()) return false;
5178 case X86ISD::MOVDDUP:
5179 case X86ISD::MOVLHPD:
5180 case X86ISD::MOVLPD:
5181 case X86ISD::MOVLPS:
5182 case X86ISD::MOVSHDUP:
5183 case X86ISD::MOVSLDUP:
5184 // Not yet implemented
5186 default: llvm_unreachable("unknown target shuffle node");
5192 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5193 /// element of the result of the vector shuffle.
5194 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5197 return SDValue(); // Limit search depth.
5199 SDValue V = SDValue(N, 0);
5200 EVT VT = V.getValueType();
5201 unsigned Opcode = V.getOpcode();
5203 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5204 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5205 int Elt = SV->getMaskElt(Index);
5208 return DAG.getUNDEF(VT.getVectorElementType());
5210 unsigned NumElems = VT.getVectorNumElements();
5211 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5212 : SV->getOperand(1);
5213 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5216 // Recurse into target specific vector shuffles to find scalars.
5217 if (isTargetShuffle(Opcode)) {
5218 MVT ShufVT = V.getSimpleValueType();
5219 unsigned NumElems = ShufVT.getVectorNumElements();
5220 SmallVector<int, 16> ShuffleMask;
5223 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5226 int Elt = ShuffleMask[Index];
5228 return DAG.getUNDEF(ShufVT.getVectorElementType());
5230 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5232 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5236 // Actual nodes that may contain scalar elements
5237 if (Opcode == ISD::BITCAST) {
5238 V = V.getOperand(0);
5239 EVT SrcVT = V.getValueType();
5240 unsigned NumElems = VT.getVectorNumElements();
5242 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5246 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5247 return (Index == 0) ? V.getOperand(0)
5248 : DAG.getUNDEF(VT.getVectorElementType());
5250 if (V.getOpcode() == ISD::BUILD_VECTOR)
5251 return V.getOperand(Index);
5256 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5257 /// shuffle operation which come from a consecutively from a zero. The
5258 /// search can start in two different directions, from left or right.
5259 /// We count undefs as zeros until PreferredNum is reached.
5260 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5261 unsigned NumElems, bool ZerosFromLeft,
5263 unsigned PreferredNum = -1U) {
5264 unsigned NumZeros = 0;
5265 for (unsigned i = 0; i != NumElems; ++i) {
5266 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5267 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5271 if (X86::isZeroNode(Elt))
5273 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5274 NumZeros = std::min(NumZeros + 1, PreferredNum);
5282 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5283 /// correspond consecutively to elements from one of the vector operands,
5284 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5286 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5287 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5288 unsigned NumElems, unsigned &OpNum) {
5289 bool SeenV1 = false;
5290 bool SeenV2 = false;
5292 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5293 int Idx = SVOp->getMaskElt(i);
5294 // Ignore undef indicies
5298 if (Idx < (int)NumElems)
5303 // Only accept consecutive elements from the same vector
5304 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5308 OpNum = SeenV1 ? 0 : 1;
5312 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5313 /// logical left shift of a vector.
5314 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5315 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5317 SVOp->getSimpleValueType(0).getVectorNumElements();
5318 unsigned NumZeros = getNumOfConsecutiveZeros(
5319 SVOp, NumElems, false /* check zeros from right */, DAG,
5320 SVOp->getMaskElt(0));
5326 // Considering the elements in the mask that are not consecutive zeros,
5327 // check if they consecutively come from only one of the source vectors.
5329 // V1 = {X, A, B, C} 0
5331 // vector_shuffle V1, V2 <1, 2, 3, X>
5333 if (!isShuffleMaskConsecutive(SVOp,
5334 0, // Mask Start Index
5335 NumElems-NumZeros, // Mask End Index(exclusive)
5336 NumZeros, // Where to start looking in the src vector
5337 NumElems, // Number of elements in vector
5338 OpSrc)) // Which source operand ?
5343 ShVal = SVOp->getOperand(OpSrc);
5347 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5348 /// logical left shift of a vector.
5349 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5350 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5352 SVOp->getSimpleValueType(0).getVectorNumElements();
5353 unsigned NumZeros = getNumOfConsecutiveZeros(
5354 SVOp, NumElems, true /* check zeros from left */, DAG,
5355 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5361 // Considering the elements in the mask that are not consecutive zeros,
5362 // check if they consecutively come from only one of the source vectors.
5364 // 0 { A, B, X, X } = V2
5366 // vector_shuffle V1, V2 <X, X, 4, 5>
5368 if (!isShuffleMaskConsecutive(SVOp,
5369 NumZeros, // Mask Start Index
5370 NumElems, // Mask End Index(exclusive)
5371 0, // Where to start looking in the src vector
5372 NumElems, // Number of elements in vector
5373 OpSrc)) // Which source operand ?
5378 ShVal = SVOp->getOperand(OpSrc);
5382 /// isVectorShift - Returns true if the shuffle can be implemented as a
5383 /// logical left or right shift of a vector.
5384 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5385 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5386 // Although the logic below support any bitwidth size, there are no
5387 // shift instructions which handle more than 128-bit vectors.
5388 if (!SVOp->getSimpleValueType(0).is128BitVector())
5391 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5392 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5398 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5400 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5401 unsigned NumNonZero, unsigned NumZero,
5403 const X86Subtarget* Subtarget,
5404 const TargetLowering &TLI) {
5411 for (unsigned i = 0; i < 16; ++i) {
5412 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5413 if (ThisIsNonZero && First) {
5415 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5417 V = DAG.getUNDEF(MVT::v8i16);
5422 SDValue ThisElt, LastElt;
5423 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5424 if (LastIsNonZero) {
5425 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5426 MVT::i16, Op.getOperand(i-1));
5428 if (ThisIsNonZero) {
5429 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5430 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5431 ThisElt, DAG.getConstant(8, MVT::i8));
5433 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5437 if (ThisElt.getNode())
5438 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5439 DAG.getIntPtrConstant(i/2));
5443 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5446 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5448 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5449 unsigned NumNonZero, unsigned NumZero,
5451 const X86Subtarget* Subtarget,
5452 const TargetLowering &TLI) {
5459 for (unsigned i = 0; i < 8; ++i) {
5460 bool isNonZero = (NonZeros & (1 << i)) != 0;
5464 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5466 V = DAG.getUNDEF(MVT::v8i16);
5469 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5470 MVT::v8i16, V, Op.getOperand(i),
5471 DAG.getIntPtrConstant(i));
5478 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5479 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5480 unsigned NonZeros, unsigned NumNonZero,
5481 unsigned NumZero, SelectionDAG &DAG,
5482 const X86Subtarget *Subtarget,
5483 const TargetLowering &TLI) {
5484 // We know there's at least one non-zero element
5485 unsigned FirstNonZeroIdx = 0;
5486 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5487 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5488 X86::isZeroNode(FirstNonZero)) {
5490 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5493 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5494 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5497 SDValue V = FirstNonZero.getOperand(0);
5498 MVT VVT = V.getSimpleValueType();
5499 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5502 unsigned FirstNonZeroDst =
5503 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5504 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5505 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5506 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5508 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5509 SDValue Elem = Op.getOperand(Idx);
5510 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5513 // TODO: What else can be here? Deal with it.
5514 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5517 // TODO: Some optimizations are still possible here
5518 // ex: Getting one element from a vector, and the rest from another.
5519 if (Elem.getOperand(0) != V)
5522 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5525 else if (IncorrectIdx == -1U) {
5529 // There was already one element with an incorrect index.
5530 // We can't optimize this case to an insertps.
5534 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5536 EVT VT = Op.getSimpleValueType();
5537 unsigned ElementMoveMask = 0;
5538 if (IncorrectIdx == -1U)
5539 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5541 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5543 SDValue InsertpsMask =
5544 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5545 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5551 /// getVShift - Return a vector logical shift node.
5553 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5554 unsigned NumBits, SelectionDAG &DAG,
5555 const TargetLowering &TLI, SDLoc dl) {
5556 assert(VT.is128BitVector() && "Unknown type for VShift");
5557 EVT ShVT = MVT::v2i64;
5558 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5559 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5560 return DAG.getNode(ISD::BITCAST, dl, VT,
5561 DAG.getNode(Opc, dl, ShVT, SrcOp,
5562 DAG.getConstant(NumBits,
5563 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5567 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5569 // Check if the scalar load can be widened into a vector load. And if
5570 // the address is "base + cst" see if the cst can be "absorbed" into
5571 // the shuffle mask.
5572 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5573 SDValue Ptr = LD->getBasePtr();
5574 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5576 EVT PVT = LD->getValueType(0);
5577 if (PVT != MVT::i32 && PVT != MVT::f32)
5582 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5583 FI = FINode->getIndex();
5585 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5586 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5587 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5588 Offset = Ptr.getConstantOperandVal(1);
5589 Ptr = Ptr.getOperand(0);
5594 // FIXME: 256-bit vector instructions don't require a strict alignment,
5595 // improve this code to support it better.
5596 unsigned RequiredAlign = VT.getSizeInBits()/8;
5597 SDValue Chain = LD->getChain();
5598 // Make sure the stack object alignment is at least 16 or 32.
5599 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5600 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5601 if (MFI->isFixedObjectIndex(FI)) {
5602 // Can't change the alignment. FIXME: It's possible to compute
5603 // the exact stack offset and reference FI + adjust offset instead.
5604 // If someone *really* cares about this. That's the way to implement it.
5607 MFI->setObjectAlignment(FI, RequiredAlign);
5611 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5612 // Ptr + (Offset & ~15).
5615 if ((Offset % RequiredAlign) & 3)
5617 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5619 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5620 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5622 int EltNo = (Offset - StartOffset) >> 2;
5623 unsigned NumElems = VT.getVectorNumElements();
5625 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5626 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5627 LD->getPointerInfo().getWithOffset(StartOffset),
5628 false, false, false, 0);
5630 SmallVector<int, 8> Mask;
5631 for (unsigned i = 0; i != NumElems; ++i)
5632 Mask.push_back(EltNo);
5634 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5640 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5641 /// vector of type 'VT', see if the elements can be replaced by a single large
5642 /// load which has the same value as a build_vector whose operands are 'elts'.
5644 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5646 /// FIXME: we'd also like to handle the case where the last elements are zero
5647 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5648 /// There's even a handy isZeroNode for that purpose.
5649 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5650 SDLoc &DL, SelectionDAG &DAG,
5651 bool isAfterLegalize) {
5652 EVT EltVT = VT.getVectorElementType();
5653 unsigned NumElems = Elts.size();
5655 LoadSDNode *LDBase = nullptr;
5656 unsigned LastLoadedElt = -1U;
5658 // For each element in the initializer, see if we've found a load or an undef.
5659 // If we don't find an initial load element, or later load elements are
5660 // non-consecutive, bail out.
5661 for (unsigned i = 0; i < NumElems; ++i) {
5662 SDValue Elt = Elts[i];
5664 if (!Elt.getNode() ||
5665 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5668 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5670 LDBase = cast<LoadSDNode>(Elt.getNode());
5674 if (Elt.getOpcode() == ISD::UNDEF)
5677 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5678 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5683 // If we have found an entire vector of loads and undefs, then return a large
5684 // load of the entire vector width starting at the base pointer. If we found
5685 // consecutive loads for the low half, generate a vzext_load node.
5686 if (LastLoadedElt == NumElems - 1) {
5688 if (isAfterLegalize &&
5689 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5692 SDValue NewLd = SDValue();
5694 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5695 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5696 LDBase->getPointerInfo(),
5697 LDBase->isVolatile(), LDBase->isNonTemporal(),
5698 LDBase->isInvariant(), 0);
5699 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5700 LDBase->getPointerInfo(),
5701 LDBase->isVolatile(), LDBase->isNonTemporal(),
5702 LDBase->isInvariant(), LDBase->getAlignment());
5704 if (LDBase->hasAnyUseOfValue(1)) {
5705 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5707 SDValue(NewLd.getNode(), 1));
5708 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5709 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5710 SDValue(NewLd.getNode(), 1));
5715 if (NumElems == 4 && LastLoadedElt == 1 &&
5716 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5717 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5718 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5720 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5721 LDBase->getPointerInfo(),
5722 LDBase->getAlignment(),
5723 false/*isVolatile*/, true/*ReadMem*/,
5726 // Make sure the newly-created LOAD is in the same position as LDBase in
5727 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5728 // update uses of LDBase's output chain to use the TokenFactor.
5729 if (LDBase->hasAnyUseOfValue(1)) {
5730 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5731 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5732 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5733 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5734 SDValue(ResNode.getNode(), 1));
5737 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5742 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5743 /// to generate a splat value for the following cases:
5744 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5745 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5746 /// a scalar load, or a constant.
5747 /// The VBROADCAST node is returned when a pattern is found,
5748 /// or SDValue() otherwise.
5749 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5750 SelectionDAG &DAG) {
5751 if (!Subtarget->hasFp256())
5754 MVT VT = Op.getSimpleValueType();
5757 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5758 "Unsupported vector type for broadcast.");
5763 switch (Op.getOpcode()) {
5765 // Unknown pattern found.
5768 case ISD::BUILD_VECTOR: {
5769 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5770 // The BUILD_VECTOR node must be a splat.
5771 SDValue Splat = BVOp->getConstantSplatValue();
5776 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5777 Ld.getOpcode() == ISD::ConstantFP);
5779 // The suspected load node has several users. Make sure that all
5780 // of its users are from the BUILD_VECTOR node.
5781 // Constants may have multiple users.
5782 // FIXME: This doesn't make sense if the build vector contains undefs.
5783 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5788 case ISD::VECTOR_SHUFFLE: {
5789 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5791 // Shuffles must have a splat mask where the first element is
5793 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5796 SDValue Sc = Op.getOperand(0);
5797 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5798 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5800 if (!Subtarget->hasInt256())
5803 // Use the register form of the broadcast instruction available on AVX2.
5804 if (VT.getSizeInBits() >= 256)
5805 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5806 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5809 Ld = Sc.getOperand(0);
5810 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5811 Ld.getOpcode() == ISD::ConstantFP);
5813 // The scalar_to_vector node and the suspected
5814 // load node must have exactly one user.
5815 // Constants may have multiple users.
5817 // AVX-512 has register version of the broadcast
5818 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5819 Ld.getValueType().getSizeInBits() >= 32;
5820 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5827 bool IsGE256 = (VT.getSizeInBits() >= 256);
5829 // Handle the broadcasting a single constant scalar from the constant pool
5830 // into a vector. On Sandybridge it is still better to load a constant vector
5831 // from the constant pool and not to broadcast it from a scalar.
5832 if (ConstSplatVal && Subtarget->hasInt256()) {
5833 EVT CVT = Ld.getValueType();
5834 assert(!CVT.isVector() && "Must not broadcast a vector type");
5835 unsigned ScalarSize = CVT.getSizeInBits();
5837 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5838 const Constant *C = nullptr;
5839 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5840 C = CI->getConstantIntValue();
5841 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5842 C = CF->getConstantFPValue();
5844 assert(C && "Invalid constant type");
5846 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5847 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5848 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5849 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5850 MachinePointerInfo::getConstantPool(),
5851 false, false, false, Alignment);
5853 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5857 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5858 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5860 // Handle AVX2 in-register broadcasts.
5861 if (!IsLoad && Subtarget->hasInt256() &&
5862 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5863 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5865 // The scalar source must be a normal load.
5869 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5870 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5872 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5873 // double since there is no vbroadcastsd xmm
5874 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5875 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5876 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5879 // Unsupported broadcast.
5883 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5884 /// underlying vector and index.
5886 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5888 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5890 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5891 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5894 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5896 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5898 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5899 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5902 // In this case the vector is the extract_subvector expression and the index
5903 // is 2, as specified by the shuffle.
5904 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5905 SDValue ShuffleVec = SVOp->getOperand(0);
5906 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5907 assert(ShuffleVecVT.getVectorElementType() ==
5908 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5910 int ShuffleIdx = SVOp->getMaskElt(Idx);
5911 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5912 ExtractedFromVec = ShuffleVec;
5918 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5919 MVT VT = Op.getSimpleValueType();
5921 // Skip if insert_vec_elt is not supported.
5922 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5923 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5927 unsigned NumElems = Op.getNumOperands();
5931 SmallVector<unsigned, 4> InsertIndices;
5932 SmallVector<int, 8> Mask(NumElems, -1);
5934 for (unsigned i = 0; i != NumElems; ++i) {
5935 unsigned Opc = Op.getOperand(i).getOpcode();
5937 if (Opc == ISD::UNDEF)
5940 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5941 // Quit if more than 1 elements need inserting.
5942 if (InsertIndices.size() > 1)
5945 InsertIndices.push_back(i);
5949 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5950 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5951 // Quit if non-constant index.
5952 if (!isa<ConstantSDNode>(ExtIdx))
5954 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5956 // Quit if extracted from vector of different type.
5957 if (ExtractedFromVec.getValueType() != VT)
5960 if (!VecIn1.getNode())
5961 VecIn1 = ExtractedFromVec;
5962 else if (VecIn1 != ExtractedFromVec) {
5963 if (!VecIn2.getNode())
5964 VecIn2 = ExtractedFromVec;
5965 else if (VecIn2 != ExtractedFromVec)
5966 // Quit if more than 2 vectors to shuffle
5970 if (ExtractedFromVec == VecIn1)
5972 else if (ExtractedFromVec == VecIn2)
5973 Mask[i] = Idx + NumElems;
5976 if (!VecIn1.getNode())
5979 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5980 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5981 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5982 unsigned Idx = InsertIndices[i];
5983 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5984 DAG.getIntPtrConstant(Idx));
5990 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5992 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5994 MVT VT = Op.getSimpleValueType();
5995 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5996 "Unexpected type in LowerBUILD_VECTORvXi1!");
5999 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6000 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6001 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6002 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6005 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6006 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6007 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6008 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6011 bool AllContants = true;
6012 uint64_t Immediate = 0;
6013 int NonConstIdx = -1;
6014 bool IsSplat = true;
6015 unsigned NumNonConsts = 0;
6016 unsigned NumConsts = 0;
6017 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6018 SDValue In = Op.getOperand(idx);
6019 if (In.getOpcode() == ISD::UNDEF)
6021 if (!isa<ConstantSDNode>(In)) {
6022 AllContants = false;
6028 if (cast<ConstantSDNode>(In)->getZExtValue())
6029 Immediate |= (1ULL << idx);
6031 if (In != Op.getOperand(0))
6036 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6037 DAG.getConstant(Immediate, MVT::i16));
6038 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6039 DAG.getIntPtrConstant(0));
6042 if (NumNonConsts == 1 && NonConstIdx != 0) {
6045 SDValue VecAsImm = DAG.getConstant(Immediate,
6046 MVT::getIntegerVT(VT.getSizeInBits()));
6047 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6050 DstVec = DAG.getUNDEF(VT);
6051 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6052 Op.getOperand(NonConstIdx),
6053 DAG.getIntPtrConstant(NonConstIdx));
6055 if (!IsSplat && (NonConstIdx != 0))
6056 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6057 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6060 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6061 DAG.getConstant(-1, SelectVT),
6062 DAG.getConstant(0, SelectVT));
6064 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6065 DAG.getConstant((Immediate | 1), SelectVT),
6066 DAG.getConstant(Immediate, SelectVT));
6067 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6070 /// \brief Return true if \p N implements a horizontal binop and return the
6071 /// operands for the horizontal binop into V0 and V1.
6073 /// This is a helper function of PerformBUILD_VECTORCombine.
6074 /// This function checks that the build_vector \p N in input implements a
6075 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6076 /// operation to match.
6077 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6078 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6079 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6082 /// This function only analyzes elements of \p N whose indices are
6083 /// in range [BaseIdx, LastIdx).
6084 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6086 unsigned BaseIdx, unsigned LastIdx,
6087 SDValue &V0, SDValue &V1) {
6088 EVT VT = N->getValueType(0);
6090 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6091 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6092 "Invalid Vector in input!");
6094 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6095 bool CanFold = true;
6096 unsigned ExpectedVExtractIdx = BaseIdx;
6097 unsigned NumElts = LastIdx - BaseIdx;
6098 V0 = DAG.getUNDEF(VT);
6099 V1 = DAG.getUNDEF(VT);
6101 // Check if N implements a horizontal binop.
6102 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6103 SDValue Op = N->getOperand(i + BaseIdx);
6106 if (Op->getOpcode() == ISD::UNDEF) {
6107 // Update the expected vector extract index.
6108 if (i * 2 == NumElts)
6109 ExpectedVExtractIdx = BaseIdx;
6110 ExpectedVExtractIdx += 2;
6114 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6119 SDValue Op0 = Op.getOperand(0);
6120 SDValue Op1 = Op.getOperand(1);
6122 // Try to match the following pattern:
6123 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6124 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6125 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6126 Op0.getOperand(0) == Op1.getOperand(0) &&
6127 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6128 isa<ConstantSDNode>(Op1.getOperand(1)));
6132 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6133 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6135 if (i * 2 < NumElts) {
6136 if (V0.getOpcode() == ISD::UNDEF)
6137 V0 = Op0.getOperand(0);
6139 if (V1.getOpcode() == ISD::UNDEF)
6140 V1 = Op0.getOperand(0);
6141 if (i * 2 == NumElts)
6142 ExpectedVExtractIdx = BaseIdx;
6145 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6146 if (I0 == ExpectedVExtractIdx)
6147 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6148 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6149 // Try to match the following dag sequence:
6150 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6151 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6155 ExpectedVExtractIdx += 2;
6161 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6162 /// a concat_vector.
6164 /// This is a helper function of PerformBUILD_VECTORCombine.
6165 /// This function expects two 256-bit vectors called V0 and V1.
6166 /// At first, each vector is split into two separate 128-bit vectors.
6167 /// Then, the resulting 128-bit vectors are used to implement two
6168 /// horizontal binary operations.
6170 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6172 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6173 /// the two new horizontal binop.
6174 /// When Mode is set, the first horizontal binop dag node would take as input
6175 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6176 /// horizontal binop dag node would take as input the lower 128-bit of V1
6177 /// and the upper 128-bit of V1.
6179 /// HADD V0_LO, V0_HI
6180 /// HADD V1_LO, V1_HI
6182 /// Otherwise, the first horizontal binop dag node takes as input the lower
6183 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6184 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6186 /// HADD V0_LO, V1_LO
6187 /// HADD V0_HI, V1_HI
6189 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6190 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6191 /// the upper 128-bits of the result.
6192 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6193 SDLoc DL, SelectionDAG &DAG,
6194 unsigned X86Opcode, bool Mode,
6195 bool isUndefLO, bool isUndefHI) {
6196 EVT VT = V0.getValueType();
6197 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6198 "Invalid nodes in input!");
6200 unsigned NumElts = VT.getVectorNumElements();
6201 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6202 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6203 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6204 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6205 EVT NewVT = V0_LO.getValueType();
6207 SDValue LO = DAG.getUNDEF(NewVT);
6208 SDValue HI = DAG.getUNDEF(NewVT);
6211 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6212 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6213 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6214 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6215 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6217 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6218 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6219 V1_LO->getOpcode() != ISD::UNDEF))
6220 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6222 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6223 V1_HI->getOpcode() != ISD::UNDEF))
6224 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6227 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6230 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6231 /// sequence of 'vadd + vsub + blendi'.
6232 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6233 const X86Subtarget *Subtarget) {
6235 EVT VT = BV->getValueType(0);
6236 unsigned NumElts = VT.getVectorNumElements();
6237 SDValue InVec0 = DAG.getUNDEF(VT);
6238 SDValue InVec1 = DAG.getUNDEF(VT);
6240 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6241 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6243 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6245 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6248 // Odd-numbered elements in the input build vector are obtained from
6249 // adding two integer/float elements.
6250 // Even-numbered elements in the input build vector are obtained from
6251 // subtracting two integer/float elements.
6252 unsigned ExpectedOpcode = ISD::FSUB;
6253 unsigned NextExpectedOpcode = ISD::FADD;
6254 bool AddFound = false;
6255 bool SubFound = false;
6257 for (unsigned i = 0, e = NumElts; i != e; i++) {
6258 SDValue Op = BV->getOperand(i);
6260 // Skip 'undef' values.
6261 unsigned Opcode = Op.getOpcode();
6262 if (Opcode == ISD::UNDEF) {
6263 std::swap(ExpectedOpcode, NextExpectedOpcode);
6267 // Early exit if we found an unexpected opcode.
6268 if (Opcode != ExpectedOpcode)
6271 SDValue Op0 = Op.getOperand(0);
6272 SDValue Op1 = Op.getOperand(1);
6274 // Try to match the following pattern:
6275 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6276 // Early exit if we cannot match that sequence.
6277 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6278 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6279 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6280 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6281 Op0.getOperand(1) != Op1.getOperand(1))
6284 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6288 // We found a valid add/sub node. Update the information accordingly.
6294 // Update InVec0 and InVec1.
6295 if (InVec0.getOpcode() == ISD::UNDEF)
6296 InVec0 = Op0.getOperand(0);
6297 if (InVec1.getOpcode() == ISD::UNDEF)
6298 InVec1 = Op1.getOperand(0);
6300 // Make sure that operands in input to each add/sub node always
6301 // come from a same pair of vectors.
6302 if (InVec0 != Op0.getOperand(0)) {
6303 if (ExpectedOpcode == ISD::FSUB)
6306 // FADD is commutable. Try to commute the operands
6307 // and then test again.
6308 std::swap(Op0, Op1);
6309 if (InVec0 != Op0.getOperand(0))
6313 if (InVec1 != Op1.getOperand(0))
6316 // Update the pair of expected opcodes.
6317 std::swap(ExpectedOpcode, NextExpectedOpcode);
6320 // Don't try to fold this build_vector into a VSELECT if it has
6321 // too many UNDEF operands.
6322 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6323 InVec1.getOpcode() != ISD::UNDEF) {
6324 // Emit a sequence of vector add and sub followed by a VSELECT.
6325 // The new VSELECT will be lowered into a BLENDI.
6326 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6327 // and emit a single ADDSUB instruction.
6328 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6329 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6331 // Construct the VSELECT mask.
6332 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6333 EVT SVT = MaskVT.getVectorElementType();
6334 unsigned SVTBits = SVT.getSizeInBits();
6335 SmallVector<SDValue, 8> Ops;
6337 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6338 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6339 APInt::getAllOnesValue(SVTBits);
6340 SDValue Constant = DAG.getConstant(Value, SVT);
6341 Ops.push_back(Constant);
6344 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6345 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6351 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6352 const X86Subtarget *Subtarget) {
6354 EVT VT = N->getValueType(0);
6355 unsigned NumElts = VT.getVectorNumElements();
6356 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6357 SDValue InVec0, InVec1;
6359 // Try to match an ADDSUB.
6360 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6361 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6362 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6363 if (Value.getNode())
6367 // Try to match horizontal ADD/SUB.
6368 unsigned NumUndefsLO = 0;
6369 unsigned NumUndefsHI = 0;
6370 unsigned Half = NumElts/2;
6372 // Count the number of UNDEF operands in the build_vector in input.
6373 for (unsigned i = 0, e = Half; i != e; ++i)
6374 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6377 for (unsigned i = Half, e = NumElts; i != e; ++i)
6378 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6381 // Early exit if this is either a build_vector of all UNDEFs or all the
6382 // operands but one are UNDEF.
6383 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6386 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6387 // Try to match an SSE3 float HADD/HSUB.
6388 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6389 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6391 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6392 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6393 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6394 // Try to match an SSSE3 integer HADD/HSUB.
6395 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6396 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6398 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6399 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6402 if (!Subtarget->hasAVX())
6405 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6406 // Try to match an AVX horizontal add/sub of packed single/double
6407 // precision floating point values from 256-bit vectors.
6408 SDValue InVec2, InVec3;
6409 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6410 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6411 ((InVec0.getOpcode() == ISD::UNDEF ||
6412 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6413 ((InVec1.getOpcode() == ISD::UNDEF ||
6414 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6415 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6417 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6418 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6419 ((InVec0.getOpcode() == ISD::UNDEF ||
6420 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6421 ((InVec1.getOpcode() == ISD::UNDEF ||
6422 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6423 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6424 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6425 // Try to match an AVX2 horizontal add/sub of signed integers.
6426 SDValue InVec2, InVec3;
6428 bool CanFold = true;
6430 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6431 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6432 ((InVec0.getOpcode() == ISD::UNDEF ||
6433 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6434 ((InVec1.getOpcode() == ISD::UNDEF ||
6435 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6436 X86Opcode = X86ISD::HADD;
6437 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6438 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6439 ((InVec0.getOpcode() == ISD::UNDEF ||
6440 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6441 ((InVec1.getOpcode() == ISD::UNDEF ||
6442 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6443 X86Opcode = X86ISD::HSUB;
6448 // Fold this build_vector into a single horizontal add/sub.
6449 // Do this only if the target has AVX2.
6450 if (Subtarget->hasAVX2())
6451 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6453 // Do not try to expand this build_vector into a pair of horizontal
6454 // add/sub if we can emit a pair of scalar add/sub.
6455 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6458 // Convert this build_vector into a pair of horizontal binop followed by
6460 bool isUndefLO = NumUndefsLO == Half;
6461 bool isUndefHI = NumUndefsHI == Half;
6462 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6463 isUndefLO, isUndefHI);
6467 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6468 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6470 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6471 X86Opcode = X86ISD::HADD;
6472 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6473 X86Opcode = X86ISD::HSUB;
6474 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6475 X86Opcode = X86ISD::FHADD;
6476 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6477 X86Opcode = X86ISD::FHSUB;
6481 // Don't try to expand this build_vector into a pair of horizontal add/sub
6482 // if we can simply emit a pair of scalar add/sub.
6483 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6486 // Convert this build_vector into two horizontal add/sub followed by
6488 bool isUndefLO = NumUndefsLO == Half;
6489 bool isUndefHI = NumUndefsHI == Half;
6490 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6491 isUndefLO, isUndefHI);
6498 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6501 MVT VT = Op.getSimpleValueType();
6502 MVT ExtVT = VT.getVectorElementType();
6503 unsigned NumElems = Op.getNumOperands();
6505 // Generate vectors for predicate vectors.
6506 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6507 return LowerBUILD_VECTORvXi1(Op, DAG);
6509 // Vectors containing all zeros can be matched by pxor and xorps later
6510 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6511 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6512 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6513 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6516 return getZeroVector(VT, Subtarget, DAG, dl);
6519 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6520 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6521 // vpcmpeqd on 256-bit vectors.
6522 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6523 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6526 if (!VT.is512BitVector())
6527 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6530 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6531 if (Broadcast.getNode())
6534 unsigned EVTBits = ExtVT.getSizeInBits();
6536 unsigned NumZero = 0;
6537 unsigned NumNonZero = 0;
6538 unsigned NonZeros = 0;
6539 bool IsAllConstants = true;
6540 SmallSet<SDValue, 8> Values;
6541 for (unsigned i = 0; i < NumElems; ++i) {
6542 SDValue Elt = Op.getOperand(i);
6543 if (Elt.getOpcode() == ISD::UNDEF)
6546 if (Elt.getOpcode() != ISD::Constant &&
6547 Elt.getOpcode() != ISD::ConstantFP)
6548 IsAllConstants = false;
6549 if (X86::isZeroNode(Elt))
6552 NonZeros |= (1 << i);
6557 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6558 if (NumNonZero == 0)
6559 return DAG.getUNDEF(VT);
6561 // Special case for single non-zero, non-undef, element.
6562 if (NumNonZero == 1) {
6563 unsigned Idx = countTrailingZeros(NonZeros);
6564 SDValue Item = Op.getOperand(Idx);
6566 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6567 // the value are obviously zero, truncate the value to i32 and do the
6568 // insertion that way. Only do this if the value is non-constant or if the
6569 // value is a constant being inserted into element 0. It is cheaper to do
6570 // a constant pool load than it is to do a movd + shuffle.
6571 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6572 (!IsAllConstants || Idx == 0)) {
6573 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6575 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6576 EVT VecVT = MVT::v4i32;
6577 unsigned VecElts = 4;
6579 // Truncate the value (which may itself be a constant) to i32, and
6580 // convert it to a vector with movd (S2V+shuffle to zero extend).
6581 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6582 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6583 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6585 // Now we have our 32-bit value zero extended in the low element of
6586 // a vector. If Idx != 0, swizzle it into place.
6588 SmallVector<int, 4> Mask;
6589 Mask.push_back(Idx);
6590 for (unsigned i = 1; i != VecElts; ++i)
6592 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6595 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6599 // If we have a constant or non-constant insertion into the low element of
6600 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6601 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6602 // depending on what the source datatype is.
6605 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6607 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6608 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6609 if (VT.is256BitVector() || VT.is512BitVector()) {
6610 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6611 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6612 Item, DAG.getIntPtrConstant(0));
6614 assert(VT.is128BitVector() && "Expected an SSE value type!");
6615 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6616 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6617 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6620 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6621 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6622 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6623 if (VT.is256BitVector()) {
6624 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6625 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6627 assert(VT.is128BitVector() && "Expected an SSE value type!");
6628 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6630 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6634 // Is it a vector logical left shift?
6635 if (NumElems == 2 && Idx == 1 &&
6636 X86::isZeroNode(Op.getOperand(0)) &&
6637 !X86::isZeroNode(Op.getOperand(1))) {
6638 unsigned NumBits = VT.getSizeInBits();
6639 return getVShift(true, VT,
6640 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6641 VT, Op.getOperand(1)),
6642 NumBits/2, DAG, *this, dl);
6645 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6648 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6649 // is a non-constant being inserted into an element other than the low one,
6650 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6651 // movd/movss) to move this into the low element, then shuffle it into
6653 if (EVTBits == 32) {
6654 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6656 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6657 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6658 SmallVector<int, 8> MaskVec;
6659 for (unsigned i = 0; i != NumElems; ++i)
6660 MaskVec.push_back(i == Idx ? 0 : 1);
6661 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6665 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6666 if (Values.size() == 1) {
6667 if (EVTBits == 32) {
6668 // Instead of a shuffle like this:
6669 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6670 // Check if it's possible to issue this instead.
6671 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6672 unsigned Idx = countTrailingZeros(NonZeros);
6673 SDValue Item = Op.getOperand(Idx);
6674 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6675 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6680 // A vector full of immediates; various special cases are already
6681 // handled, so this is best done with a single constant-pool load.
6685 // For AVX-length vectors, build the individual 128-bit pieces and use
6686 // shuffles to put them in place.
6687 if (VT.is256BitVector() || VT.is512BitVector()) {
6688 SmallVector<SDValue, 64> V;
6689 for (unsigned i = 0; i != NumElems; ++i)
6690 V.push_back(Op.getOperand(i));
6692 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6694 // Build both the lower and upper subvector.
6695 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6696 makeArrayRef(&V[0], NumElems/2));
6697 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6698 makeArrayRef(&V[NumElems / 2], NumElems/2));
6700 // Recreate the wider vector with the lower and upper part.
6701 if (VT.is256BitVector())
6702 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6703 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6706 // Let legalizer expand 2-wide build_vectors.
6707 if (EVTBits == 64) {
6708 if (NumNonZero == 1) {
6709 // One half is zero or undef.
6710 unsigned Idx = countTrailingZeros(NonZeros);
6711 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6712 Op.getOperand(Idx));
6713 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6718 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6719 if (EVTBits == 8 && NumElems == 16) {
6720 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6722 if (V.getNode()) return V;
6725 if (EVTBits == 16 && NumElems == 8) {
6726 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6728 if (V.getNode()) return V;
6731 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6732 if (EVTBits == 32 && NumElems == 4) {
6733 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6734 NumZero, DAG, Subtarget, *this);
6739 // If element VT is == 32 bits, turn it into a number of shuffles.
6740 SmallVector<SDValue, 8> V(NumElems);
6741 if (NumElems == 4 && NumZero > 0) {
6742 for (unsigned i = 0; i < 4; ++i) {
6743 bool isZero = !(NonZeros & (1 << i));
6745 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6747 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6750 for (unsigned i = 0; i < 2; ++i) {
6751 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6754 V[i] = V[i*2]; // Must be a zero vector.
6757 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6760 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6763 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6768 bool Reverse1 = (NonZeros & 0x3) == 2;
6769 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6773 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6774 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6776 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6779 if (Values.size() > 1 && VT.is128BitVector()) {
6780 // Check for a build vector of consecutive loads.
6781 for (unsigned i = 0; i < NumElems; ++i)
6782 V[i] = Op.getOperand(i);
6784 // Check for elements which are consecutive loads.
6785 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6789 // Check for a build vector from mostly shuffle plus few inserting.
6790 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6794 // For SSE 4.1, use insertps to put the high elements into the low element.
6795 if (getSubtarget()->hasSSE41()) {
6797 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6798 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6800 Result = DAG.getUNDEF(VT);
6802 for (unsigned i = 1; i < NumElems; ++i) {
6803 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6804 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6805 Op.getOperand(i), DAG.getIntPtrConstant(i));
6810 // Otherwise, expand into a number of unpckl*, start by extending each of
6811 // our (non-undef) elements to the full vector width with the element in the
6812 // bottom slot of the vector (which generates no code for SSE).
6813 for (unsigned i = 0; i < NumElems; ++i) {
6814 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6815 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6817 V[i] = DAG.getUNDEF(VT);
6820 // Next, we iteratively mix elements, e.g. for v4f32:
6821 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6822 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6823 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6824 unsigned EltStride = NumElems >> 1;
6825 while (EltStride != 0) {
6826 for (unsigned i = 0; i < EltStride; ++i) {
6827 // If V[i+EltStride] is undef and this is the first round of mixing,
6828 // then it is safe to just drop this shuffle: V[i] is already in the
6829 // right place, the one element (since it's the first round) being
6830 // inserted as undef can be dropped. This isn't safe for successive
6831 // rounds because they will permute elements within both vectors.
6832 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6833 EltStride == NumElems/2)
6836 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6845 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6846 // to create 256-bit vectors from two other 128-bit ones.
6847 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6849 MVT ResVT = Op.getSimpleValueType();
6851 assert((ResVT.is256BitVector() ||
6852 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6854 SDValue V1 = Op.getOperand(0);
6855 SDValue V2 = Op.getOperand(1);
6856 unsigned NumElems = ResVT.getVectorNumElements();
6857 if(ResVT.is256BitVector())
6858 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6860 if (Op.getNumOperands() == 4) {
6861 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6862 ResVT.getVectorNumElements()/2);
6863 SDValue V3 = Op.getOperand(2);
6864 SDValue V4 = Op.getOperand(3);
6865 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6866 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6868 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6871 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6872 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6873 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6874 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6875 Op.getNumOperands() == 4)));
6877 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6878 // from two other 128-bit ones.
6880 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6881 return LowerAVXCONCAT_VECTORS(Op, DAG);
6885 //===----------------------------------------------------------------------===//
6886 // Vector shuffle lowering
6888 // This is an experimental code path for lowering vector shuffles on x86. It is
6889 // designed to handle arbitrary vector shuffles and blends, gracefully
6890 // degrading performance as necessary. It works hard to recognize idiomatic
6891 // shuffles and lower them to optimal instruction patterns without leaving
6892 // a framework that allows reasonably efficient handling of all vector shuffle
6894 //===----------------------------------------------------------------------===//
6896 /// \brief Tiny helper function to identify a no-op mask.
6898 /// This is a somewhat boring predicate function. It checks whether the mask
6899 /// array input, which is assumed to be a single-input shuffle mask of the kind
6900 /// used by the X86 shuffle instructions (not a fully general
6901 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6902 /// in-place shuffle are 'no-op's.
6903 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6904 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6905 if (Mask[i] != -1 && Mask[i] != i)
6910 /// \brief Helper function to classify a mask as a single-input mask.
6912 /// This isn't a generic single-input test because in the vector shuffle
6913 /// lowering we canonicalize single inputs to be the first input operand. This
6914 /// means we can more quickly test for a single input by only checking whether
6915 /// an input from the second operand exists. We also assume that the size of
6916 /// mask corresponds to the size of the input vectors which isn't true in the
6917 /// fully general case.
6918 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6920 if (M >= (int)Mask.size())
6925 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6927 /// This helper function produces an 8-bit shuffle immediate corresponding to
6928 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6929 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6932 /// NB: We rely heavily on "undef" masks preserving the input lane.
6933 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6934 SelectionDAG &DAG) {
6935 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6936 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6937 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6938 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6939 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6942 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6943 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6944 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6945 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6946 return DAG.getConstant(Imm, MVT::i8);
6949 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6951 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6952 /// support for floating point shuffles but not integer shuffles. These
6953 /// instructions will incur a domain crossing penalty on some chips though so
6954 /// it is better to avoid lowering through this for integer vectors where
6956 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6957 const X86Subtarget *Subtarget,
6958 SelectionDAG &DAG) {
6960 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6961 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6962 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6963 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6964 ArrayRef<int> Mask = SVOp->getMask();
6965 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6967 if (isSingleInputShuffleMask(Mask)) {
6968 // Straight shuffle of a single input vector. Simulate this by using the
6969 // single input as both of the "inputs" to this instruction..
6970 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6971 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6972 DAG.getConstant(SHUFPDMask, MVT::i8));
6974 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6975 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6977 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6978 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6979 DAG.getConstant(SHUFPDMask, MVT::i8));
6982 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6984 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6985 /// the integer unit to minimize domain crossing penalties. However, for blends
6986 /// it falls back to the floating point shuffle operation with appropriate bit
6988 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6989 const X86Subtarget *Subtarget,
6990 SelectionDAG &DAG) {
6992 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6993 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6994 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6995 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6996 ArrayRef<int> Mask = SVOp->getMask();
6997 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6999 if (isSingleInputShuffleMask(Mask)) {
7000 // Straight shuffle of a single input vector. For everything from SSE2
7001 // onward this has a single fast instruction with no scary immediates.
7002 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7003 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7004 int WidenedMask[4] = {
7005 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7006 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7008 ISD::BITCAST, DL, MVT::v2i64,
7009 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7010 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7013 // We implement this with SHUFPD which is pretty lame because it will likely
7014 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7015 // However, all the alternatives are still more cycles and newer chips don't
7016 // have this problem. It would be really nice if x86 had better shuffles here.
7017 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7018 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7019 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7020 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7023 /// \brief Lower 4-lane 32-bit floating point shuffles.
7025 /// Uses instructions exclusively from the floating point unit to minimize
7026 /// domain crossing penalties, as these are sufficient to implement all v4f32
7028 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7029 const X86Subtarget *Subtarget,
7030 SelectionDAG &DAG) {
7032 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7033 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7034 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7035 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7036 ArrayRef<int> Mask = SVOp->getMask();
7037 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7039 SDValue LowV = V1, HighV = V2;
7040 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7043 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7045 if (NumV2Elements == 0)
7046 // Straight shuffle of a single input vector. We pass the input vector to
7047 // both operands to simulate this with a SHUFPS.
7048 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7049 getV4X86ShuffleImm8ForMask(Mask, DAG));
7051 if (NumV2Elements == 1) {
7053 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7055 // Compute the index adjacent to V2Index and in the same half by toggling
7057 int V2AdjIndex = V2Index ^ 1;
7059 if (Mask[V2AdjIndex] == -1) {
7060 // Handles all the cases where we have a single V2 element and an undef.
7061 // This will only ever happen in the high lanes because we commute the
7062 // vector otherwise.
7064 std::swap(LowV, HighV);
7065 NewMask[V2Index] -= 4;
7067 // Handle the case where the V2 element ends up adjacent to a V1 element.
7068 // To make this work, blend them together as the first step.
7069 int V1Index = V2AdjIndex;
7070 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7071 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7072 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7074 // Now proceed to reconstruct the final blend as we have the necessary
7075 // high or low half formed.
7082 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7083 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7085 } else if (NumV2Elements == 2) {
7086 if (Mask[0] < 4 && Mask[1] < 4) {
7087 // Handle the easy case where we have V1 in the low lanes and V2 in the
7088 // high lanes. We never see this reversed because we sort the shuffle.
7092 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7093 // trying to place elements directly, just blend them and set up the final
7094 // shuffle to place them.
7096 // The first two blend mask elements are for V1, the second two are for
7098 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7099 Mask[2] < 4 ? Mask[2] : Mask[3],
7100 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7101 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7102 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7103 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7105 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7108 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7109 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7110 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7111 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7114 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7115 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7118 /// \brief Lower 4-lane i32 vector shuffles.
7120 /// We try to handle these with integer-domain shuffles where we can, but for
7121 /// blends we use the floating point domain blend instructions.
7122 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7123 const X86Subtarget *Subtarget,
7124 SelectionDAG &DAG) {
7126 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7127 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7128 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7129 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7130 ArrayRef<int> Mask = SVOp->getMask();
7131 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7133 if (isSingleInputShuffleMask(Mask))
7134 // Straight shuffle of a single input vector. For everything from SSE2
7135 // onward this has a single fast instruction with no scary immediates.
7136 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7137 getV4X86ShuffleImm8ForMask(Mask, DAG));
7139 // We implement this with SHUFPS because it can blend from two vectors.
7140 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7141 // up the inputs, bypassing domain shift penalties that we would encur if we
7142 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7144 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7145 DAG.getVectorShuffle(
7147 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7148 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7151 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7152 /// shuffle lowering, and the most complex part.
7154 /// The lowering strategy is to try to form pairs of input lanes which are
7155 /// targeted at the same half of the final vector, and then use a dword shuffle
7156 /// to place them onto the right half, and finally unpack the paired lanes into
7157 /// their final position.
7159 /// The exact breakdown of how to form these dword pairs and align them on the
7160 /// correct sides is really tricky. See the comments within the function for
7161 /// more of the details.
7162 static SDValue lowerV8I16SingleInputVectorShuffle(
7163 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7164 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7165 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7166 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7167 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7169 SmallVector<int, 4> LoInputs;
7170 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7171 [](int M) { return M >= 0; });
7172 std::sort(LoInputs.begin(), LoInputs.end());
7173 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7174 SmallVector<int, 4> HiInputs;
7175 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7176 [](int M) { return M >= 0; });
7177 std::sort(HiInputs.begin(), HiInputs.end());
7178 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7180 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7181 int NumHToL = LoInputs.size() - NumLToL;
7183 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7184 int NumHToH = HiInputs.size() - NumLToH;
7185 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7186 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7187 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7188 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7190 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7191 // such inputs we can swap two of the dwords across the half mark and end up
7192 // with <=2 inputs to each half in each half. Once there, we can fall through
7193 // to the generic code below. For example:
7195 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7196 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7198 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7200 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7201 int ThreeInputHalfSum, int OneInputHalfOffset) {
7202 // Compute the index of dword with only one word among the three inputs in
7203 // a half by taking the sum of the half with three inputs and subtracting
7204 // the sum of the actual three inputs. The difference is the remaining
7206 int DWordA = (ThreeInputHalfSum -
7207 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7209 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7211 int PSHUFDMask[] = {0, 1, 2, 3};
7212 PSHUFDMask[DWordA] = DWordB;
7213 PSHUFDMask[DWordB] = DWordA;
7214 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7215 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7216 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7217 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7219 // Adjust the mask to match the new locations of A and B.
7221 if (M != -1 && M/2 == DWordA)
7222 M = 2 * DWordB + M % 2;
7223 else if (M != -1 && M/2 == DWordB)
7224 M = 2 * DWordA + M % 2;
7226 // Recurse back into this routine to re-compute state now that this isn't
7227 // a 3 and 1 problem.
7228 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7231 if (NumLToL == 3 && NumHToL == 1)
7232 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7233 else if (NumLToL == 1 && NumHToL == 3)
7234 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7235 else if (NumLToH == 1 && NumHToH == 3)
7236 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7237 else if (NumLToH == 3 && NumHToH == 1)
7238 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7240 // At this point there are at most two inputs to the low and high halves from
7241 // each half. That means the inputs can always be grouped into dwords and
7242 // those dwords can then be moved to the correct half with a dword shuffle.
7243 // We use at most one low and one high word shuffle to collect these paired
7244 // inputs into dwords, and finally a dword shuffle to place them.
7245 int PSHUFLMask[4] = {-1, -1, -1, -1};
7246 int PSHUFHMask[4] = {-1, -1, -1, -1};
7247 int PSHUFDMask[4] = {-1, -1, -1, -1};
7249 // First fix the masks for all the inputs that are staying in their
7250 // original halves. This will then dictate the targets of the cross-half
7252 auto fixInPlaceInputs = [&PSHUFDMask](
7253 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7254 MutableArrayRef<int> HalfMask, int HalfOffset) {
7255 if (InPlaceInputs.empty())
7257 if (InPlaceInputs.size() == 1) {
7258 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7259 InPlaceInputs[0] - HalfOffset;
7260 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7264 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7265 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7266 InPlaceInputs[0] - HalfOffset;
7267 // Put the second input next to the first so that they are packed into
7268 // a dword. We find the adjacent index by toggling the low bit.
7269 int AdjIndex = InPlaceInputs[0] ^ 1;
7270 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7271 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7272 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7274 if (!HToLInputs.empty())
7275 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7276 if (!LToHInputs.empty())
7277 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7279 // Now gather the cross-half inputs and place them into a free dword of
7280 // their target half.
7281 // FIXME: This operation could almost certainly be simplified dramatically to
7282 // look more like the 3-1 fixing operation.
7283 auto moveInputsToRightHalf = [&PSHUFDMask](
7284 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7285 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7286 int SourceOffset, int DestOffset) {
7287 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7288 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7290 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7292 int LowWord = Word & ~1;
7293 int HighWord = Word | 1;
7294 return isWordClobbered(SourceHalfMask, LowWord) ||
7295 isWordClobbered(SourceHalfMask, HighWord);
7298 if (IncomingInputs.empty())
7301 if (ExistingInputs.empty()) {
7302 // Map any dwords with inputs from them into the right half.
7303 for (int Input : IncomingInputs) {
7304 // If the source half mask maps over the inputs, turn those into
7305 // swaps and use the swapped lane.
7306 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7307 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7308 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7309 Input - SourceOffset;
7310 // We have to swap the uses in our half mask in one sweep.
7311 for (int &M : HalfMask)
7312 if (M == SourceHalfMask[Input - SourceOffset])
7314 else if (M == Input)
7315 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7317 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7318 Input - SourceOffset &&
7319 "Previous placement doesn't match!");
7321 // Note that this correctly re-maps both when we do a swap and when
7322 // we observe the other side of the swap above. We rely on that to
7323 // avoid swapping the members of the input list directly.
7324 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7327 // Map the input's dword into the correct half.
7328 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7329 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7331 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7333 "Previous placement doesn't match!");
7336 // And just directly shift any other-half mask elements to be same-half
7337 // as we will have mirrored the dword containing the element into the
7338 // same position within that half.
7339 for (int &M : HalfMask)
7340 if (M >= SourceOffset && M < SourceOffset + 4) {
7341 M = M - SourceOffset + DestOffset;
7342 assert(M >= 0 && "This should never wrap below zero!");
7347 // Ensure we have the input in a viable dword of its current half. This
7348 // is particularly tricky because the original position may be clobbered
7349 // by inputs being moved and *staying* in that half.
7350 if (IncomingInputs.size() == 1) {
7351 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7352 int InputFixed = std::find(std::begin(SourceHalfMask),
7353 std::end(SourceHalfMask), -1) -
7354 std::begin(SourceHalfMask) + SourceOffset;
7355 SourceHalfMask[InputFixed - SourceOffset] =
7356 IncomingInputs[0] - SourceOffset;
7357 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7359 IncomingInputs[0] = InputFixed;
7361 } else if (IncomingInputs.size() == 2) {
7362 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7363 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7364 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7365 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7366 "Not all dwords can be clobbered!");
7367 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7368 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7369 for (int &M : HalfMask)
7370 if (M == IncomingInputs[0])
7371 M = SourceDWordBase + SourceOffset;
7372 else if (M == IncomingInputs[1])
7373 M = SourceDWordBase + 1 + SourceOffset;
7374 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7375 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7378 llvm_unreachable("Unhandled input size!");
7381 // Now hoist the DWord down to the right half.
7382 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7383 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7384 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7385 for (int Input : IncomingInputs)
7386 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7387 FreeDWord * 2 + Input % 2);
7389 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7390 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7391 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7392 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7394 // Now enact all the shuffles we've computed to move the inputs into their
7396 if (!isNoopShuffleMask(PSHUFLMask))
7397 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7398 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7399 if (!isNoopShuffleMask(PSHUFHMask))
7400 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7401 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7402 if (!isNoopShuffleMask(PSHUFDMask))
7403 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7404 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7405 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7406 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7408 // At this point, each half should contain all its inputs, and we can then
7409 // just shuffle them into their final position.
7410 assert(std::count_if(LoMask.begin(), LoMask.end(),
7411 [](int M) { return M >= 4; }) == 0 &&
7412 "Failed to lift all the high half inputs to the low mask!");
7413 assert(std::count_if(HiMask.begin(), HiMask.end(),
7414 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7415 "Failed to lift all the low half inputs to the high mask!");
7417 // Do a half shuffle for the low mask.
7418 if (!isNoopShuffleMask(LoMask))
7419 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7420 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7422 // Do a half shuffle with the high mask after shifting its values down.
7423 for (int &M : HiMask)
7426 if (!isNoopShuffleMask(HiMask))
7427 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7428 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7433 /// \brief Detect whether the mask pattern should be lowered through
7436 /// This essentially tests whether viewing the mask as an interleaving of two
7437 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7438 /// lowering it through interleaving is a significantly better strategy.
7439 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7440 int NumEvenInputs[2] = {0, 0};
7441 int NumOddInputs[2] = {0, 0};
7442 int NumLoInputs[2] = {0, 0};
7443 int NumHiInputs[2] = {0, 0};
7444 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7448 int InputIdx = Mask[i] >= Size;
7451 ++NumLoInputs[InputIdx];
7453 ++NumHiInputs[InputIdx];
7456 ++NumEvenInputs[InputIdx];
7458 ++NumOddInputs[InputIdx];
7461 // The minimum number of cross-input results for both the interleaved and
7462 // split cases. If interleaving results in fewer cross-input results, return
7464 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7465 NumEvenInputs[0] + NumOddInputs[1]);
7466 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7467 NumLoInputs[0] + NumHiInputs[1]);
7468 return InterleavedCrosses < SplitCrosses;
7471 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7473 /// This strategy only works when the inputs from each vector fit into a single
7474 /// half of that vector, and generally there are not so many inputs as to leave
7475 /// the in-place shuffles required highly constrained (and thus expensive). It
7476 /// shifts all the inputs into a single side of both input vectors and then
7477 /// uses an unpack to interleave these inputs in a single vector. At that
7478 /// point, we will fall back on the generic single input shuffle lowering.
7479 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7481 MutableArrayRef<int> Mask,
7482 const X86Subtarget *Subtarget,
7483 SelectionDAG &DAG) {
7484 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7485 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7486 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7487 for (int i = 0; i < 8; ++i)
7488 if (Mask[i] >= 0 && Mask[i] < 4)
7489 LoV1Inputs.push_back(i);
7490 else if (Mask[i] >= 4 && Mask[i] < 8)
7491 HiV1Inputs.push_back(i);
7492 else if (Mask[i] >= 8 && Mask[i] < 12)
7493 LoV2Inputs.push_back(i);
7494 else if (Mask[i] >= 12)
7495 HiV2Inputs.push_back(i);
7497 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7498 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7501 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7502 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7503 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7505 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7506 HiV1Inputs.size() + HiV2Inputs.size();
7508 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7509 ArrayRef<int> HiInputs, bool MoveToLo,
7511 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7512 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7513 if (BadInputs.empty())
7516 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7517 int MoveOffset = MoveToLo ? 0 : 4;
7519 if (GoodInputs.empty()) {
7520 for (int BadInput : BadInputs) {
7521 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7522 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7525 if (GoodInputs.size() == 2) {
7526 // If the low inputs are spread across two dwords, pack them into
7528 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7529 Mask[GoodInputs[0]] - MaskOffset;
7530 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7531 Mask[GoodInputs[1]] - MaskOffset;
7532 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7533 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7535 // Otherwise pin the low inputs.
7536 for (int GoodInput : GoodInputs)
7537 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7541 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7542 std::begin(MoveMask);
7543 assert(MoveMaskIdx >= MoveOffset && "Established above");
7545 if (BadInputs.size() == 2) {
7546 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7547 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7548 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7549 Mask[BadInputs[0]] - MaskOffset;
7550 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7551 Mask[BadInputs[1]] - MaskOffset;
7552 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7553 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7555 assert(BadInputs.size() == 1 && "All sizes handled");
7556 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7557 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7561 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7564 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7566 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7569 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7570 // cross-half traffic in the final shuffle.
7572 // Munge the mask to be a single-input mask after the unpack merges the
7576 M = 2 * (M % 4) + (M / 8);
7578 return DAG.getVectorShuffle(
7579 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7580 DL, MVT::v8i16, V1, V2),
7581 DAG.getUNDEF(MVT::v8i16), Mask);
7584 /// \brief Generic lowering of 8-lane i16 shuffles.
7586 /// This handles both single-input shuffles and combined shuffle/blends with
7587 /// two inputs. The single input shuffles are immediately delegated to
7588 /// a dedicated lowering routine.
7590 /// The blends are lowered in one of three fundamental ways. If there are few
7591 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7592 /// of the input is significantly cheaper when lowered as an interleaving of
7593 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7594 /// halves of the inputs separately (making them have relatively few inputs)
7595 /// and then concatenate them.
7596 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7597 const X86Subtarget *Subtarget,
7598 SelectionDAG &DAG) {
7600 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7601 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7602 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7603 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7604 ArrayRef<int> OrigMask = SVOp->getMask();
7605 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7606 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7607 MutableArrayRef<int> Mask(MaskStorage);
7609 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7611 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7612 auto isV2 = [](int M) { return M >= 8; };
7614 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7615 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7617 if (NumV2Inputs == 0)
7618 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7620 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7621 "to be V1-input shuffles.");
7623 if (NumV1Inputs + NumV2Inputs <= 4)
7624 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7626 // Check whether an interleaving lowering is likely to be more efficient.
7627 // This isn't perfect but it is a strong heuristic that tends to work well on
7628 // the kinds of shuffles that show up in practice.
7630 // FIXME: Handle 1x, 2x, and 4x interleaving.
7631 if (shouldLowerAsInterleaving(Mask)) {
7632 // FIXME: Figure out whether we should pack these into the low or high
7635 int EMask[8], OMask[8];
7636 for (int i = 0; i < 4; ++i) {
7637 EMask[i] = Mask[2*i];
7638 OMask[i] = Mask[2*i + 1];
7643 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7644 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7646 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7649 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7650 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7652 for (int i = 0; i < 4; ++i) {
7653 LoBlendMask[i] = Mask[i];
7654 HiBlendMask[i] = Mask[i + 4];
7657 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7658 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7659 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7660 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7662 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7663 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7666 /// \brief Generic lowering of v16i8 shuffles.
7668 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7669 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7670 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7671 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7673 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7674 const X86Subtarget *Subtarget,
7675 SelectionDAG &DAG) {
7677 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7678 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7679 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7681 ArrayRef<int> OrigMask = SVOp->getMask();
7682 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7683 int MaskStorage[16] = {
7684 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7685 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7686 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7687 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7688 MutableArrayRef<int> Mask(MaskStorage);
7689 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7690 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7692 // For single-input shuffles, there are some nicer lowering tricks we can use.
7693 if (isSingleInputShuffleMask(Mask)) {
7694 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7695 // Notably, this handles splat and partial-splat shuffles more efficiently.
7697 // FIXME: We should check for other patterns which can be widened into an
7698 // i16 shuffle as well.
7699 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7700 for (int i = 0; i < 16; i += 2) {
7701 if (Mask[i] != Mask[i + 1])
7706 if (canWidenViaDuplication(Mask)) {
7707 SmallVector<int, 4> LoInputs;
7708 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7709 [](int M) { return M >= 0 && M < 8; });
7710 std::sort(LoInputs.begin(), LoInputs.end());
7711 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7713 SmallVector<int, 4> HiInputs;
7714 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7715 [](int M) { return M >= 8; });
7716 std::sort(HiInputs.begin(), HiInputs.end());
7717 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7720 bool TargetLo = LoInputs.size() >= HiInputs.size();
7721 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7722 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7725 SmallDenseMap<int, int, 8> LaneMap;
7726 for (int i = 0; i < 16; ++i)
7728 for (int I : InPlaceInputs) {
7732 int FreeByteIdx = 0;
7733 int TargetOffset = TargetLo ? 0 : 8;
7734 for (int I : MovingInputs) {
7735 // Walk the free index into the byte mask until we find an unoccupied
7736 // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7737 // principle indicates that there *must* be a spot as we can only have
7738 // 8 duplicated inputs. We have to walk the index using modular
7739 // arithmetic to wrap around as necessary.
7740 // FIXME: We could do a much better job of picking an inexpensive slot
7741 // so this doesn't go through the worst case for the byte shuffle.
7742 for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7743 ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7745 assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7746 "Failed to find a free byte!");
7747 ByteMask[FreeByteIdx + TargetOffset] = I;
7748 LaneMap[I] = FreeByteIdx + TargetOffset;
7750 V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7756 // Unpack the bytes to form the i16s that will be shuffled into place.
7757 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7758 MVT::v16i8, V1, V1);
7760 int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7761 for (int i = 0; i < 16; i += 2) {
7763 I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7764 assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7766 return DAG.getVectorShuffle(MVT::v8i16, DL,
7767 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7768 DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7772 // Check whether an interleaving lowering is likely to be more efficient.
7773 // This isn't perfect but it is a strong heuristic that tends to work well on
7774 // the kinds of shuffles that show up in practice.
7776 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7777 if (shouldLowerAsInterleaving(Mask)) {
7778 // FIXME: Figure out whether we should pack these into the low or high
7781 int EMask[16], OMask[16];
7782 for (int i = 0; i < 8; ++i) {
7783 EMask[i] = Mask[2*i];
7784 OMask[i] = Mask[2*i + 1];
7789 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7790 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7792 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7794 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7796 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7797 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7799 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7800 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7802 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7803 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7805 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7806 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7808 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7809 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7810 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7811 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7813 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7814 MutableArrayRef<int> V1HalfBlendMask,
7815 MutableArrayRef<int> V2HalfBlendMask) {
7816 for (int i = 0; i < 8; ++i)
7817 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7818 V1HalfBlendMask[i] = HalfMask[i];
7820 } else if (HalfMask[i] >= 16) {
7821 V2HalfBlendMask[i] = HalfMask[i] - 16;
7822 HalfMask[i] = i + 8;
7825 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7826 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7828 SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7829 SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7830 SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7831 SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7833 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7834 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7836 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7839 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7841 /// This routine breaks down the specific type of 128-bit shuffle and
7842 /// dispatches to the lowering routines accordingly.
7843 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7844 MVT VT, const X86Subtarget *Subtarget,
7845 SelectionDAG &DAG) {
7846 switch (VT.SimpleTy) {
7848 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7850 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7852 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7854 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7856 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7858 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7861 llvm_unreachable("Unimplemented!");
7865 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7866 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7867 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7868 if (Mask[i] + 1 != Mask[i+1])
7874 /// \brief Top-level lowering for x86 vector shuffles.
7876 /// This handles decomposition, canonicalization, and lowering of all x86
7877 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7878 /// above in helper routines. The canonicalization attempts to widen shuffles
7879 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7880 /// s.t. only one of the two inputs needs to be tested, etc.
7881 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7882 SelectionDAG &DAG) {
7883 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7884 ArrayRef<int> Mask = SVOp->getMask();
7885 SDValue V1 = Op.getOperand(0);
7886 SDValue V2 = Op.getOperand(1);
7887 MVT VT = Op.getSimpleValueType();
7888 int NumElements = VT.getVectorNumElements();
7891 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7893 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7894 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7895 if (V1IsUndef && V2IsUndef)
7896 return DAG.getUNDEF(VT);
7898 // When we create a shuffle node we put the UNDEF node to second operand,
7899 // but in some cases the first operand may be transformed to UNDEF.
7900 // In this case we should just commute the node.
7902 return CommuteVectorShuffle(SVOp, DAG);
7904 // Check for non-undef masks pointing at an undef vector and make the masks
7905 // undef as well. This makes it easier to match the shuffle based solely on
7909 if (M >= NumElements) {
7910 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7911 for (int &M : NewMask)
7912 if (M >= NumElements)
7914 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7917 // Check for a shuffle of a splat, and return just the splat. While DAG
7918 // combining will do a similar transformation, this shows up with the
7919 // internally created shuffles and so we handle it specially here as we won't
7920 // have another chance to DAG-combine the generic shuffle instructions.
7924 // Look through any bitcasts. These can't change the size, just the number
7925 // of elements which we check later.
7926 while (V.getOpcode() == ISD::BITCAST)
7927 V = V->getOperand(0);
7929 // A splat should always show up as a build vector node.
7930 if (V.getOpcode() == ISD::BUILD_VECTOR) {
7932 bool AllSame = true;
7933 for (unsigned i = 0; i != V->getNumOperands(); ++i)
7934 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
7935 Base = V->getOperand(i);
7938 // Splat of <u, u, ..., u>, return <u, u, ..., u>
7941 for (unsigned i = 0; i != V->getNumOperands(); ++i)
7942 if (V->getOperand(i) != Base) {
7946 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
7947 // number of elements match or the value splatted is a zero constant.
7949 if (V.getValueType().getVectorNumElements() == (unsigned)NumElements)
7951 if (auto *C = dyn_cast<ConstantSDNode>(Base))
7952 if (C->isNullValue())
7958 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7959 // lanes but wider integers. We cap this to not form integers larger than i64
7960 // but it might be interesting to form i128 integers to handle flipping the
7961 // low and high halves of AVX 256-bit vectors.
7962 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7963 areAdjacentMasksSequential(Mask)) {
7964 SmallVector<int, 8> NewMask;
7965 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7966 NewMask.push_back(Mask[i] / 2);
7968 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7969 VT.getVectorNumElements() / 2);
7970 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7971 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7972 return DAG.getNode(ISD::BITCAST, dl, VT,
7973 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7976 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7977 for (int M : SVOp->getMask())
7980 else if (M < NumElements)
7985 // Commute the shuffle as needed such that more elements come from V1 than
7986 // V2. This allows us to match the shuffle pattern strictly on how many
7987 // elements come from V1 without handling the symmetric cases.
7988 if (NumV2Elements > NumV1Elements)
7989 return CommuteVectorShuffle(SVOp, DAG);
7991 // When the number of V1 and V2 elements are the same, try to minimize the
7992 // number of uses of V2 in the low half of the vector.
7993 if (NumV1Elements == NumV2Elements) {
7994 int LowV1Elements = 0, LowV2Elements = 0;
7995 for (int M : SVOp->getMask().slice(0, NumElements / 2))
7996 if (M >= NumElements)
8000 if (LowV2Elements > LowV1Elements)
8001 return CommuteVectorShuffle(SVOp, DAG);
8004 // For each vector width, delegate to a specialized lowering routine.
8005 if (VT.getSizeInBits() == 128)
8006 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8008 llvm_unreachable("Unimplemented!");
8012 //===----------------------------------------------------------------------===//
8013 // Legacy vector shuffle lowering
8015 // This code is the legacy code handling vector shuffles until the above
8016 // replaces its functionality and performance.
8017 //===----------------------------------------------------------------------===//
8019 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8020 bool hasInt256, unsigned *MaskOut = nullptr) {
8021 MVT EltVT = VT.getVectorElementType();
8023 // There is no blend with immediate in AVX-512.
8024 if (VT.is512BitVector())
8027 if (!hasSSE41 || EltVT == MVT::i8)
8029 if (!hasInt256 && VT == MVT::v16i16)
8032 unsigned MaskValue = 0;
8033 unsigned NumElems = VT.getVectorNumElements();
8034 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8035 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8036 unsigned NumElemsInLane = NumElems / NumLanes;
8038 // Blend for v16i16 should be symetric for the both lanes.
8039 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8041 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8042 int EltIdx = MaskVals[i];
8044 if ((EltIdx < 0 || EltIdx == (int)i) &&
8045 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8048 if (((unsigned)EltIdx == (i + NumElems)) &&
8049 (SndLaneEltIdx < 0 ||
8050 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8051 MaskValue |= (1 << i);
8057 *MaskOut = MaskValue;
8061 // Try to lower a shuffle node into a simple blend instruction.
8062 // This function assumes isBlendMask returns true for this
8063 // SuffleVectorSDNode
8064 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8066 const X86Subtarget *Subtarget,
8067 SelectionDAG &DAG) {
8068 MVT VT = SVOp->getSimpleValueType(0);
8069 MVT EltVT = VT.getVectorElementType();
8070 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8071 Subtarget->hasInt256() && "Trying to lower a "
8072 "VECTOR_SHUFFLE to a Blend but "
8073 "with the wrong mask"));
8074 SDValue V1 = SVOp->getOperand(0);
8075 SDValue V2 = SVOp->getOperand(1);
8077 unsigned NumElems = VT.getVectorNumElements();
8079 // Convert i32 vectors to floating point if it is not AVX2.
8080 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8082 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8083 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8085 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8086 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8089 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8090 DAG.getConstant(MaskValue, MVT::i32));
8091 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8094 /// In vector type \p VT, return true if the element at index \p InputIdx
8095 /// falls on a different 128-bit lane than \p OutputIdx.
8096 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8097 unsigned OutputIdx) {
8098 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8099 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8102 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8103 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8104 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8105 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8107 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8108 SelectionDAG &DAG) {
8109 MVT VT = V1.getSimpleValueType();
8110 assert(VT.is128BitVector() || VT.is256BitVector());
8112 MVT EltVT = VT.getVectorElementType();
8113 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8114 unsigned NumElts = VT.getVectorNumElements();
8116 SmallVector<SDValue, 32> PshufbMask;
8117 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8118 int InputIdx = MaskVals[OutputIdx];
8119 unsigned InputByteIdx;
8121 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8122 InputByteIdx = 0x80;
8124 // Cross lane is not allowed.
8125 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8127 InputByteIdx = InputIdx * EltSizeInBytes;
8128 // Index is an byte offset within the 128-bit lane.
8129 InputByteIdx &= 0xf;
8132 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8133 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8134 if (InputByteIdx != 0x80)
8139 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8141 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8142 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8143 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8146 // v8i16 shuffles - Prefer shuffles in the following order:
8147 // 1. [all] pshuflw, pshufhw, optional move
8148 // 2. [ssse3] 1 x pshufb
8149 // 3. [ssse3] 2 x pshufb + 1 x por
8150 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8152 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8153 SelectionDAG &DAG) {
8154 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8155 SDValue V1 = SVOp->getOperand(0);
8156 SDValue V2 = SVOp->getOperand(1);
8158 SmallVector<int, 8> MaskVals;
8160 // Determine if more than 1 of the words in each of the low and high quadwords
8161 // of the result come from the same quadword of one of the two inputs. Undef
8162 // mask values count as coming from any quadword, for better codegen.
8164 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8165 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8166 unsigned LoQuad[] = { 0, 0, 0, 0 };
8167 unsigned HiQuad[] = { 0, 0, 0, 0 };
8168 // Indices of quads used.
8169 std::bitset<4> InputQuads;
8170 for (unsigned i = 0; i < 8; ++i) {
8171 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8172 int EltIdx = SVOp->getMaskElt(i);
8173 MaskVals.push_back(EltIdx);
8182 InputQuads.set(EltIdx / 4);
8185 int BestLoQuad = -1;
8186 unsigned MaxQuad = 1;
8187 for (unsigned i = 0; i < 4; ++i) {
8188 if (LoQuad[i] > MaxQuad) {
8190 MaxQuad = LoQuad[i];
8194 int BestHiQuad = -1;
8196 for (unsigned i = 0; i < 4; ++i) {
8197 if (HiQuad[i] > MaxQuad) {
8199 MaxQuad = HiQuad[i];
8203 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8204 // of the two input vectors, shuffle them into one input vector so only a
8205 // single pshufb instruction is necessary. If there are more than 2 input
8206 // quads, disable the next transformation since it does not help SSSE3.
8207 bool V1Used = InputQuads[0] || InputQuads[1];
8208 bool V2Used = InputQuads[2] || InputQuads[3];
8209 if (Subtarget->hasSSSE3()) {
8210 if (InputQuads.count() == 2 && V1Used && V2Used) {
8211 BestLoQuad = InputQuads[0] ? 0 : 1;
8212 BestHiQuad = InputQuads[2] ? 2 : 3;
8214 if (InputQuads.count() > 2) {
8220 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8221 // the shuffle mask. If a quad is scored as -1, that means that it contains
8222 // words from all 4 input quadwords.
8224 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8226 BestLoQuad < 0 ? 0 : BestLoQuad,
8227 BestHiQuad < 0 ? 1 : BestHiQuad
8229 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8230 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8231 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8232 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8234 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8235 // source words for the shuffle, to aid later transformations.
8236 bool AllWordsInNewV = true;
8237 bool InOrder[2] = { true, true };
8238 for (unsigned i = 0; i != 8; ++i) {
8239 int idx = MaskVals[i];
8241 InOrder[i/4] = false;
8242 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8244 AllWordsInNewV = false;
8248 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8249 if (AllWordsInNewV) {
8250 for (int i = 0; i != 8; ++i) {
8251 int idx = MaskVals[i];
8254 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8255 if ((idx != i) && idx < 4)
8257 if ((idx != i) && idx > 3)
8266 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8267 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8268 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8269 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8270 unsigned TargetMask = 0;
8271 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8272 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8273 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8274 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8275 getShufflePSHUFLWImmediate(SVOp);
8276 V1 = NewV.getOperand(0);
8277 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8281 // Promote splats to a larger type which usually leads to more efficient code.
8282 // FIXME: Is this true if pshufb is available?
8283 if (SVOp->isSplat())
8284 return PromoteSplat(SVOp, DAG);
8286 // If we have SSSE3, and all words of the result are from 1 input vector,
8287 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8288 // is present, fall back to case 4.
8289 if (Subtarget->hasSSSE3()) {
8290 SmallVector<SDValue,16> pshufbMask;
8292 // If we have elements from both input vectors, set the high bit of the
8293 // shuffle mask element to zero out elements that come from V2 in the V1
8294 // mask, and elements that come from V1 in the V2 mask, so that the two
8295 // results can be OR'd together.
8296 bool TwoInputs = V1Used && V2Used;
8297 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8299 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8301 // Calculate the shuffle mask for the second input, shuffle it, and
8302 // OR it with the first shuffled input.
8303 CommuteVectorShuffleMask(MaskVals, 8);
8304 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8305 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8306 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8309 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8310 // and update MaskVals with new element order.
8311 std::bitset<8> InOrder;
8312 if (BestLoQuad >= 0) {
8313 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8314 for (int i = 0; i != 4; ++i) {
8315 int idx = MaskVals[i];
8318 } else if ((idx / 4) == BestLoQuad) {
8323 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8326 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8327 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8328 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8330 getShufflePSHUFLWImmediate(SVOp), DAG);
8334 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8335 // and update MaskVals with the new element order.
8336 if (BestHiQuad >= 0) {
8337 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8338 for (unsigned i = 4; i != 8; ++i) {
8339 int idx = MaskVals[i];
8342 } else if ((idx / 4) == BestHiQuad) {
8343 MaskV[i] = (idx & 3) + 4;
8347 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8350 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8351 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8352 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8354 getShufflePSHUFHWImmediate(SVOp), DAG);
8358 // In case BestHi & BestLo were both -1, which means each quadword has a word
8359 // from each of the four input quadwords, calculate the InOrder bitvector now
8360 // before falling through to the insert/extract cleanup.
8361 if (BestLoQuad == -1 && BestHiQuad == -1) {
8363 for (int i = 0; i != 8; ++i)
8364 if (MaskVals[i] < 0 || MaskVals[i] == i)
8368 // The other elements are put in the right place using pextrw and pinsrw.
8369 for (unsigned i = 0; i != 8; ++i) {
8372 int EltIdx = MaskVals[i];
8375 SDValue ExtOp = (EltIdx < 8) ?
8376 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8377 DAG.getIntPtrConstant(EltIdx)) :
8378 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8379 DAG.getIntPtrConstant(EltIdx - 8));
8380 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8381 DAG.getIntPtrConstant(i));
8386 /// \brief v16i16 shuffles
8388 /// FIXME: We only support generation of a single pshufb currently. We can
8389 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8390 /// well (e.g 2 x pshufb + 1 x por).
8392 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8393 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8394 SDValue V1 = SVOp->getOperand(0);
8395 SDValue V2 = SVOp->getOperand(1);
8398 if (V2.getOpcode() != ISD::UNDEF)
8401 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8402 return getPSHUFB(MaskVals, V1, dl, DAG);
8405 // v16i8 shuffles - Prefer shuffles in the following order:
8406 // 1. [ssse3] 1 x pshufb
8407 // 2. [ssse3] 2 x pshufb + 1 x por
8408 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8409 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8410 const X86Subtarget* Subtarget,
8411 SelectionDAG &DAG) {
8412 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8413 SDValue V1 = SVOp->getOperand(0);
8414 SDValue V2 = SVOp->getOperand(1);
8416 ArrayRef<int> MaskVals = SVOp->getMask();
8418 // Promote splats to a larger type which usually leads to more efficient code.
8419 // FIXME: Is this true if pshufb is available?
8420 if (SVOp->isSplat())
8421 return PromoteSplat(SVOp, DAG);
8423 // If we have SSSE3, case 1 is generated when all result bytes come from
8424 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8425 // present, fall back to case 3.
8427 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8428 if (Subtarget->hasSSSE3()) {
8429 SmallVector<SDValue,16> pshufbMask;
8431 // If all result elements are from one input vector, then only translate
8432 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8434 // Otherwise, we have elements from both input vectors, and must zero out
8435 // elements that come from V2 in the first mask, and V1 in the second mask
8436 // so that we can OR them together.
8437 for (unsigned i = 0; i != 16; ++i) {
8438 int EltIdx = MaskVals[i];
8439 if (EltIdx < 0 || EltIdx >= 16)
8441 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8443 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8444 DAG.getNode(ISD::BUILD_VECTOR, dl,
8445 MVT::v16i8, pshufbMask));
8447 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8448 // the 2nd operand if it's undefined or zero.
8449 if (V2.getOpcode() == ISD::UNDEF ||
8450 ISD::isBuildVectorAllZeros(V2.getNode()))
8453 // Calculate the shuffle mask for the second input, shuffle it, and
8454 // OR it with the first shuffled input.
8456 for (unsigned i = 0; i != 16; ++i) {
8457 int EltIdx = MaskVals[i];
8458 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8459 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8461 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8462 DAG.getNode(ISD::BUILD_VECTOR, dl,
8463 MVT::v16i8, pshufbMask));
8464 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8467 // No SSSE3 - Calculate in place words and then fix all out of place words
8468 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8469 // the 16 different words that comprise the two doublequadword input vectors.
8470 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8471 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8473 for (int i = 0; i != 8; ++i) {
8474 int Elt0 = MaskVals[i*2];
8475 int Elt1 = MaskVals[i*2+1];
8477 // This word of the result is all undef, skip it.
8478 if (Elt0 < 0 && Elt1 < 0)
8481 // This word of the result is already in the correct place, skip it.
8482 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8485 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8486 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8489 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8490 // using a single extract together, load it and store it.
8491 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8492 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8493 DAG.getIntPtrConstant(Elt1 / 2));
8494 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8495 DAG.getIntPtrConstant(i));
8499 // If Elt1 is defined, extract it from the appropriate source. If the
8500 // source byte is not also odd, shift the extracted word left 8 bits
8501 // otherwise clear the bottom 8 bits if we need to do an or.
8503 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8504 DAG.getIntPtrConstant(Elt1 / 2));
8505 if ((Elt1 & 1) == 0)
8506 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8508 TLI.getShiftAmountTy(InsElt.getValueType())));
8510 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8511 DAG.getConstant(0xFF00, MVT::i16));
8513 // If Elt0 is defined, extract it from the appropriate source. If the
8514 // source byte is not also even, shift the extracted word right 8 bits. If
8515 // Elt1 was also defined, OR the extracted values together before
8516 // inserting them in the result.
8518 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8519 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8520 if ((Elt0 & 1) != 0)
8521 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8523 TLI.getShiftAmountTy(InsElt0.getValueType())));
8525 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8526 DAG.getConstant(0x00FF, MVT::i16));
8527 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8530 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8531 DAG.getIntPtrConstant(i));
8533 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8536 // v32i8 shuffles - Translate to VPSHUFB if possible.
8538 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8539 const X86Subtarget *Subtarget,
8540 SelectionDAG &DAG) {
8541 MVT VT = SVOp->getSimpleValueType(0);
8542 SDValue V1 = SVOp->getOperand(0);
8543 SDValue V2 = SVOp->getOperand(1);
8545 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8547 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8548 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8549 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8551 // VPSHUFB may be generated if
8552 // (1) one of input vector is undefined or zeroinitializer.
8553 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8554 // And (2) the mask indexes don't cross the 128-bit lane.
8555 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8556 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8559 if (V1IsAllZero && !V2IsAllZero) {
8560 CommuteVectorShuffleMask(MaskVals, 32);
8563 return getPSHUFB(MaskVals, V1, dl, DAG);
8566 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8567 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8568 /// done when every pair / quad of shuffle mask elements point to elements in
8569 /// the right sequence. e.g.
8570 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8572 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8573 SelectionDAG &DAG) {
8574 MVT VT = SVOp->getSimpleValueType(0);
8576 unsigned NumElems = VT.getVectorNumElements();
8579 switch (VT.SimpleTy) {
8580 default: llvm_unreachable("Unexpected!");
8583 return SDValue(SVOp, 0);
8584 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8585 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8586 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8587 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8588 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8589 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8592 SmallVector<int, 8> MaskVec;
8593 for (unsigned i = 0; i != NumElems; i += Scale) {
8595 for (unsigned j = 0; j != Scale; ++j) {
8596 int EltIdx = SVOp->getMaskElt(i+j);
8600 StartIdx = (EltIdx / Scale);
8601 if (EltIdx != (int)(StartIdx*Scale + j))
8604 MaskVec.push_back(StartIdx);
8607 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8608 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8609 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8612 /// getVZextMovL - Return a zero-extending vector move low node.
8614 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8615 SDValue SrcOp, SelectionDAG &DAG,
8616 const X86Subtarget *Subtarget, SDLoc dl) {
8617 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8618 LoadSDNode *LD = nullptr;
8619 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8620 LD = dyn_cast<LoadSDNode>(SrcOp);
8622 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8624 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8625 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8626 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8627 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8628 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8630 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8631 return DAG.getNode(ISD::BITCAST, dl, VT,
8632 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8633 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8641 return DAG.getNode(ISD::BITCAST, dl, VT,
8642 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8643 DAG.getNode(ISD::BITCAST, dl,
8647 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8648 /// which could not be matched by any known target speficic shuffle
8650 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8652 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8653 if (NewOp.getNode())
8656 MVT VT = SVOp->getSimpleValueType(0);
8658 unsigned NumElems = VT.getVectorNumElements();
8659 unsigned NumLaneElems = NumElems / 2;
8662 MVT EltVT = VT.getVectorElementType();
8663 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8666 SmallVector<int, 16> Mask;
8667 for (unsigned l = 0; l < 2; ++l) {
8668 // Build a shuffle mask for the output, discovering on the fly which
8669 // input vectors to use as shuffle operands (recorded in InputUsed).
8670 // If building a suitable shuffle vector proves too hard, then bail
8671 // out with UseBuildVector set.
8672 bool UseBuildVector = false;
8673 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8674 unsigned LaneStart = l * NumLaneElems;
8675 for (unsigned i = 0; i != NumLaneElems; ++i) {
8676 // The mask element. This indexes into the input.
8677 int Idx = SVOp->getMaskElt(i+LaneStart);
8679 // the mask element does not index into any input vector.
8684 // The input vector this mask element indexes into.
8685 int Input = Idx / NumLaneElems;
8687 // Turn the index into an offset from the start of the input vector.
8688 Idx -= Input * NumLaneElems;
8690 // Find or create a shuffle vector operand to hold this input.
8692 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8693 if (InputUsed[OpNo] == Input)
8694 // This input vector is already an operand.
8696 if (InputUsed[OpNo] < 0) {
8697 // Create a new operand for this input vector.
8698 InputUsed[OpNo] = Input;
8703 if (OpNo >= array_lengthof(InputUsed)) {
8704 // More than two input vectors used! Give up on trying to create a
8705 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8706 UseBuildVector = true;
8710 // Add the mask index for the new shuffle vector.
8711 Mask.push_back(Idx + OpNo * NumLaneElems);
8714 if (UseBuildVector) {
8715 SmallVector<SDValue, 16> SVOps;
8716 for (unsigned i = 0; i != NumLaneElems; ++i) {
8717 // The mask element. This indexes into the input.
8718 int Idx = SVOp->getMaskElt(i+LaneStart);
8720 SVOps.push_back(DAG.getUNDEF(EltVT));
8724 // The input vector this mask element indexes into.
8725 int Input = Idx / NumElems;
8727 // Turn the index into an offset from the start of the input vector.
8728 Idx -= Input * NumElems;
8730 // Extract the vector element by hand.
8731 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8732 SVOp->getOperand(Input),
8733 DAG.getIntPtrConstant(Idx)));
8736 // Construct the output using a BUILD_VECTOR.
8737 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8738 } else if (InputUsed[0] < 0) {
8739 // No input vectors were used! The result is undefined.
8740 Output[l] = DAG.getUNDEF(NVT);
8742 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8743 (InputUsed[0] % 2) * NumLaneElems,
8745 // If only one input was used, use an undefined vector for the other.
8746 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8747 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8748 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8749 // At least one input vector was used. Create a new shuffle vector.
8750 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8756 // Concatenate the result back
8757 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8760 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8761 /// 4 elements, and match them with several different shuffle types.
8763 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8764 SDValue V1 = SVOp->getOperand(0);
8765 SDValue V2 = SVOp->getOperand(1);
8767 MVT VT = SVOp->getSimpleValueType(0);
8769 assert(VT.is128BitVector() && "Unsupported vector size");
8771 std::pair<int, int> Locs[4];
8772 int Mask1[] = { -1, -1, -1, -1 };
8773 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8777 for (unsigned i = 0; i != 4; ++i) {
8778 int Idx = PermMask[i];
8780 Locs[i] = std::make_pair(-1, -1);
8782 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8784 Locs[i] = std::make_pair(0, NumLo);
8788 Locs[i] = std::make_pair(1, NumHi);
8790 Mask1[2+NumHi] = Idx;
8796 if (NumLo <= 2 && NumHi <= 2) {
8797 // If no more than two elements come from either vector. This can be
8798 // implemented with two shuffles. First shuffle gather the elements.
8799 // The second shuffle, which takes the first shuffle as both of its
8800 // vector operands, put the elements into the right order.
8801 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8803 int Mask2[] = { -1, -1, -1, -1 };
8805 for (unsigned i = 0; i != 4; ++i)
8806 if (Locs[i].first != -1) {
8807 unsigned Idx = (i < 2) ? 0 : 4;
8808 Idx += Locs[i].first * 2 + Locs[i].second;
8812 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8815 if (NumLo == 3 || NumHi == 3) {
8816 // Otherwise, we must have three elements from one vector, call it X, and
8817 // one element from the other, call it Y. First, use a shufps to build an
8818 // intermediate vector with the one element from Y and the element from X
8819 // that will be in the same half in the final destination (the indexes don't
8820 // matter). Then, use a shufps to build the final vector, taking the half
8821 // containing the element from Y from the intermediate, and the other half
8824 // Normalize it so the 3 elements come from V1.
8825 CommuteVectorShuffleMask(PermMask, 4);
8829 // Find the element from V2.
8831 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8832 int Val = PermMask[HiIndex];
8839 Mask1[0] = PermMask[HiIndex];
8841 Mask1[2] = PermMask[HiIndex^1];
8843 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8846 Mask1[0] = PermMask[0];
8847 Mask1[1] = PermMask[1];
8848 Mask1[2] = HiIndex & 1 ? 6 : 4;
8849 Mask1[3] = HiIndex & 1 ? 4 : 6;
8850 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8853 Mask1[0] = HiIndex & 1 ? 2 : 0;
8854 Mask1[1] = HiIndex & 1 ? 0 : 2;
8855 Mask1[2] = PermMask[2];
8856 Mask1[3] = PermMask[3];
8861 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8864 // Break it into (shuffle shuffle_hi, shuffle_lo).
8865 int LoMask[] = { -1, -1, -1, -1 };
8866 int HiMask[] = { -1, -1, -1, -1 };
8868 int *MaskPtr = LoMask;
8869 unsigned MaskIdx = 0;
8872 for (unsigned i = 0; i != 4; ++i) {
8879 int Idx = PermMask[i];
8881 Locs[i] = std::make_pair(-1, -1);
8882 } else if (Idx < 4) {
8883 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8884 MaskPtr[LoIdx] = Idx;
8887 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8888 MaskPtr[HiIdx] = Idx;
8893 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8894 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8895 int MaskOps[] = { -1, -1, -1, -1 };
8896 for (unsigned i = 0; i != 4; ++i)
8897 if (Locs[i].first != -1)
8898 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8899 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8902 static bool MayFoldVectorLoad(SDValue V) {
8903 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8904 V = V.getOperand(0);
8906 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8907 V = V.getOperand(0);
8908 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8909 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8910 // BUILD_VECTOR (load), undef
8911 V = V.getOperand(0);
8913 return MayFoldLoad(V);
8917 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8918 MVT VT = Op.getSimpleValueType();
8920 // Canonizalize to v2f64.
8921 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8922 return DAG.getNode(ISD::BITCAST, dl, VT,
8923 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8928 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8930 SDValue V1 = Op.getOperand(0);
8931 SDValue V2 = Op.getOperand(1);
8932 MVT VT = Op.getSimpleValueType();
8934 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8936 if (HasSSE2 && VT == MVT::v2f64)
8937 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8939 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8940 return DAG.getNode(ISD::BITCAST, dl, VT,
8941 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8942 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8943 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8947 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8948 SDValue V1 = Op.getOperand(0);
8949 SDValue V2 = Op.getOperand(1);
8950 MVT VT = Op.getSimpleValueType();
8952 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8953 "unsupported shuffle type");
8955 if (V2.getOpcode() == ISD::UNDEF)
8959 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8963 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8964 SDValue V1 = Op.getOperand(0);
8965 SDValue V2 = Op.getOperand(1);
8966 MVT VT = Op.getSimpleValueType();
8967 unsigned NumElems = VT.getVectorNumElements();
8969 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8970 // operand of these instructions is only memory, so check if there's a
8971 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8973 bool CanFoldLoad = false;
8975 // Trivial case, when V2 comes from a load.
8976 if (MayFoldVectorLoad(V2))
8979 // When V1 is a load, it can be folded later into a store in isel, example:
8980 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8982 // (MOVLPSmr addr:$src1, VR128:$src2)
8983 // So, recognize this potential and also use MOVLPS or MOVLPD
8984 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8987 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8989 if (HasSSE2 && NumElems == 2)
8990 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8993 // If we don't care about the second element, proceed to use movss.
8994 if (SVOp->getMaskElt(1) != -1)
8995 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8998 // movl and movlp will both match v2i64, but v2i64 is never matched by
8999 // movl earlier because we make it strict to avoid messing with the movlp load
9000 // folding logic (see the code above getMOVLP call). Match it here then,
9001 // this is horrible, but will stay like this until we move all shuffle
9002 // matching to x86 specific nodes. Note that for the 1st condition all
9003 // types are matched with movsd.
9005 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9006 // as to remove this logic from here, as much as possible
9007 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9008 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9009 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9012 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9014 // Invert the operand order and use SHUFPS to match it.
9015 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9016 getShuffleSHUFImmediate(SVOp), DAG);
9019 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9020 SelectionDAG &DAG) {
9022 MVT VT = Load->getSimpleValueType(0);
9023 MVT EVT = VT.getVectorElementType();
9024 SDValue Addr = Load->getOperand(1);
9025 SDValue NewAddr = DAG.getNode(
9026 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9027 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9030 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9031 DAG.getMachineFunction().getMachineMemOperand(
9032 Load->getMemOperand(), 0, EVT.getStoreSize()));
9036 // It is only safe to call this function if isINSERTPSMask is true for
9037 // this shufflevector mask.
9038 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9039 SelectionDAG &DAG) {
9040 // Generate an insertps instruction when inserting an f32 from memory onto a
9041 // v4f32 or when copying a member from one v4f32 to another.
9042 // We also use it for transferring i32 from one register to another,
9043 // since it simply copies the same bits.
9044 // If we're transferring an i32 from memory to a specific element in a
9045 // register, we output a generic DAG that will match the PINSRD
9047 MVT VT = SVOp->getSimpleValueType(0);
9048 MVT EVT = VT.getVectorElementType();
9049 SDValue V1 = SVOp->getOperand(0);
9050 SDValue V2 = SVOp->getOperand(1);
9051 auto Mask = SVOp->getMask();
9052 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9053 "unsupported vector type for insertps/pinsrd");
9055 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9056 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9057 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9065 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9068 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9069 "More than one element from V1 and from V2, or no elements from one "
9070 "of the vectors. This case should not have returned true from "
9075 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9078 unsigned SrcIndex = Mask[DestIndex] % 4;
9079 if (MayFoldLoad(From)) {
9080 // Trivial case, when From comes from a load and is only used by the
9081 // shuffle. Make it use insertps from the vector that we need from that
9084 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9085 if (!NewLoad.getNode())
9088 if (EVT == MVT::f32) {
9089 // Create this as a scalar to vector to match the instruction pattern.
9090 SDValue LoadScalarToVector =
9091 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9092 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9093 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9095 } else { // EVT == MVT::i32
9096 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9097 // instruction, to match the PINSRD instruction, which loads an i32 to a
9098 // certain vector element.
9099 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9100 DAG.getConstant(DestIndex, MVT::i32));
9104 // Vector-element-to-vector
9105 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9106 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9109 // Reduce a vector shuffle to zext.
9110 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9111 SelectionDAG &DAG) {
9112 // PMOVZX is only available from SSE41.
9113 if (!Subtarget->hasSSE41())
9116 MVT VT = Op.getSimpleValueType();
9118 // Only AVX2 support 256-bit vector integer extending.
9119 if (!Subtarget->hasInt256() && VT.is256BitVector())
9122 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9124 SDValue V1 = Op.getOperand(0);
9125 SDValue V2 = Op.getOperand(1);
9126 unsigned NumElems = VT.getVectorNumElements();
9128 // Extending is an unary operation and the element type of the source vector
9129 // won't be equal to or larger than i64.
9130 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9131 VT.getVectorElementType() == MVT::i64)
9134 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9135 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9136 while ((1U << Shift) < NumElems) {
9137 if (SVOp->getMaskElt(1U << Shift) == 1)
9140 // The maximal ratio is 8, i.e. from i8 to i64.
9145 // Check the shuffle mask.
9146 unsigned Mask = (1U << Shift) - 1;
9147 for (unsigned i = 0; i != NumElems; ++i) {
9148 int EltIdx = SVOp->getMaskElt(i);
9149 if ((i & Mask) != 0 && EltIdx != -1)
9151 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9155 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9156 MVT NeVT = MVT::getIntegerVT(NBits);
9157 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9159 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9162 // Simplify the operand as it's prepared to be fed into shuffle.
9163 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9164 if (V1.getOpcode() == ISD::BITCAST &&
9165 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9166 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9167 V1.getOperand(0).getOperand(0)
9168 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9169 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9170 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9171 ConstantSDNode *CIdx =
9172 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9173 // If it's foldable, i.e. normal load with single use, we will let code
9174 // selection to fold it. Otherwise, we will short the conversion sequence.
9175 if (CIdx && CIdx->getZExtValue() == 0 &&
9176 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9177 MVT FullVT = V.getSimpleValueType();
9178 MVT V1VT = V1.getSimpleValueType();
9179 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9180 // The "ext_vec_elt" node is wider than the result node.
9181 // In this case we should extract subvector from V.
9182 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9183 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9184 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9185 FullVT.getVectorNumElements()/Ratio);
9186 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9187 DAG.getIntPtrConstant(0));
9189 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9193 return DAG.getNode(ISD::BITCAST, DL, VT,
9194 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9197 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9198 SelectionDAG &DAG) {
9199 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9200 MVT VT = Op.getSimpleValueType();
9202 SDValue V1 = Op.getOperand(0);
9203 SDValue V2 = Op.getOperand(1);
9205 if (isZeroShuffle(SVOp))
9206 return getZeroVector(VT, Subtarget, DAG, dl);
9208 // Handle splat operations
9209 if (SVOp->isSplat()) {
9210 // Use vbroadcast whenever the splat comes from a foldable load
9211 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9212 if (Broadcast.getNode())
9216 // Check integer expanding shuffles.
9217 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9218 if (NewOp.getNode())
9221 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9223 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9225 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9226 if (NewOp.getNode())
9227 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9228 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9229 // FIXME: Figure out a cleaner way to do this.
9230 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9231 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9232 if (NewOp.getNode()) {
9233 MVT NewVT = NewOp.getSimpleValueType();
9234 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9235 NewVT, true, false))
9236 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9239 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9240 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9241 if (NewOp.getNode()) {
9242 MVT NewVT = NewOp.getSimpleValueType();
9243 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9244 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9253 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9254 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9255 SDValue V1 = Op.getOperand(0);
9256 SDValue V2 = Op.getOperand(1);
9257 MVT VT = Op.getSimpleValueType();
9259 unsigned NumElems = VT.getVectorNumElements();
9260 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9261 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9262 bool V1IsSplat = false;
9263 bool V2IsSplat = false;
9264 bool HasSSE2 = Subtarget->hasSSE2();
9265 bool HasFp256 = Subtarget->hasFp256();
9266 bool HasInt256 = Subtarget->hasInt256();
9267 MachineFunction &MF = DAG.getMachineFunction();
9268 bool OptForSize = MF.getFunction()->getAttributes().
9269 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9271 // Check if we should use the experimental vector shuffle lowering. If so,
9272 // delegate completely to that code path.
9273 if (ExperimentalVectorShuffleLowering)
9274 return lowerVectorShuffle(Op, Subtarget, DAG);
9276 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9278 if (V1IsUndef && V2IsUndef)
9279 return DAG.getUNDEF(VT);
9281 // When we create a shuffle node we put the UNDEF node to second operand,
9282 // but in some cases the first operand may be transformed to UNDEF.
9283 // In this case we should just commute the node.
9285 return CommuteVectorShuffle(SVOp, DAG);
9287 // Vector shuffle lowering takes 3 steps:
9289 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9290 // narrowing and commutation of operands should be handled.
9291 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9293 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9294 // so the shuffle can be broken into other shuffles and the legalizer can
9295 // try the lowering again.
9297 // The general idea is that no vector_shuffle operation should be left to
9298 // be matched during isel, all of them must be converted to a target specific
9301 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9302 // narrowing and commutation of operands should be handled. The actual code
9303 // doesn't include all of those, work in progress...
9304 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9305 if (NewOp.getNode())
9308 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9310 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9311 // unpckh_undef). Only use pshufd if speed is more important than size.
9312 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9313 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9314 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9315 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9317 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9318 V2IsUndef && MayFoldVectorLoad(V1))
9319 return getMOVDDup(Op, dl, V1, DAG);
9321 if (isMOVHLPS_v_undef_Mask(M, VT))
9322 return getMOVHighToLow(Op, dl, DAG);
9324 // Use to match splats
9325 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9326 (VT == MVT::v2f64 || VT == MVT::v2i64))
9327 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9329 if (isPSHUFDMask(M, VT)) {
9330 // The actual implementation will match the mask in the if above and then
9331 // during isel it can match several different instructions, not only pshufd
9332 // as its name says, sad but true, emulate the behavior for now...
9333 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9334 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9336 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9338 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9339 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9341 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9342 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9345 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9349 if (isPALIGNRMask(M, VT, Subtarget))
9350 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9351 getShufflePALIGNRImmediate(SVOp),
9354 // Check if this can be converted into a logical shift.
9355 bool isLeft = false;
9358 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9359 if (isShift && ShVal.hasOneUse()) {
9360 // If the shifted value has multiple uses, it may be cheaper to use
9361 // v_set0 + movlhps or movhlps, etc.
9362 MVT EltVT = VT.getVectorElementType();
9363 ShAmt *= EltVT.getSizeInBits();
9364 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9367 if (isMOVLMask(M, VT)) {
9368 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9369 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9370 if (!isMOVLPMask(M, VT)) {
9371 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9372 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9374 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9375 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9379 // FIXME: fold these into legal mask.
9380 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9381 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9383 if (isMOVHLPSMask(M, VT))
9384 return getMOVHighToLow(Op, dl, DAG);
9386 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9387 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9389 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9390 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9392 if (isMOVLPMask(M, VT))
9393 return getMOVLP(Op, dl, DAG, HasSSE2);
9395 if (ShouldXformToMOVHLPS(M, VT) ||
9396 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9397 return CommuteVectorShuffle(SVOp, DAG);
9400 // No better options. Use a vshldq / vsrldq.
9401 MVT EltVT = VT.getVectorElementType();
9402 ShAmt *= EltVT.getSizeInBits();
9403 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9406 bool Commuted = false;
9407 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9408 // 1,1,1,1 -> v8i16 though.
9409 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9410 if (BVOp->getConstantSplatValue())
9412 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9413 if (BVOp->getConstantSplatValue())
9416 // Canonicalize the splat or undef, if present, to be on the RHS.
9417 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9418 CommuteVectorShuffleMask(M, NumElems);
9420 std::swap(V1IsSplat, V2IsSplat);
9424 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9425 // Shuffling low element of v1 into undef, just return v1.
9428 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9429 // the instruction selector will not match, so get a canonical MOVL with
9430 // swapped operands to undo the commute.
9431 return getMOVL(DAG, dl, VT, V2, V1);
9434 if (isUNPCKLMask(M, VT, HasInt256))
9435 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9437 if (isUNPCKHMask(M, VT, HasInt256))
9438 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9441 // Normalize mask so all entries that point to V2 points to its first
9442 // element then try to match unpck{h|l} again. If match, return a
9443 // new vector_shuffle with the corrected mask.p
9444 SmallVector<int, 8> NewMask(M.begin(), M.end());
9445 NormalizeMask(NewMask, NumElems);
9446 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9447 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9448 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9449 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9453 // Commute is back and try unpck* again.
9454 // FIXME: this seems wrong.
9455 CommuteVectorShuffleMask(M, NumElems);
9457 std::swap(V1IsSplat, V2IsSplat);
9459 if (isUNPCKLMask(M, VT, HasInt256))
9460 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9462 if (isUNPCKHMask(M, VT, HasInt256))
9463 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9466 // Normalize the node to match x86 shuffle ops if needed
9467 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9468 return CommuteVectorShuffle(SVOp, DAG);
9470 // The checks below are all present in isShuffleMaskLegal, but they are
9471 // inlined here right now to enable us to directly emit target specific
9472 // nodes, and remove one by one until they don't return Op anymore.
9474 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9475 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9476 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9477 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9480 if (isPSHUFHWMask(M, VT, HasInt256))
9481 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9482 getShufflePSHUFHWImmediate(SVOp),
9485 if (isPSHUFLWMask(M, VT, HasInt256))
9486 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9487 getShufflePSHUFLWImmediate(SVOp),
9491 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9493 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9495 if (isSHUFPMask(M, VT))
9496 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9497 getShuffleSHUFImmediate(SVOp), DAG);
9499 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9500 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9501 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9502 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9504 //===--------------------------------------------------------------------===//
9505 // Generate target specific nodes for 128 or 256-bit shuffles only
9506 // supported in the AVX instruction set.
9509 // Handle VMOVDDUPY permutations
9510 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9511 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9513 // Handle VPERMILPS/D* permutations
9514 if (isVPERMILPMask(M, VT)) {
9515 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9516 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9517 getShuffleSHUFImmediate(SVOp), DAG);
9518 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9519 getShuffleSHUFImmediate(SVOp), DAG);
9523 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9524 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9525 Idx*(NumElems/2), DAG, dl);
9527 // Handle VPERM2F128/VPERM2I128 permutations
9528 if (isVPERM2X128Mask(M, VT, HasFp256))
9529 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9530 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9532 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9533 return getINSERTPS(SVOp, dl, DAG);
9536 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9537 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9539 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9540 VT.is512BitVector()) {
9541 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9542 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9543 SmallVector<SDValue, 16> permclMask;
9544 for (unsigned i = 0; i != NumElems; ++i) {
9545 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9548 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9550 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9551 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9552 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9553 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9554 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9557 //===--------------------------------------------------------------------===//
9558 // Since no target specific shuffle was selected for this generic one,
9559 // lower it into other known shuffles. FIXME: this isn't true yet, but
9560 // this is the plan.
9563 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9564 if (VT == MVT::v8i16) {
9565 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9566 if (NewOp.getNode())
9570 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9571 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9572 if (NewOp.getNode())
9576 if (VT == MVT::v16i8) {
9577 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9578 if (NewOp.getNode())
9582 if (VT == MVT::v32i8) {
9583 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9584 if (NewOp.getNode())
9588 // Handle all 128-bit wide vectors with 4 elements, and match them with
9589 // several different shuffle types.
9590 if (NumElems == 4 && VT.is128BitVector())
9591 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9593 // Handle general 256-bit shuffles
9594 if (VT.is256BitVector())
9595 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9600 // This function assumes its argument is a BUILD_VECTOR of constants or
9601 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9603 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9604 unsigned &MaskValue) {
9606 unsigned NumElems = BuildVector->getNumOperands();
9607 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9608 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9609 unsigned NumElemsInLane = NumElems / NumLanes;
9611 // Blend for v16i16 should be symetric for the both lanes.
9612 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9613 SDValue EltCond = BuildVector->getOperand(i);
9614 SDValue SndLaneEltCond =
9615 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9617 int Lane1Cond = -1, Lane2Cond = -1;
9618 if (isa<ConstantSDNode>(EltCond))
9619 Lane1Cond = !isZero(EltCond);
9620 if (isa<ConstantSDNode>(SndLaneEltCond))
9621 Lane2Cond = !isZero(SndLaneEltCond);
9623 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9624 // Lane1Cond != 0, means we want the first argument.
9625 // Lane1Cond == 0, means we want the second argument.
9626 // The encoding of this argument is 0 for the first argument, 1
9627 // for the second. Therefore, invert the condition.
9628 MaskValue |= !Lane1Cond << i;
9629 else if (Lane1Cond < 0)
9630 MaskValue |= !Lane2Cond << i;
9637 // Try to lower a vselect node into a simple blend instruction.
9638 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9639 SelectionDAG &DAG) {
9640 SDValue Cond = Op.getOperand(0);
9641 SDValue LHS = Op.getOperand(1);
9642 SDValue RHS = Op.getOperand(2);
9644 MVT VT = Op.getSimpleValueType();
9645 MVT EltVT = VT.getVectorElementType();
9646 unsigned NumElems = VT.getVectorNumElements();
9648 // There is no blend with immediate in AVX-512.
9649 if (VT.is512BitVector())
9652 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9654 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9657 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9660 // Check the mask for BLEND and build the value.
9661 unsigned MaskValue = 0;
9662 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9665 // Convert i32 vectors to floating point if it is not AVX2.
9666 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9668 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9669 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9671 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9672 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9675 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9676 DAG.getConstant(MaskValue, MVT::i32));
9677 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9680 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9681 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9682 if (BlendOp.getNode())
9685 // Some types for vselect were previously set to Expand, not Legal or
9686 // Custom. Return an empty SDValue so we fall-through to Expand, after
9687 // the Custom lowering phase.
9688 MVT VT = Op.getSimpleValueType();
9689 switch (VT.SimpleTy) {
9697 // We couldn't create a "Blend with immediate" node.
9698 // This node should still be legal, but we'll have to emit a blendv*
9703 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9704 MVT VT = Op.getSimpleValueType();
9707 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9710 if (VT.getSizeInBits() == 8) {
9711 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9712 Op.getOperand(0), Op.getOperand(1));
9713 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9714 DAG.getValueType(VT));
9715 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9718 if (VT.getSizeInBits() == 16) {
9719 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9720 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9722 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9723 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9724 DAG.getNode(ISD::BITCAST, dl,
9728 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9729 Op.getOperand(0), Op.getOperand(1));
9730 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9731 DAG.getValueType(VT));
9732 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9735 if (VT == MVT::f32) {
9736 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9737 // the result back to FR32 register. It's only worth matching if the
9738 // result has a single use which is a store or a bitcast to i32. And in
9739 // the case of a store, it's not worth it if the index is a constant 0,
9740 // because a MOVSSmr can be used instead, which is smaller and faster.
9741 if (!Op.hasOneUse())
9743 SDNode *User = *Op.getNode()->use_begin();
9744 if ((User->getOpcode() != ISD::STORE ||
9745 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9746 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9747 (User->getOpcode() != ISD::BITCAST ||
9748 User->getValueType(0) != MVT::i32))
9750 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9751 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9754 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9757 if (VT == MVT::i32 || VT == MVT::i64) {
9758 // ExtractPS/pextrq works with constant index.
9759 if (isa<ConstantSDNode>(Op.getOperand(1)))
9765 /// Extract one bit from mask vector, like v16i1 or v8i1.
9766 /// AVX-512 feature.
9768 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9769 SDValue Vec = Op.getOperand(0);
9771 MVT VecVT = Vec.getSimpleValueType();
9772 SDValue Idx = Op.getOperand(1);
9773 MVT EltVT = Op.getSimpleValueType();
9775 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9777 // variable index can't be handled in mask registers,
9778 // extend vector to VR512
9779 if (!isa<ConstantSDNode>(Idx)) {
9780 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9781 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9782 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9783 ExtVT.getVectorElementType(), Ext, Idx);
9784 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9787 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9788 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9789 unsigned MaxSift = rc->getSize()*8 - 1;
9790 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9791 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9792 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9793 DAG.getConstant(MaxSift, MVT::i8));
9794 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9795 DAG.getIntPtrConstant(0));
9799 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9800 SelectionDAG &DAG) const {
9802 SDValue Vec = Op.getOperand(0);
9803 MVT VecVT = Vec.getSimpleValueType();
9804 SDValue Idx = Op.getOperand(1);
9806 if (Op.getSimpleValueType() == MVT::i1)
9807 return ExtractBitFromMaskVector(Op, DAG);
9809 if (!isa<ConstantSDNode>(Idx)) {
9810 if (VecVT.is512BitVector() ||
9811 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9812 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9815 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9816 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9817 MaskEltVT.getSizeInBits());
9819 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9820 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9821 getZeroVector(MaskVT, Subtarget, DAG, dl),
9822 Idx, DAG.getConstant(0, getPointerTy()));
9823 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9824 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9825 Perm, DAG.getConstant(0, getPointerTy()));
9830 // If this is a 256-bit vector result, first extract the 128-bit vector and
9831 // then extract the element from the 128-bit vector.
9832 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9834 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9835 // Get the 128-bit vector.
9836 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9837 MVT EltVT = VecVT.getVectorElementType();
9839 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9841 //if (IdxVal >= NumElems/2)
9842 // IdxVal -= NumElems/2;
9843 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9844 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9845 DAG.getConstant(IdxVal, MVT::i32));
9848 assert(VecVT.is128BitVector() && "Unexpected vector length");
9850 if (Subtarget->hasSSE41()) {
9851 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9856 MVT VT = Op.getSimpleValueType();
9857 // TODO: handle v16i8.
9858 if (VT.getSizeInBits() == 16) {
9859 SDValue Vec = Op.getOperand(0);
9860 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9862 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9863 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9864 DAG.getNode(ISD::BITCAST, dl,
9867 // Transform it so it match pextrw which produces a 32-bit result.
9868 MVT EltVT = MVT::i32;
9869 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9870 Op.getOperand(0), Op.getOperand(1));
9871 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9872 DAG.getValueType(VT));
9873 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9876 if (VT.getSizeInBits() == 32) {
9877 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9881 // SHUFPS the element to the lowest double word, then movss.
9882 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9883 MVT VVT = Op.getOperand(0).getSimpleValueType();
9884 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9885 DAG.getUNDEF(VVT), Mask);
9886 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9887 DAG.getIntPtrConstant(0));
9890 if (VT.getSizeInBits() == 64) {
9891 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9892 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9893 // to match extract_elt for f64.
9894 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9898 // UNPCKHPD the element to the lowest double word, then movsd.
9899 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9900 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9901 int Mask[2] = { 1, -1 };
9902 MVT VVT = Op.getOperand(0).getSimpleValueType();
9903 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9904 DAG.getUNDEF(VVT), Mask);
9905 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9906 DAG.getIntPtrConstant(0));
9912 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9913 MVT VT = Op.getSimpleValueType();
9914 MVT EltVT = VT.getVectorElementType();
9917 SDValue N0 = Op.getOperand(0);
9918 SDValue N1 = Op.getOperand(1);
9919 SDValue N2 = Op.getOperand(2);
9921 if (!VT.is128BitVector())
9924 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9925 isa<ConstantSDNode>(N2)) {
9927 if (VT == MVT::v8i16)
9928 Opc = X86ISD::PINSRW;
9929 else if (VT == MVT::v16i8)
9930 Opc = X86ISD::PINSRB;
9932 Opc = X86ISD::PINSRB;
9934 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9936 if (N1.getValueType() != MVT::i32)
9937 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9938 if (N2.getValueType() != MVT::i32)
9939 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9940 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9943 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9944 // Bits [7:6] of the constant are the source select. This will always be
9945 // zero here. The DAG Combiner may combine an extract_elt index into these
9946 // bits. For example (insert (extract, 3), 2) could be matched by putting
9947 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9948 // Bits [5:4] of the constant are the destination select. This is the
9949 // value of the incoming immediate.
9950 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9951 // combine either bitwise AND or insert of float 0.0 to set these bits.
9952 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9953 // Create this as a scalar to vector..
9954 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9955 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9958 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9959 // PINSR* works with constant index.
9965 /// Insert one bit to mask vector, like v16i1 or v8i1.
9966 /// AVX-512 feature.
9968 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9970 SDValue Vec = Op.getOperand(0);
9971 SDValue Elt = Op.getOperand(1);
9972 SDValue Idx = Op.getOperand(2);
9973 MVT VecVT = Vec.getSimpleValueType();
9975 if (!isa<ConstantSDNode>(Idx)) {
9976 // Non constant index. Extend source and destination,
9977 // insert element and then truncate the result.
9978 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9979 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
9980 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
9981 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9982 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9983 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9986 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9987 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9988 if (Vec.getOpcode() == ISD::UNDEF)
9989 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9990 DAG.getConstant(IdxVal, MVT::i8));
9991 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9992 unsigned MaxSift = rc->getSize()*8 - 1;
9993 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9994 DAG.getConstant(MaxSift, MVT::i8));
9995 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9996 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9997 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10000 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10001 MVT VT = Op.getSimpleValueType();
10002 MVT EltVT = VT.getVectorElementType();
10004 if (EltVT == MVT::i1)
10005 return InsertBitToMaskVector(Op, DAG);
10008 SDValue N0 = Op.getOperand(0);
10009 SDValue N1 = Op.getOperand(1);
10010 SDValue N2 = Op.getOperand(2);
10012 // If this is a 256-bit vector result, first extract the 128-bit vector,
10013 // insert the element into the extracted half and then place it back.
10014 if (VT.is256BitVector() || VT.is512BitVector()) {
10015 if (!isa<ConstantSDNode>(N2))
10018 // Get the desired 128-bit vector half.
10019 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10020 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10022 // Insert the element into the desired half.
10023 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10024 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10026 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10027 DAG.getConstant(IdxIn128, MVT::i32));
10029 // Insert the changed part back to the 256-bit vector
10030 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10033 if (Subtarget->hasSSE41())
10034 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10036 if (EltVT == MVT::i8)
10039 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10040 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10041 // as its second argument.
10042 if (N1.getValueType() != MVT::i32)
10043 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10044 if (N2.getValueType() != MVT::i32)
10045 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10046 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10051 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10053 MVT OpVT = Op.getSimpleValueType();
10055 // If this is a 256-bit vector result, first insert into a 128-bit
10056 // vector and then insert into the 256-bit vector.
10057 if (!OpVT.is128BitVector()) {
10058 // Insert into a 128-bit vector.
10059 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10060 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10061 OpVT.getVectorNumElements() / SizeFactor);
10063 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10065 // Insert the 128-bit vector.
10066 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10069 if (OpVT == MVT::v1i64 &&
10070 Op.getOperand(0).getValueType() == MVT::i64)
10071 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10073 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10074 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10075 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10076 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10079 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10080 // a simple subregister reference or explicit instructions to grab
10081 // upper bits of a vector.
10082 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10083 SelectionDAG &DAG) {
10085 SDValue In = Op.getOperand(0);
10086 SDValue Idx = Op.getOperand(1);
10087 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10088 MVT ResVT = Op.getSimpleValueType();
10089 MVT InVT = In.getSimpleValueType();
10091 if (Subtarget->hasFp256()) {
10092 if (ResVT.is128BitVector() &&
10093 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10094 isa<ConstantSDNode>(Idx)) {
10095 return Extract128BitVector(In, IdxVal, DAG, dl);
10097 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10098 isa<ConstantSDNode>(Idx)) {
10099 return Extract256BitVector(In, IdxVal, DAG, dl);
10105 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10106 // simple superregister reference or explicit instructions to insert
10107 // the upper bits of a vector.
10108 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10109 SelectionDAG &DAG) {
10110 if (Subtarget->hasFp256()) {
10111 SDLoc dl(Op.getNode());
10112 SDValue Vec = Op.getNode()->getOperand(0);
10113 SDValue SubVec = Op.getNode()->getOperand(1);
10114 SDValue Idx = Op.getNode()->getOperand(2);
10116 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10117 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10118 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10119 isa<ConstantSDNode>(Idx)) {
10120 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10121 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10124 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10125 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10126 isa<ConstantSDNode>(Idx)) {
10127 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10128 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10134 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10135 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10136 // one of the above mentioned nodes. It has to be wrapped because otherwise
10137 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10138 // be used to form addressing mode. These wrapped nodes will be selected
10141 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10142 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10144 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10145 // global base reg.
10146 unsigned char OpFlag = 0;
10147 unsigned WrapperKind = X86ISD::Wrapper;
10148 CodeModel::Model M = DAG.getTarget().getCodeModel();
10150 if (Subtarget->isPICStyleRIPRel() &&
10151 (M == CodeModel::Small || M == CodeModel::Kernel))
10152 WrapperKind = X86ISD::WrapperRIP;
10153 else if (Subtarget->isPICStyleGOT())
10154 OpFlag = X86II::MO_GOTOFF;
10155 else if (Subtarget->isPICStyleStubPIC())
10156 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10158 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10159 CP->getAlignment(),
10160 CP->getOffset(), OpFlag);
10162 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10163 // With PIC, the address is actually $g + Offset.
10165 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10166 DAG.getNode(X86ISD::GlobalBaseReg,
10167 SDLoc(), getPointerTy()),
10174 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10175 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10177 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10178 // global base reg.
10179 unsigned char OpFlag = 0;
10180 unsigned WrapperKind = X86ISD::Wrapper;
10181 CodeModel::Model M = DAG.getTarget().getCodeModel();
10183 if (Subtarget->isPICStyleRIPRel() &&
10184 (M == CodeModel::Small || M == CodeModel::Kernel))
10185 WrapperKind = X86ISD::WrapperRIP;
10186 else if (Subtarget->isPICStyleGOT())
10187 OpFlag = X86II::MO_GOTOFF;
10188 else if (Subtarget->isPICStyleStubPIC())
10189 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10191 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10194 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10196 // With PIC, the address is actually $g + Offset.
10198 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10199 DAG.getNode(X86ISD::GlobalBaseReg,
10200 SDLoc(), getPointerTy()),
10207 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10208 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10210 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10211 // global base reg.
10212 unsigned char OpFlag = 0;
10213 unsigned WrapperKind = X86ISD::Wrapper;
10214 CodeModel::Model M = DAG.getTarget().getCodeModel();
10216 if (Subtarget->isPICStyleRIPRel() &&
10217 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10218 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10219 OpFlag = X86II::MO_GOTPCREL;
10220 WrapperKind = X86ISD::WrapperRIP;
10221 } else if (Subtarget->isPICStyleGOT()) {
10222 OpFlag = X86II::MO_GOT;
10223 } else if (Subtarget->isPICStyleStubPIC()) {
10224 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10225 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10226 OpFlag = X86II::MO_DARWIN_NONLAZY;
10229 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10232 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10234 // With PIC, the address is actually $g + Offset.
10235 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10236 !Subtarget->is64Bit()) {
10237 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10238 DAG.getNode(X86ISD::GlobalBaseReg,
10239 SDLoc(), getPointerTy()),
10243 // For symbols that require a load from a stub to get the address, emit the
10245 if (isGlobalStubReference(OpFlag))
10246 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10247 MachinePointerInfo::getGOT(), false, false, false, 0);
10253 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10254 // Create the TargetBlockAddressAddress node.
10255 unsigned char OpFlags =
10256 Subtarget->ClassifyBlockAddressReference();
10257 CodeModel::Model M = DAG.getTarget().getCodeModel();
10258 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10259 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10261 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10264 if (Subtarget->isPICStyleRIPRel() &&
10265 (M == CodeModel::Small || M == CodeModel::Kernel))
10266 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10268 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10270 // With PIC, the address is actually $g + Offset.
10271 if (isGlobalRelativeToPICBase(OpFlags)) {
10272 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10273 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10281 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10282 int64_t Offset, SelectionDAG &DAG) const {
10283 // Create the TargetGlobalAddress node, folding in the constant
10284 // offset if it is legal.
10285 unsigned char OpFlags =
10286 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10287 CodeModel::Model M = DAG.getTarget().getCodeModel();
10289 if (OpFlags == X86II::MO_NO_FLAG &&
10290 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10291 // A direct static reference to a global.
10292 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10295 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10298 if (Subtarget->isPICStyleRIPRel() &&
10299 (M == CodeModel::Small || M == CodeModel::Kernel))
10300 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10302 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10304 // With PIC, the address is actually $g + Offset.
10305 if (isGlobalRelativeToPICBase(OpFlags)) {
10306 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10307 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10311 // For globals that require a load from a stub to get the address, emit the
10313 if (isGlobalStubReference(OpFlags))
10314 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10315 MachinePointerInfo::getGOT(), false, false, false, 0);
10317 // If there was a non-zero offset that we didn't fold, create an explicit
10318 // addition for it.
10320 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10321 DAG.getConstant(Offset, getPointerTy()));
10327 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10328 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10329 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10330 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10334 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10335 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10336 unsigned char OperandFlags, bool LocalDynamic = false) {
10337 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10338 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10340 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10341 GA->getValueType(0),
10345 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10349 SDValue Ops[] = { Chain, TGA, *InFlag };
10350 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10352 SDValue Ops[] = { Chain, TGA };
10353 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10356 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10357 MFI->setAdjustsStack(true);
10359 SDValue Flag = Chain.getValue(1);
10360 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10363 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10365 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10368 SDLoc dl(GA); // ? function entry point might be better
10369 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10370 DAG.getNode(X86ISD::GlobalBaseReg,
10371 SDLoc(), PtrVT), InFlag);
10372 InFlag = Chain.getValue(1);
10374 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10377 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10379 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10381 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10382 X86::RAX, X86II::MO_TLSGD);
10385 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10391 // Get the start address of the TLS block for this module.
10392 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10393 .getInfo<X86MachineFunctionInfo>();
10394 MFI->incNumLocalDynamicTLSAccesses();
10398 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10399 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10402 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10403 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10404 InFlag = Chain.getValue(1);
10405 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10406 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10409 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10413 unsigned char OperandFlags = X86II::MO_DTPOFF;
10414 unsigned WrapperKind = X86ISD::Wrapper;
10415 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10416 GA->getValueType(0),
10417 GA->getOffset(), OperandFlags);
10418 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10420 // Add x@dtpoff with the base.
10421 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10424 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10425 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10426 const EVT PtrVT, TLSModel::Model model,
10427 bool is64Bit, bool isPIC) {
10430 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10431 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10432 is64Bit ? 257 : 256));
10434 SDValue ThreadPointer =
10435 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10436 MachinePointerInfo(Ptr), false, false, false, 0);
10438 unsigned char OperandFlags = 0;
10439 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10441 unsigned WrapperKind = X86ISD::Wrapper;
10442 if (model == TLSModel::LocalExec) {
10443 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10444 } else if (model == TLSModel::InitialExec) {
10446 OperandFlags = X86II::MO_GOTTPOFF;
10447 WrapperKind = X86ISD::WrapperRIP;
10449 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10452 llvm_unreachable("Unexpected model");
10455 // emit "addl x@ntpoff,%eax" (local exec)
10456 // or "addl x@indntpoff,%eax" (initial exec)
10457 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10459 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10460 GA->getOffset(), OperandFlags);
10461 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10463 if (model == TLSModel::InitialExec) {
10464 if (isPIC && !is64Bit) {
10465 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10466 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10470 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10471 MachinePointerInfo::getGOT(), false, false, false, 0);
10474 // The address of the thread local variable is the add of the thread
10475 // pointer with the offset of the variable.
10476 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10480 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10482 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10483 const GlobalValue *GV = GA->getGlobal();
10485 if (Subtarget->isTargetELF()) {
10486 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10489 case TLSModel::GeneralDynamic:
10490 if (Subtarget->is64Bit())
10491 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10492 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10493 case TLSModel::LocalDynamic:
10494 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10495 Subtarget->is64Bit());
10496 case TLSModel::InitialExec:
10497 case TLSModel::LocalExec:
10498 return LowerToTLSExecModel(
10499 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10500 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10502 llvm_unreachable("Unknown TLS model.");
10505 if (Subtarget->isTargetDarwin()) {
10506 // Darwin only has one model of TLS. Lower to that.
10507 unsigned char OpFlag = 0;
10508 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10509 X86ISD::WrapperRIP : X86ISD::Wrapper;
10511 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10512 // global base reg.
10513 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10514 !Subtarget->is64Bit();
10516 OpFlag = X86II::MO_TLVP_PIC_BASE;
10518 OpFlag = X86II::MO_TLVP;
10520 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10521 GA->getValueType(0),
10522 GA->getOffset(), OpFlag);
10523 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10525 // With PIC32, the address is actually $g + Offset.
10527 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10528 DAG.getNode(X86ISD::GlobalBaseReg,
10529 SDLoc(), getPointerTy()),
10532 // Lowering the machine isd will make sure everything is in the right
10534 SDValue Chain = DAG.getEntryNode();
10535 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10536 SDValue Args[] = { Chain, Offset };
10537 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10539 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10540 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10541 MFI->setAdjustsStack(true);
10543 // And our return value (tls address) is in the standard call return value
10545 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10546 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10547 Chain.getValue(1));
10550 if (Subtarget->isTargetKnownWindowsMSVC() ||
10551 Subtarget->isTargetWindowsGNU()) {
10552 // Just use the implicit TLS architecture
10553 // Need to generate someting similar to:
10554 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10556 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10557 // mov rcx, qword [rdx+rcx*8]
10558 // mov eax, .tls$:tlsvar
10559 // [rax+rcx] contains the address
10560 // Windows 64bit: gs:0x58
10561 // Windows 32bit: fs:__tls_array
10564 SDValue Chain = DAG.getEntryNode();
10566 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10567 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10568 // use its literal value of 0x2C.
10569 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10570 ? Type::getInt8PtrTy(*DAG.getContext(),
10572 : Type::getInt32PtrTy(*DAG.getContext(),
10576 Subtarget->is64Bit()
10577 ? DAG.getIntPtrConstant(0x58)
10578 : (Subtarget->isTargetWindowsGNU()
10579 ? DAG.getIntPtrConstant(0x2C)
10580 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10582 SDValue ThreadPointer =
10583 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10584 MachinePointerInfo(Ptr), false, false, false, 0);
10586 // Load the _tls_index variable
10587 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10588 if (Subtarget->is64Bit())
10589 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10590 IDX, MachinePointerInfo(), MVT::i32,
10593 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10594 false, false, false, 0);
10596 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10598 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10600 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10601 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10602 false, false, false, 0);
10604 // Get the offset of start of .tls section
10605 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10606 GA->getValueType(0),
10607 GA->getOffset(), X86II::MO_SECREL);
10608 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10610 // The address of the thread local variable is the add of the thread
10611 // pointer with the offset of the variable.
10612 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10615 llvm_unreachable("TLS not implemented for this target.");
10618 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10619 /// and take a 2 x i32 value to shift plus a shift amount.
10620 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10621 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10622 MVT VT = Op.getSimpleValueType();
10623 unsigned VTBits = VT.getSizeInBits();
10625 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10626 SDValue ShOpLo = Op.getOperand(0);
10627 SDValue ShOpHi = Op.getOperand(1);
10628 SDValue ShAmt = Op.getOperand(2);
10629 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10630 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10632 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10633 DAG.getConstant(VTBits - 1, MVT::i8));
10634 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10635 DAG.getConstant(VTBits - 1, MVT::i8))
10636 : DAG.getConstant(0, VT);
10638 SDValue Tmp2, Tmp3;
10639 if (Op.getOpcode() == ISD::SHL_PARTS) {
10640 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10641 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10643 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10644 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10647 // If the shift amount is larger or equal than the width of a part we can't
10648 // rely on the results of shld/shrd. Insert a test and select the appropriate
10649 // values for large shift amounts.
10650 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10651 DAG.getConstant(VTBits, MVT::i8));
10652 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10653 AndNode, DAG.getConstant(0, MVT::i8));
10656 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10657 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10658 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10660 if (Op.getOpcode() == ISD::SHL_PARTS) {
10661 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10662 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10664 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10665 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10668 SDValue Ops[2] = { Lo, Hi };
10669 return DAG.getMergeValues(Ops, dl);
10672 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10673 SelectionDAG &DAG) const {
10674 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10676 if (SrcVT.isVector())
10679 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10680 "Unknown SINT_TO_FP to lower!");
10682 // These are really Legal; return the operand so the caller accepts it as
10684 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10686 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10687 Subtarget->is64Bit()) {
10692 unsigned Size = SrcVT.getSizeInBits()/8;
10693 MachineFunction &MF = DAG.getMachineFunction();
10694 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10695 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10696 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10698 MachinePointerInfo::getFixedStack(SSFI),
10700 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10703 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10705 SelectionDAG &DAG) const {
10709 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10711 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10713 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10715 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10717 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10718 MachineMemOperand *MMO;
10720 int SSFI = FI->getIndex();
10722 DAG.getMachineFunction()
10723 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10724 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10726 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10727 StackSlot = StackSlot.getOperand(1);
10729 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10730 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10732 Tys, Ops, SrcVT, MMO);
10735 Chain = Result.getValue(1);
10736 SDValue InFlag = Result.getValue(2);
10738 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10739 // shouldn't be necessary except that RFP cannot be live across
10740 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10741 MachineFunction &MF = DAG.getMachineFunction();
10742 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10743 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10744 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10745 Tys = DAG.getVTList(MVT::Other);
10747 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10749 MachineMemOperand *MMO =
10750 DAG.getMachineFunction()
10751 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10752 MachineMemOperand::MOStore, SSFISize, SSFISize);
10754 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10755 Ops, Op.getValueType(), MMO);
10756 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10757 MachinePointerInfo::getFixedStack(SSFI),
10758 false, false, false, 0);
10764 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10765 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10766 SelectionDAG &DAG) const {
10767 // This algorithm is not obvious. Here it is what we're trying to output:
10770 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10771 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10773 haddpd %xmm0, %xmm0
10775 pshufd $0x4e, %xmm0, %xmm1
10781 LLVMContext *Context = DAG.getContext();
10783 // Build some magic constants.
10784 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10785 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10786 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10788 SmallVector<Constant*,2> CV1;
10790 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10791 APInt(64, 0x4330000000000000ULL))));
10793 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10794 APInt(64, 0x4530000000000000ULL))));
10795 Constant *C1 = ConstantVector::get(CV1);
10796 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10798 // Load the 64-bit value into an XMM register.
10799 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10801 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10802 MachinePointerInfo::getConstantPool(),
10803 false, false, false, 16);
10804 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10805 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10808 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10809 MachinePointerInfo::getConstantPool(),
10810 false, false, false, 16);
10811 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10812 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10815 if (Subtarget->hasSSE3()) {
10816 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10817 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10819 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10820 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10822 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10823 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10827 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10828 DAG.getIntPtrConstant(0));
10831 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10832 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10833 SelectionDAG &DAG) const {
10835 // FP constant to bias correct the final result.
10836 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10839 // Load the 32-bit value into an XMM register.
10840 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10843 // Zero out the upper parts of the register.
10844 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10846 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10847 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10848 DAG.getIntPtrConstant(0));
10850 // Or the load with the bias.
10851 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10852 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10853 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10854 MVT::v2f64, Load)),
10855 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10856 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10857 MVT::v2f64, Bias)));
10858 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10859 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10860 DAG.getIntPtrConstant(0));
10862 // Subtract the bias.
10863 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10865 // Handle final rounding.
10866 EVT DestVT = Op.getValueType();
10868 if (DestVT.bitsLT(MVT::f64))
10869 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10870 DAG.getIntPtrConstant(0));
10871 if (DestVT.bitsGT(MVT::f64))
10872 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10874 // Handle final rounding.
10878 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10879 SelectionDAG &DAG) const {
10880 SDValue N0 = Op.getOperand(0);
10881 MVT SVT = N0.getSimpleValueType();
10884 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10885 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10886 "Custom UINT_TO_FP is not supported!");
10888 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10889 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10890 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10893 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10894 SelectionDAG &DAG) const {
10895 SDValue N0 = Op.getOperand(0);
10898 if (Op.getValueType().isVector())
10899 return lowerUINT_TO_FP_vec(Op, DAG);
10901 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10902 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10903 // the optimization here.
10904 if (DAG.SignBitIsZero(N0))
10905 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10907 MVT SrcVT = N0.getSimpleValueType();
10908 MVT DstVT = Op.getSimpleValueType();
10909 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10910 return LowerUINT_TO_FP_i64(Op, DAG);
10911 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10912 return LowerUINT_TO_FP_i32(Op, DAG);
10913 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10916 // Make a 64-bit buffer, and use it to build an FILD.
10917 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10918 if (SrcVT == MVT::i32) {
10919 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10920 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10921 getPointerTy(), StackSlot, WordOff);
10922 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10923 StackSlot, MachinePointerInfo(),
10925 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10926 OffsetSlot, MachinePointerInfo(),
10928 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10932 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10933 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10934 StackSlot, MachinePointerInfo(),
10936 // For i64 source, we need to add the appropriate power of 2 if the input
10937 // was negative. This is the same as the optimization in
10938 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10939 // we must be careful to do the computation in x87 extended precision, not
10940 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10941 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10942 MachineMemOperand *MMO =
10943 DAG.getMachineFunction()
10944 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10945 MachineMemOperand::MOLoad, 8, 8);
10947 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10948 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10949 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10952 APInt FF(32, 0x5F800000ULL);
10954 // Check whether the sign bit is set.
10955 SDValue SignSet = DAG.getSetCC(dl,
10956 getSetCCResultType(*DAG.getContext(), MVT::i64),
10957 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10960 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10961 SDValue FudgePtr = DAG.getConstantPool(
10962 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10965 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10966 SDValue Zero = DAG.getIntPtrConstant(0);
10967 SDValue Four = DAG.getIntPtrConstant(4);
10968 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10970 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10972 // Load the value out, extending it from f32 to f80.
10973 // FIXME: Avoid the extend by constructing the right constant pool?
10974 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10975 FudgePtr, MachinePointerInfo::getConstantPool(),
10976 MVT::f32, false, false, 4);
10977 // Extend everything to 80 bits to force it to be done on x87.
10978 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10979 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10982 std::pair<SDValue,SDValue>
10983 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10984 bool IsSigned, bool IsReplace) const {
10987 EVT DstTy = Op.getValueType();
10989 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10990 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10994 assert(DstTy.getSimpleVT() <= MVT::i64 &&
10995 DstTy.getSimpleVT() >= MVT::i16 &&
10996 "Unknown FP_TO_INT to lower!");
10998 // These are really Legal.
10999 if (DstTy == MVT::i32 &&
11000 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11001 return std::make_pair(SDValue(), SDValue());
11002 if (Subtarget->is64Bit() &&
11003 DstTy == MVT::i64 &&
11004 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11005 return std::make_pair(SDValue(), SDValue());
11007 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11008 // stack slot, or into the FTOL runtime function.
11009 MachineFunction &MF = DAG.getMachineFunction();
11010 unsigned MemSize = DstTy.getSizeInBits()/8;
11011 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11012 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11015 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11016 Opc = X86ISD::WIN_FTOL;
11018 switch (DstTy.getSimpleVT().SimpleTy) {
11019 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11020 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11021 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11022 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11025 SDValue Chain = DAG.getEntryNode();
11026 SDValue Value = Op.getOperand(0);
11027 EVT TheVT = Op.getOperand(0).getValueType();
11028 // FIXME This causes a redundant load/store if the SSE-class value is already
11029 // in memory, such as if it is on the callstack.
11030 if (isScalarFPTypeInSSEReg(TheVT)) {
11031 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11032 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11033 MachinePointerInfo::getFixedStack(SSFI),
11035 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11037 Chain, StackSlot, DAG.getValueType(TheVT)
11040 MachineMemOperand *MMO =
11041 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11042 MachineMemOperand::MOLoad, MemSize, MemSize);
11043 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11044 Chain = Value.getValue(1);
11045 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11046 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11049 MachineMemOperand *MMO =
11050 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11051 MachineMemOperand::MOStore, MemSize, MemSize);
11053 if (Opc != X86ISD::WIN_FTOL) {
11054 // Build the FP_TO_INT*_IN_MEM
11055 SDValue Ops[] = { Chain, Value, StackSlot };
11056 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11058 return std::make_pair(FIST, StackSlot);
11060 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11061 DAG.getVTList(MVT::Other, MVT::Glue),
11063 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11064 MVT::i32, ftol.getValue(1));
11065 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11066 MVT::i32, eax.getValue(2));
11067 SDValue Ops[] = { eax, edx };
11068 SDValue pair = IsReplace
11069 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11070 : DAG.getMergeValues(Ops, DL);
11071 return std::make_pair(pair, SDValue());
11075 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11076 const X86Subtarget *Subtarget) {
11077 MVT VT = Op->getSimpleValueType(0);
11078 SDValue In = Op->getOperand(0);
11079 MVT InVT = In.getSimpleValueType();
11082 // Optimize vectors in AVX mode:
11085 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11086 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11087 // Concat upper and lower parts.
11090 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11091 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11092 // Concat upper and lower parts.
11095 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11096 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11097 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11100 if (Subtarget->hasInt256())
11101 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11103 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11104 SDValue Undef = DAG.getUNDEF(InVT);
11105 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11106 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11107 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11109 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11110 VT.getVectorNumElements()/2);
11112 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11113 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11115 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11118 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11119 SelectionDAG &DAG) {
11120 MVT VT = Op->getSimpleValueType(0);
11121 SDValue In = Op->getOperand(0);
11122 MVT InVT = In.getSimpleValueType();
11124 unsigned int NumElts = VT.getVectorNumElements();
11125 if (NumElts != 8 && NumElts != 16)
11128 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11129 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11131 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11132 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11133 // Now we have only mask extension
11134 assert(InVT.getVectorElementType() == MVT::i1);
11135 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11136 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11137 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11138 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11139 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11140 MachinePointerInfo::getConstantPool(),
11141 false, false, false, Alignment);
11143 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11144 if (VT.is512BitVector())
11146 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11149 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11150 SelectionDAG &DAG) {
11151 if (Subtarget->hasFp256()) {
11152 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11160 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11161 SelectionDAG &DAG) {
11163 MVT VT = Op.getSimpleValueType();
11164 SDValue In = Op.getOperand(0);
11165 MVT SVT = In.getSimpleValueType();
11167 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11168 return LowerZERO_EXTEND_AVX512(Op, DAG);
11170 if (Subtarget->hasFp256()) {
11171 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11176 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11177 VT.getVectorNumElements() != SVT.getVectorNumElements());
11181 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11183 MVT VT = Op.getSimpleValueType();
11184 SDValue In = Op.getOperand(0);
11185 MVT InVT = In.getSimpleValueType();
11187 if (VT == MVT::i1) {
11188 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11189 "Invalid scalar TRUNCATE operation");
11190 if (InVT == MVT::i32)
11192 if (InVT.getSizeInBits() == 64)
11193 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11194 else if (InVT.getSizeInBits() < 32)
11195 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11196 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11198 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11199 "Invalid TRUNCATE operation");
11201 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11202 if (VT.getVectorElementType().getSizeInBits() >=8)
11203 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11205 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11206 unsigned NumElts = InVT.getVectorNumElements();
11207 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11208 if (InVT.getSizeInBits() < 512) {
11209 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11210 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11214 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11215 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11216 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11217 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11218 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11219 MachinePointerInfo::getConstantPool(),
11220 false, false, false, Alignment);
11221 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11222 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11223 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11226 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11227 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11228 if (Subtarget->hasInt256()) {
11229 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11230 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11231 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11233 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11234 DAG.getIntPtrConstant(0));
11237 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11238 DAG.getIntPtrConstant(0));
11239 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11240 DAG.getIntPtrConstant(2));
11241 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11242 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11243 static const int ShufMask[] = {0, 2, 4, 6};
11244 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11247 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11248 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11249 if (Subtarget->hasInt256()) {
11250 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11252 SmallVector<SDValue,32> pshufbMask;
11253 for (unsigned i = 0; i < 2; ++i) {
11254 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11255 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11256 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11257 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11258 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11259 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11260 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11261 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11262 for (unsigned j = 0; j < 8; ++j)
11263 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11265 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11266 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11267 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11269 static const int ShufMask[] = {0, 2, -1, -1};
11270 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11272 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11273 DAG.getIntPtrConstant(0));
11274 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11277 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11278 DAG.getIntPtrConstant(0));
11280 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11281 DAG.getIntPtrConstant(4));
11283 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11284 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11286 // The PSHUFB mask:
11287 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11288 -1, -1, -1, -1, -1, -1, -1, -1};
11290 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11291 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11292 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11294 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11295 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11297 // The MOVLHPS Mask:
11298 static const int ShufMask2[] = {0, 1, 4, 5};
11299 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11300 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11303 // Handle truncation of V256 to V128 using shuffles.
11304 if (!VT.is128BitVector() || !InVT.is256BitVector())
11307 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11309 unsigned NumElems = VT.getVectorNumElements();
11310 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11312 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11313 // Prepare truncation shuffle mask
11314 for (unsigned i = 0; i != NumElems; ++i)
11315 MaskVec[i] = i * 2;
11316 SDValue V = DAG.getVectorShuffle(NVT, DL,
11317 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11318 DAG.getUNDEF(NVT), &MaskVec[0]);
11319 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11320 DAG.getIntPtrConstant(0));
11323 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11324 SelectionDAG &DAG) const {
11325 assert(!Op.getSimpleValueType().isVector());
11327 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11328 /*IsSigned=*/ true, /*IsReplace=*/ false);
11329 SDValue FIST = Vals.first, StackSlot = Vals.second;
11330 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11331 if (!FIST.getNode()) return Op;
11333 if (StackSlot.getNode())
11334 // Load the result.
11335 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11336 FIST, StackSlot, MachinePointerInfo(),
11337 false, false, false, 0);
11339 // The node is the result.
11343 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11344 SelectionDAG &DAG) const {
11345 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11346 /*IsSigned=*/ false, /*IsReplace=*/ false);
11347 SDValue FIST = Vals.first, StackSlot = Vals.second;
11348 assert(FIST.getNode() && "Unexpected failure");
11350 if (StackSlot.getNode())
11351 // Load the result.
11352 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11353 FIST, StackSlot, MachinePointerInfo(),
11354 false, false, false, 0);
11356 // The node is the result.
11360 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11362 MVT VT = Op.getSimpleValueType();
11363 SDValue In = Op.getOperand(0);
11364 MVT SVT = In.getSimpleValueType();
11366 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11368 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11369 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11370 In, DAG.getUNDEF(SVT)));
11373 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11374 LLVMContext *Context = DAG.getContext();
11376 MVT VT = Op.getSimpleValueType();
11378 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11379 if (VT.isVector()) {
11380 EltVT = VT.getVectorElementType();
11381 NumElts = VT.getVectorNumElements();
11384 if (EltVT == MVT::f64)
11385 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11386 APInt(64, ~(1ULL << 63))));
11388 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11389 APInt(32, ~(1U << 31))));
11390 C = ConstantVector::getSplat(NumElts, C);
11391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11392 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11393 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11394 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11395 MachinePointerInfo::getConstantPool(),
11396 false, false, false, Alignment);
11397 if (VT.isVector()) {
11398 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11399 return DAG.getNode(ISD::BITCAST, dl, VT,
11400 DAG.getNode(ISD::AND, dl, ANDVT,
11401 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11403 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11405 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11408 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11409 LLVMContext *Context = DAG.getContext();
11411 MVT VT = Op.getSimpleValueType();
11413 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11414 if (VT.isVector()) {
11415 EltVT = VT.getVectorElementType();
11416 NumElts = VT.getVectorNumElements();
11419 if (EltVT == MVT::f64)
11420 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11421 APInt(64, 1ULL << 63)));
11423 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11424 APInt(32, 1U << 31)));
11425 C = ConstantVector::getSplat(NumElts, C);
11426 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11427 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11428 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11429 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11430 MachinePointerInfo::getConstantPool(),
11431 false, false, false, Alignment);
11432 if (VT.isVector()) {
11433 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11434 return DAG.getNode(ISD::BITCAST, dl, VT,
11435 DAG.getNode(ISD::XOR, dl, XORVT,
11436 DAG.getNode(ISD::BITCAST, dl, XORVT,
11438 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11441 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11444 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11445 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11446 LLVMContext *Context = DAG.getContext();
11447 SDValue Op0 = Op.getOperand(0);
11448 SDValue Op1 = Op.getOperand(1);
11450 MVT VT = Op.getSimpleValueType();
11451 MVT SrcVT = Op1.getSimpleValueType();
11453 // If second operand is smaller, extend it first.
11454 if (SrcVT.bitsLT(VT)) {
11455 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11458 // And if it is bigger, shrink it first.
11459 if (SrcVT.bitsGT(VT)) {
11460 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11464 // At this point the operands and the result should have the same
11465 // type, and that won't be f80 since that is not custom lowered.
11467 // First get the sign bit of second operand.
11468 SmallVector<Constant*,4> CV;
11469 if (SrcVT == MVT::f64) {
11470 const fltSemantics &Sem = APFloat::IEEEdouble;
11471 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11472 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11474 const fltSemantics &Sem = APFloat::IEEEsingle;
11475 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11476 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11477 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11478 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11480 Constant *C = ConstantVector::get(CV);
11481 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11482 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11483 MachinePointerInfo::getConstantPool(),
11484 false, false, false, 16);
11485 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11487 // Shift sign bit right or left if the two operands have different types.
11488 if (SrcVT.bitsGT(VT)) {
11489 // Op0 is MVT::f32, Op1 is MVT::f64.
11490 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11491 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11492 DAG.getConstant(32, MVT::i32));
11493 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11494 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11495 DAG.getIntPtrConstant(0));
11498 // Clear first operand sign bit.
11500 if (VT == MVT::f64) {
11501 const fltSemantics &Sem = APFloat::IEEEdouble;
11502 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11503 APInt(64, ~(1ULL << 63)))));
11504 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11506 const fltSemantics &Sem = APFloat::IEEEsingle;
11507 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11508 APInt(32, ~(1U << 31)))));
11509 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11510 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11511 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11513 C = ConstantVector::get(CV);
11514 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11515 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11516 MachinePointerInfo::getConstantPool(),
11517 false, false, false, 16);
11518 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11520 // Or the value with the sign bit.
11521 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11524 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11525 SDValue N0 = Op.getOperand(0);
11527 MVT VT = Op.getSimpleValueType();
11529 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11530 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11531 DAG.getConstant(1, VT));
11532 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11535 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11537 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11538 SelectionDAG &DAG) {
11539 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11541 if (!Subtarget->hasSSE41())
11544 if (!Op->hasOneUse())
11547 SDNode *N = Op.getNode();
11550 SmallVector<SDValue, 8> Opnds;
11551 DenseMap<SDValue, unsigned> VecInMap;
11552 SmallVector<SDValue, 8> VecIns;
11553 EVT VT = MVT::Other;
11555 // Recognize a special case where a vector is casted into wide integer to
11557 Opnds.push_back(N->getOperand(0));
11558 Opnds.push_back(N->getOperand(1));
11560 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11561 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11562 // BFS traverse all OR'd operands.
11563 if (I->getOpcode() == ISD::OR) {
11564 Opnds.push_back(I->getOperand(0));
11565 Opnds.push_back(I->getOperand(1));
11566 // Re-evaluate the number of nodes to be traversed.
11567 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11571 // Quit if a non-EXTRACT_VECTOR_ELT
11572 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11575 // Quit if without a constant index.
11576 SDValue Idx = I->getOperand(1);
11577 if (!isa<ConstantSDNode>(Idx))
11580 SDValue ExtractedFromVec = I->getOperand(0);
11581 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11582 if (M == VecInMap.end()) {
11583 VT = ExtractedFromVec.getValueType();
11584 // Quit if not 128/256-bit vector.
11585 if (!VT.is128BitVector() && !VT.is256BitVector())
11587 // Quit if not the same type.
11588 if (VecInMap.begin() != VecInMap.end() &&
11589 VT != VecInMap.begin()->first.getValueType())
11591 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11592 VecIns.push_back(ExtractedFromVec);
11594 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11597 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11598 "Not extracted from 128-/256-bit vector.");
11600 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11602 for (DenseMap<SDValue, unsigned>::const_iterator
11603 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11604 // Quit if not all elements are used.
11605 if (I->second != FullMask)
11609 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11611 // Cast all vectors into TestVT for PTEST.
11612 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11613 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11615 // If more than one full vectors are evaluated, OR them first before PTEST.
11616 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11617 // Each iteration will OR 2 nodes and append the result until there is only
11618 // 1 node left, i.e. the final OR'd value of all vectors.
11619 SDValue LHS = VecIns[Slot];
11620 SDValue RHS = VecIns[Slot + 1];
11621 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11624 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11625 VecIns.back(), VecIns.back());
11628 /// \brief return true if \c Op has a use that doesn't just read flags.
11629 static bool hasNonFlagsUse(SDValue Op) {
11630 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11632 SDNode *User = *UI;
11633 unsigned UOpNo = UI.getOperandNo();
11634 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11635 // Look pass truncate.
11636 UOpNo = User->use_begin().getOperandNo();
11637 User = *User->use_begin();
11640 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11641 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11647 /// Emit nodes that will be selected as "test Op0,Op0", or something
11649 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11650 SelectionDAG &DAG) const {
11651 if (Op.getValueType() == MVT::i1)
11652 // KORTEST instruction should be selected
11653 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11654 DAG.getConstant(0, Op.getValueType()));
11656 // CF and OF aren't always set the way we want. Determine which
11657 // of these we need.
11658 bool NeedCF = false;
11659 bool NeedOF = false;
11662 case X86::COND_A: case X86::COND_AE:
11663 case X86::COND_B: case X86::COND_BE:
11666 case X86::COND_G: case X86::COND_GE:
11667 case X86::COND_L: case X86::COND_LE:
11668 case X86::COND_O: case X86::COND_NO: {
11669 // Check if we really need to set the
11670 // Overflow flag. If NoSignedWrap is present
11671 // that is not actually needed.
11672 switch (Op->getOpcode()) {
11677 const BinaryWithFlagsSDNode *BinNode =
11678 cast<BinaryWithFlagsSDNode>(Op.getNode());
11679 if (BinNode->hasNoSignedWrap())
11689 // See if we can use the EFLAGS value from the operand instead of
11690 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11691 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11692 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11693 // Emit a CMP with 0, which is the TEST pattern.
11694 //if (Op.getValueType() == MVT::i1)
11695 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11696 // DAG.getConstant(0, MVT::i1));
11697 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11698 DAG.getConstant(0, Op.getValueType()));
11700 unsigned Opcode = 0;
11701 unsigned NumOperands = 0;
11703 // Truncate operations may prevent the merge of the SETCC instruction
11704 // and the arithmetic instruction before it. Attempt to truncate the operands
11705 // of the arithmetic instruction and use a reduced bit-width instruction.
11706 bool NeedTruncation = false;
11707 SDValue ArithOp = Op;
11708 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11709 SDValue Arith = Op->getOperand(0);
11710 // Both the trunc and the arithmetic op need to have one user each.
11711 if (Arith->hasOneUse())
11712 switch (Arith.getOpcode()) {
11719 NeedTruncation = true;
11725 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11726 // which may be the result of a CAST. We use the variable 'Op', which is the
11727 // non-casted variable when we check for possible users.
11728 switch (ArithOp.getOpcode()) {
11730 // Due to an isel shortcoming, be conservative if this add is likely to be
11731 // selected as part of a load-modify-store instruction. When the root node
11732 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11733 // uses of other nodes in the match, such as the ADD in this case. This
11734 // leads to the ADD being left around and reselected, with the result being
11735 // two adds in the output. Alas, even if none our users are stores, that
11736 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11737 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11738 // climbing the DAG back to the root, and it doesn't seem to be worth the
11740 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11741 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11742 if (UI->getOpcode() != ISD::CopyToReg &&
11743 UI->getOpcode() != ISD::SETCC &&
11744 UI->getOpcode() != ISD::STORE)
11747 if (ConstantSDNode *C =
11748 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11749 // An add of one will be selected as an INC.
11750 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11751 Opcode = X86ISD::INC;
11756 // An add of negative one (subtract of one) will be selected as a DEC.
11757 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11758 Opcode = X86ISD::DEC;
11764 // Otherwise use a regular EFLAGS-setting add.
11765 Opcode = X86ISD::ADD;
11770 // If we have a constant logical shift that's only used in a comparison
11771 // against zero turn it into an equivalent AND. This allows turning it into
11772 // a TEST instruction later.
11773 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11774 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11775 EVT VT = Op.getValueType();
11776 unsigned BitWidth = VT.getSizeInBits();
11777 unsigned ShAmt = Op->getConstantOperandVal(1);
11778 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11780 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11781 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11782 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11783 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11785 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11786 DAG.getConstant(Mask, VT));
11787 DAG.ReplaceAllUsesWith(Op, New);
11793 // If the primary and result isn't used, don't bother using X86ISD::AND,
11794 // because a TEST instruction will be better.
11795 if (!hasNonFlagsUse(Op))
11801 // Due to the ISEL shortcoming noted above, be conservative if this op is
11802 // likely to be selected as part of a load-modify-store instruction.
11803 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11804 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11805 if (UI->getOpcode() == ISD::STORE)
11808 // Otherwise use a regular EFLAGS-setting instruction.
11809 switch (ArithOp.getOpcode()) {
11810 default: llvm_unreachable("unexpected operator!");
11811 case ISD::SUB: Opcode = X86ISD::SUB; break;
11812 case ISD::XOR: Opcode = X86ISD::XOR; break;
11813 case ISD::AND: Opcode = X86ISD::AND; break;
11815 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11816 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11817 if (EFLAGS.getNode())
11820 Opcode = X86ISD::OR;
11834 return SDValue(Op.getNode(), 1);
11840 // If we found that truncation is beneficial, perform the truncation and
11842 if (NeedTruncation) {
11843 EVT VT = Op.getValueType();
11844 SDValue WideVal = Op->getOperand(0);
11845 EVT WideVT = WideVal.getValueType();
11846 unsigned ConvertedOp = 0;
11847 // Use a target machine opcode to prevent further DAGCombine
11848 // optimizations that may separate the arithmetic operations
11849 // from the setcc node.
11850 switch (WideVal.getOpcode()) {
11852 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11853 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11854 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11855 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11856 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11861 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11862 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11863 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11864 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11870 // Emit a CMP with 0, which is the TEST pattern.
11871 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11872 DAG.getConstant(0, Op.getValueType()));
11874 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11875 SmallVector<SDValue, 4> Ops;
11876 for (unsigned i = 0; i != NumOperands; ++i)
11877 Ops.push_back(Op.getOperand(i));
11879 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11880 DAG.ReplaceAllUsesWith(Op, New);
11881 return SDValue(New.getNode(), 1);
11884 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11886 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11887 SDLoc dl, SelectionDAG &DAG) const {
11888 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11889 if (C->getAPIntValue() == 0)
11890 return EmitTest(Op0, X86CC, dl, DAG);
11892 if (Op0.getValueType() == MVT::i1)
11893 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11896 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11897 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11898 // Do the comparison at i32 if it's smaller, besides the Atom case.
11899 // This avoids subregister aliasing issues. Keep the smaller reference
11900 // if we're optimizing for size, however, as that'll allow better folding
11901 // of memory operations.
11902 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11903 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11904 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11905 !Subtarget->isAtom()) {
11906 unsigned ExtendOp =
11907 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11908 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11909 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11911 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11912 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11913 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11915 return SDValue(Sub.getNode(), 1);
11917 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11920 /// Convert a comparison if required by the subtarget.
11921 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11922 SelectionDAG &DAG) const {
11923 // If the subtarget does not support the FUCOMI instruction, floating-point
11924 // comparisons have to be converted.
11925 if (Subtarget->hasCMov() ||
11926 Cmp.getOpcode() != X86ISD::CMP ||
11927 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11928 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11931 // The instruction selector will select an FUCOM instruction instead of
11932 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11933 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11934 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11936 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11937 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11938 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11939 DAG.getConstant(8, MVT::i8));
11940 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11941 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11944 static bool isAllOnes(SDValue V) {
11945 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11946 return C && C->isAllOnesValue();
11949 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11950 /// if it's possible.
11951 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11952 SDLoc dl, SelectionDAG &DAG) const {
11953 SDValue Op0 = And.getOperand(0);
11954 SDValue Op1 = And.getOperand(1);
11955 if (Op0.getOpcode() == ISD::TRUNCATE)
11956 Op0 = Op0.getOperand(0);
11957 if (Op1.getOpcode() == ISD::TRUNCATE)
11958 Op1 = Op1.getOperand(0);
11961 if (Op1.getOpcode() == ISD::SHL)
11962 std::swap(Op0, Op1);
11963 if (Op0.getOpcode() == ISD::SHL) {
11964 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11965 if (And00C->getZExtValue() == 1) {
11966 // If we looked past a truncate, check that it's only truncating away
11968 unsigned BitWidth = Op0.getValueSizeInBits();
11969 unsigned AndBitWidth = And.getValueSizeInBits();
11970 if (BitWidth > AndBitWidth) {
11972 DAG.computeKnownBits(Op0, Zeros, Ones);
11973 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11977 RHS = Op0.getOperand(1);
11979 } else if (Op1.getOpcode() == ISD::Constant) {
11980 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11981 uint64_t AndRHSVal = AndRHS->getZExtValue();
11982 SDValue AndLHS = Op0;
11984 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11985 LHS = AndLHS.getOperand(0);
11986 RHS = AndLHS.getOperand(1);
11989 // Use BT if the immediate can't be encoded in a TEST instruction.
11990 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11992 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11996 if (LHS.getNode()) {
11997 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
11998 // instruction. Since the shift amount is in-range-or-undefined, we know
11999 // that doing a bittest on the i32 value is ok. We extend to i32 because
12000 // the encoding for the i16 version is larger than the i32 version.
12001 // Also promote i16 to i32 for performance / code size reason.
12002 if (LHS.getValueType() == MVT::i8 ||
12003 LHS.getValueType() == MVT::i16)
12004 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12006 // If the operand types disagree, extend the shift amount to match. Since
12007 // BT ignores high bits (like shifts) we can use anyextend.
12008 if (LHS.getValueType() != RHS.getValueType())
12009 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12011 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12012 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12013 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12014 DAG.getConstant(Cond, MVT::i8), BT);
12020 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12022 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12027 // SSE Condition code mapping:
12036 switch (SetCCOpcode) {
12037 default: llvm_unreachable("Unexpected SETCC condition");
12039 case ISD::SETEQ: SSECC = 0; break;
12041 case ISD::SETGT: Swap = true; // Fallthrough
12043 case ISD::SETOLT: SSECC = 1; break;
12045 case ISD::SETGE: Swap = true; // Fallthrough
12047 case ISD::SETOLE: SSECC = 2; break;
12048 case ISD::SETUO: SSECC = 3; break;
12050 case ISD::SETNE: SSECC = 4; break;
12051 case ISD::SETULE: Swap = true; // Fallthrough
12052 case ISD::SETUGE: SSECC = 5; break;
12053 case ISD::SETULT: Swap = true; // Fallthrough
12054 case ISD::SETUGT: SSECC = 6; break;
12055 case ISD::SETO: SSECC = 7; break;
12057 case ISD::SETONE: SSECC = 8; break;
12060 std::swap(Op0, Op1);
12065 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12066 // ones, and then concatenate the result back.
12067 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12068 MVT VT = Op.getSimpleValueType();
12070 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12071 "Unsupported value type for operation");
12073 unsigned NumElems = VT.getVectorNumElements();
12075 SDValue CC = Op.getOperand(2);
12077 // Extract the LHS vectors
12078 SDValue LHS = Op.getOperand(0);
12079 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12080 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12082 // Extract the RHS vectors
12083 SDValue RHS = Op.getOperand(1);
12084 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12085 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12087 // Issue the operation on the smaller types and concatenate the result back
12088 MVT EltVT = VT.getVectorElementType();
12089 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12090 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12091 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12092 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12095 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12096 const X86Subtarget *Subtarget) {
12097 SDValue Op0 = Op.getOperand(0);
12098 SDValue Op1 = Op.getOperand(1);
12099 SDValue CC = Op.getOperand(2);
12100 MVT VT = Op.getSimpleValueType();
12103 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12104 Op.getValueType().getScalarType() == MVT::i1 &&
12105 "Cannot set masked compare for this operation");
12107 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12109 bool Unsigned = false;
12112 switch (SetCCOpcode) {
12113 default: llvm_unreachable("Unexpected SETCC condition");
12114 case ISD::SETNE: SSECC = 4; break;
12115 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12116 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12117 case ISD::SETLT: Swap = true; //fall-through
12118 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12119 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12120 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12121 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12122 case ISD::SETULE: Unsigned = true; //fall-through
12123 case ISD::SETLE: SSECC = 2; break;
12127 std::swap(Op0, Op1);
12129 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12130 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12131 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12132 DAG.getConstant(SSECC, MVT::i8));
12135 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12136 /// operand \p Op1. If non-trivial (for example because it's not constant)
12137 /// return an empty value.
12138 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12140 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12144 MVT VT = Op1.getSimpleValueType();
12145 MVT EVT = VT.getVectorElementType();
12146 unsigned n = VT.getVectorNumElements();
12147 SmallVector<SDValue, 8> ULTOp1;
12149 for (unsigned i = 0; i < n; ++i) {
12150 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12151 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12154 // Avoid underflow.
12155 APInt Val = Elt->getAPIntValue();
12159 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12162 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12165 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12166 SelectionDAG &DAG) {
12167 SDValue Op0 = Op.getOperand(0);
12168 SDValue Op1 = Op.getOperand(1);
12169 SDValue CC = Op.getOperand(2);
12170 MVT VT = Op.getSimpleValueType();
12171 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12172 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12177 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12178 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12181 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12182 unsigned Opc = X86ISD::CMPP;
12183 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12184 assert(VT.getVectorNumElements() <= 16);
12185 Opc = X86ISD::CMPM;
12187 // In the two special cases we can't handle, emit two comparisons.
12190 unsigned CombineOpc;
12191 if (SetCCOpcode == ISD::SETUEQ) {
12192 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12194 assert(SetCCOpcode == ISD::SETONE);
12195 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12198 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12199 DAG.getConstant(CC0, MVT::i8));
12200 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12201 DAG.getConstant(CC1, MVT::i8));
12202 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12204 // Handle all other FP comparisons here.
12205 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12206 DAG.getConstant(SSECC, MVT::i8));
12209 // Break 256-bit integer vector compare into smaller ones.
12210 if (VT.is256BitVector() && !Subtarget->hasInt256())
12211 return Lower256IntVSETCC(Op, DAG);
12213 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12214 EVT OpVT = Op1.getValueType();
12215 if (Subtarget->hasAVX512()) {
12216 if (Op1.getValueType().is512BitVector() ||
12217 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12218 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12220 // In AVX-512 architecture setcc returns mask with i1 elements,
12221 // But there is no compare instruction for i8 and i16 elements.
12222 // We are not talking about 512-bit operands in this case, these
12223 // types are illegal.
12225 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12226 OpVT.getVectorElementType().getSizeInBits() >= 8))
12227 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12228 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12231 // We are handling one of the integer comparisons here. Since SSE only has
12232 // GT and EQ comparisons for integer, swapping operands and multiple
12233 // operations may be required for some comparisons.
12235 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12236 bool Subus = false;
12238 switch (SetCCOpcode) {
12239 default: llvm_unreachable("Unexpected SETCC condition");
12240 case ISD::SETNE: Invert = true;
12241 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12242 case ISD::SETLT: Swap = true;
12243 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12244 case ISD::SETGE: Swap = true;
12245 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12246 Invert = true; break;
12247 case ISD::SETULT: Swap = true;
12248 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12249 FlipSigns = true; break;
12250 case ISD::SETUGE: Swap = true;
12251 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12252 FlipSigns = true; Invert = true; break;
12255 // Special case: Use min/max operations for SETULE/SETUGE
12256 MVT VET = VT.getVectorElementType();
12258 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12259 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12262 switch (SetCCOpcode) {
12264 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12265 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12268 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12271 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12272 if (!MinMax && hasSubus) {
12273 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12275 // t = psubus Op0, Op1
12276 // pcmpeq t, <0..0>
12277 switch (SetCCOpcode) {
12279 case ISD::SETULT: {
12280 // If the comparison is against a constant we can turn this into a
12281 // setule. With psubus, setule does not require a swap. This is
12282 // beneficial because the constant in the register is no longer
12283 // destructed as the destination so it can be hoisted out of a loop.
12284 // Only do this pre-AVX since vpcmp* is no longer destructive.
12285 if (Subtarget->hasAVX())
12287 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12288 if (ULEOp1.getNode()) {
12290 Subus = true; Invert = false; Swap = false;
12294 // Psubus is better than flip-sign because it requires no inversion.
12295 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12296 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12300 Opc = X86ISD::SUBUS;
12306 std::swap(Op0, Op1);
12308 // Check that the operation in question is available (most are plain SSE2,
12309 // but PCMPGTQ and PCMPEQQ have different requirements).
12310 if (VT == MVT::v2i64) {
12311 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12312 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12314 // First cast everything to the right type.
12315 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12316 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12318 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12319 // bits of the inputs before performing those operations. The lower
12320 // compare is always unsigned.
12323 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12325 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12326 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12327 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12328 Sign, Zero, Sign, Zero);
12330 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12331 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12333 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12334 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12335 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12337 // Create masks for only the low parts/high parts of the 64 bit integers.
12338 static const int MaskHi[] = { 1, 1, 3, 3 };
12339 static const int MaskLo[] = { 0, 0, 2, 2 };
12340 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12341 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12342 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12344 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12345 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12348 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12350 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12353 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12354 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12355 // pcmpeqd + pshufd + pand.
12356 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12358 // First cast everything to the right type.
12359 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12360 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12363 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12365 // Make sure the lower and upper halves are both all-ones.
12366 static const int Mask[] = { 1, 0, 3, 2 };
12367 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12368 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12371 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12373 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12377 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12378 // bits of the inputs before performing those operations.
12380 EVT EltVT = VT.getVectorElementType();
12381 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12382 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12383 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12386 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12388 // If the logical-not of the result is required, perform that now.
12390 Result = DAG.getNOT(dl, Result, VT);
12393 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12396 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12397 getZeroVector(VT, Subtarget, DAG, dl));
12402 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12404 MVT VT = Op.getSimpleValueType();
12406 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12408 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12409 && "SetCC type must be 8-bit or 1-bit integer");
12410 SDValue Op0 = Op.getOperand(0);
12411 SDValue Op1 = Op.getOperand(1);
12413 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12415 // Optimize to BT if possible.
12416 // Lower (X & (1 << N)) == 0 to BT(X, N).
12417 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12418 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12419 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12420 Op1.getOpcode() == ISD::Constant &&
12421 cast<ConstantSDNode>(Op1)->isNullValue() &&
12422 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12423 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12424 if (NewSetCC.getNode())
12428 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12430 if (Op1.getOpcode() == ISD::Constant &&
12431 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12432 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12433 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12435 // If the input is a setcc, then reuse the input setcc or use a new one with
12436 // the inverted condition.
12437 if (Op0.getOpcode() == X86ISD::SETCC) {
12438 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12439 bool Invert = (CC == ISD::SETNE) ^
12440 cast<ConstantSDNode>(Op1)->isNullValue();
12444 CCode = X86::GetOppositeBranchCondition(CCode);
12445 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12446 DAG.getConstant(CCode, MVT::i8),
12447 Op0.getOperand(1));
12449 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12453 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12454 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12455 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12457 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12458 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12461 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12462 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12463 if (X86CC == X86::COND_INVALID)
12466 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12467 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12468 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12469 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12471 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12475 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12476 static bool isX86LogicalCmp(SDValue Op) {
12477 unsigned Opc = Op.getNode()->getOpcode();
12478 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12479 Opc == X86ISD::SAHF)
12481 if (Op.getResNo() == 1 &&
12482 (Opc == X86ISD::ADD ||
12483 Opc == X86ISD::SUB ||
12484 Opc == X86ISD::ADC ||
12485 Opc == X86ISD::SBB ||
12486 Opc == X86ISD::SMUL ||
12487 Opc == X86ISD::UMUL ||
12488 Opc == X86ISD::INC ||
12489 Opc == X86ISD::DEC ||
12490 Opc == X86ISD::OR ||
12491 Opc == X86ISD::XOR ||
12492 Opc == X86ISD::AND))
12495 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12501 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12502 if (V.getOpcode() != ISD::TRUNCATE)
12505 SDValue VOp0 = V.getOperand(0);
12506 unsigned InBits = VOp0.getValueSizeInBits();
12507 unsigned Bits = V.getValueSizeInBits();
12508 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12511 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12512 bool addTest = true;
12513 SDValue Cond = Op.getOperand(0);
12514 SDValue Op1 = Op.getOperand(1);
12515 SDValue Op2 = Op.getOperand(2);
12517 EVT VT = Op1.getValueType();
12520 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12521 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12522 // sequence later on.
12523 if (Cond.getOpcode() == ISD::SETCC &&
12524 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12525 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12526 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12527 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12528 int SSECC = translateX86FSETCC(
12529 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12532 if (Subtarget->hasAVX512()) {
12533 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12534 DAG.getConstant(SSECC, MVT::i8));
12535 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12537 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12538 DAG.getConstant(SSECC, MVT::i8));
12539 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12540 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12541 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12545 if (Cond.getOpcode() == ISD::SETCC) {
12546 SDValue NewCond = LowerSETCC(Cond, DAG);
12547 if (NewCond.getNode())
12551 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12552 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12553 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12554 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12555 if (Cond.getOpcode() == X86ISD::SETCC &&
12556 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12557 isZero(Cond.getOperand(1).getOperand(1))) {
12558 SDValue Cmp = Cond.getOperand(1);
12560 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12562 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12563 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12564 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12566 SDValue CmpOp0 = Cmp.getOperand(0);
12567 // Apply further optimizations for special cases
12568 // (select (x != 0), -1, 0) -> neg & sbb
12569 // (select (x == 0), 0, -1) -> neg & sbb
12570 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12571 if (YC->isNullValue() &&
12572 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12573 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12574 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12575 DAG.getConstant(0, CmpOp0.getValueType()),
12577 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12578 DAG.getConstant(X86::COND_B, MVT::i8),
12579 SDValue(Neg.getNode(), 1));
12583 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12584 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12585 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12587 SDValue Res = // Res = 0 or -1.
12588 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12589 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12591 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12592 Res = DAG.getNOT(DL, Res, Res.getValueType());
12594 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12595 if (!N2C || !N2C->isNullValue())
12596 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12601 // Look past (and (setcc_carry (cmp ...)), 1).
12602 if (Cond.getOpcode() == ISD::AND &&
12603 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12604 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12605 if (C && C->getAPIntValue() == 1)
12606 Cond = Cond.getOperand(0);
12609 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12610 // setting operand in place of the X86ISD::SETCC.
12611 unsigned CondOpcode = Cond.getOpcode();
12612 if (CondOpcode == X86ISD::SETCC ||
12613 CondOpcode == X86ISD::SETCC_CARRY) {
12614 CC = Cond.getOperand(0);
12616 SDValue Cmp = Cond.getOperand(1);
12617 unsigned Opc = Cmp.getOpcode();
12618 MVT VT = Op.getSimpleValueType();
12620 bool IllegalFPCMov = false;
12621 if (VT.isFloatingPoint() && !VT.isVector() &&
12622 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12623 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12625 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12626 Opc == X86ISD::BT) { // FIXME
12630 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12631 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12632 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12633 Cond.getOperand(0).getValueType() != MVT::i8)) {
12634 SDValue LHS = Cond.getOperand(0);
12635 SDValue RHS = Cond.getOperand(1);
12636 unsigned X86Opcode;
12639 switch (CondOpcode) {
12640 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12641 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12642 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12643 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12644 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12645 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12646 default: llvm_unreachable("unexpected overflowing operator");
12648 if (CondOpcode == ISD::UMULO)
12649 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12652 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12654 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12656 if (CondOpcode == ISD::UMULO)
12657 Cond = X86Op.getValue(2);
12659 Cond = X86Op.getValue(1);
12661 CC = DAG.getConstant(X86Cond, MVT::i8);
12666 // Look pass the truncate if the high bits are known zero.
12667 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12668 Cond = Cond.getOperand(0);
12670 // We know the result of AND is compared against zero. Try to match
12672 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12673 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12674 if (NewSetCC.getNode()) {
12675 CC = NewSetCC.getOperand(0);
12676 Cond = NewSetCC.getOperand(1);
12683 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12684 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12687 // a < b ? -1 : 0 -> RES = ~setcc_carry
12688 // a < b ? 0 : -1 -> RES = setcc_carry
12689 // a >= b ? -1 : 0 -> RES = setcc_carry
12690 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12691 if (Cond.getOpcode() == X86ISD::SUB) {
12692 Cond = ConvertCmpIfNecessary(Cond, DAG);
12693 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12695 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12696 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12697 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12698 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12699 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12700 return DAG.getNOT(DL, Res, Res.getValueType());
12705 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12706 // widen the cmov and push the truncate through. This avoids introducing a new
12707 // branch during isel and doesn't add any extensions.
12708 if (Op.getValueType() == MVT::i8 &&
12709 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12710 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12711 if (T1.getValueType() == T2.getValueType() &&
12712 // Blacklist CopyFromReg to avoid partial register stalls.
12713 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12714 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12715 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12716 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12720 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12721 // condition is true.
12722 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12723 SDValue Ops[] = { Op2, Op1, CC, Cond };
12724 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12727 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12728 MVT VT = Op->getSimpleValueType(0);
12729 SDValue In = Op->getOperand(0);
12730 MVT InVT = In.getSimpleValueType();
12733 unsigned int NumElts = VT.getVectorNumElements();
12734 if (NumElts != 8 && NumElts != 16)
12737 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12738 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12740 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12741 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12743 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12744 Constant *C = ConstantInt::get(*DAG.getContext(),
12745 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12747 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12748 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12749 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12750 MachinePointerInfo::getConstantPool(),
12751 false, false, false, Alignment);
12752 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12753 if (VT.is512BitVector())
12755 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12758 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12759 SelectionDAG &DAG) {
12760 MVT VT = Op->getSimpleValueType(0);
12761 SDValue In = Op->getOperand(0);
12762 MVT InVT = In.getSimpleValueType();
12765 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12766 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12768 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12769 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12770 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12773 if (Subtarget->hasInt256())
12774 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12776 // Optimize vectors in AVX mode
12777 // Sign extend v8i16 to v8i32 and
12780 // Divide input vector into two parts
12781 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12782 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12783 // concat the vectors to original VT
12785 unsigned NumElems = InVT.getVectorNumElements();
12786 SDValue Undef = DAG.getUNDEF(InVT);
12788 SmallVector<int,8> ShufMask1(NumElems, -1);
12789 for (unsigned i = 0; i != NumElems/2; ++i)
12792 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12794 SmallVector<int,8> ShufMask2(NumElems, -1);
12795 for (unsigned i = 0; i != NumElems/2; ++i)
12796 ShufMask2[i] = i + NumElems/2;
12798 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12800 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12801 VT.getVectorNumElements()/2);
12803 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12804 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12806 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12809 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12810 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12811 // from the AND / OR.
12812 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12813 Opc = Op.getOpcode();
12814 if (Opc != ISD::OR && Opc != ISD::AND)
12816 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12817 Op.getOperand(0).hasOneUse() &&
12818 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12819 Op.getOperand(1).hasOneUse());
12822 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12823 // 1 and that the SETCC node has a single use.
12824 static bool isXor1OfSetCC(SDValue Op) {
12825 if (Op.getOpcode() != ISD::XOR)
12827 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12828 if (N1C && N1C->getAPIntValue() == 1) {
12829 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12830 Op.getOperand(0).hasOneUse();
12835 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12836 bool addTest = true;
12837 SDValue Chain = Op.getOperand(0);
12838 SDValue Cond = Op.getOperand(1);
12839 SDValue Dest = Op.getOperand(2);
12842 bool Inverted = false;
12844 if (Cond.getOpcode() == ISD::SETCC) {
12845 // Check for setcc([su]{add,sub,mul}o == 0).
12846 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12847 isa<ConstantSDNode>(Cond.getOperand(1)) &&
12848 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12849 Cond.getOperand(0).getResNo() == 1 &&
12850 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12851 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12852 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12853 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12854 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12855 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12857 Cond = Cond.getOperand(0);
12859 SDValue NewCond = LowerSETCC(Cond, DAG);
12860 if (NewCond.getNode())
12865 // FIXME: LowerXALUO doesn't handle these!!
12866 else if (Cond.getOpcode() == X86ISD::ADD ||
12867 Cond.getOpcode() == X86ISD::SUB ||
12868 Cond.getOpcode() == X86ISD::SMUL ||
12869 Cond.getOpcode() == X86ISD::UMUL)
12870 Cond = LowerXALUO(Cond, DAG);
12873 // Look pass (and (setcc_carry (cmp ...)), 1).
12874 if (Cond.getOpcode() == ISD::AND &&
12875 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12876 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12877 if (C && C->getAPIntValue() == 1)
12878 Cond = Cond.getOperand(0);
12881 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12882 // setting operand in place of the X86ISD::SETCC.
12883 unsigned CondOpcode = Cond.getOpcode();
12884 if (CondOpcode == X86ISD::SETCC ||
12885 CondOpcode == X86ISD::SETCC_CARRY) {
12886 CC = Cond.getOperand(0);
12888 SDValue Cmp = Cond.getOperand(1);
12889 unsigned Opc = Cmp.getOpcode();
12890 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12891 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12895 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12899 // These can only come from an arithmetic instruction with overflow,
12900 // e.g. SADDO, UADDO.
12901 Cond = Cond.getNode()->getOperand(1);
12907 CondOpcode = Cond.getOpcode();
12908 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12909 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12910 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12911 Cond.getOperand(0).getValueType() != MVT::i8)) {
12912 SDValue LHS = Cond.getOperand(0);
12913 SDValue RHS = Cond.getOperand(1);
12914 unsigned X86Opcode;
12917 // Keep this in sync with LowerXALUO, otherwise we might create redundant
12918 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12920 switch (CondOpcode) {
12921 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12923 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12925 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12928 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12929 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12931 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12933 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12936 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12937 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12938 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12939 default: llvm_unreachable("unexpected overflowing operator");
12942 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12943 if (CondOpcode == ISD::UMULO)
12944 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12947 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12949 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12951 if (CondOpcode == ISD::UMULO)
12952 Cond = X86Op.getValue(2);
12954 Cond = X86Op.getValue(1);
12956 CC = DAG.getConstant(X86Cond, MVT::i8);
12960 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12961 SDValue Cmp = Cond.getOperand(0).getOperand(1);
12962 if (CondOpc == ISD::OR) {
12963 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12964 // two branches instead of an explicit OR instruction with a
12966 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12967 isX86LogicalCmp(Cmp)) {
12968 CC = Cond.getOperand(0).getOperand(0);
12969 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12970 Chain, Dest, CC, Cmp);
12971 CC = Cond.getOperand(1).getOperand(0);
12975 } else { // ISD::AND
12976 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12977 // two branches instead of an explicit AND instruction with a
12978 // separate test. However, we only do this if this block doesn't
12979 // have a fall-through edge, because this requires an explicit
12980 // jmp when the condition is false.
12981 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12982 isX86LogicalCmp(Cmp) &&
12983 Op.getNode()->hasOneUse()) {
12984 X86::CondCode CCode =
12985 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12986 CCode = X86::GetOppositeBranchCondition(CCode);
12987 CC = DAG.getConstant(CCode, MVT::i8);
12988 SDNode *User = *Op.getNode()->use_begin();
12989 // Look for an unconditional branch following this conditional branch.
12990 // We need this because we need to reverse the successors in order
12991 // to implement FCMP_OEQ.
12992 if (User->getOpcode() == ISD::BR) {
12993 SDValue FalseBB = User->getOperand(1);
12995 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12996 assert(NewBR == User);
13000 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13001 Chain, Dest, CC, Cmp);
13002 X86::CondCode CCode =
13003 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13004 CCode = X86::GetOppositeBranchCondition(CCode);
13005 CC = DAG.getConstant(CCode, MVT::i8);
13011 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13012 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13013 // It should be transformed during dag combiner except when the condition
13014 // is set by a arithmetics with overflow node.
13015 X86::CondCode CCode =
13016 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13017 CCode = X86::GetOppositeBranchCondition(CCode);
13018 CC = DAG.getConstant(CCode, MVT::i8);
13019 Cond = Cond.getOperand(0).getOperand(1);
13021 } else if (Cond.getOpcode() == ISD::SETCC &&
13022 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13023 // For FCMP_OEQ, we can emit
13024 // two branches instead of an explicit AND instruction with a
13025 // separate test. However, we only do this if this block doesn't
13026 // have a fall-through edge, because this requires an explicit
13027 // jmp when the condition is false.
13028 if (Op.getNode()->hasOneUse()) {
13029 SDNode *User = *Op.getNode()->use_begin();
13030 // Look for an unconditional branch following this conditional branch.
13031 // We need this because we need to reverse the successors in order
13032 // to implement FCMP_OEQ.
13033 if (User->getOpcode() == ISD::BR) {
13034 SDValue FalseBB = User->getOperand(1);
13036 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13037 assert(NewBR == User);
13041 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13042 Cond.getOperand(0), Cond.getOperand(1));
13043 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13044 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13045 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13046 Chain, Dest, CC, Cmp);
13047 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13052 } else if (Cond.getOpcode() == ISD::SETCC &&
13053 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13054 // For FCMP_UNE, we can emit
13055 // two branches instead of an explicit AND instruction with a
13056 // separate test. However, we only do this if this block doesn't
13057 // have a fall-through edge, because this requires an explicit
13058 // jmp when the condition is false.
13059 if (Op.getNode()->hasOneUse()) {
13060 SDNode *User = *Op.getNode()->use_begin();
13061 // Look for an unconditional branch following this conditional branch.
13062 // We need this because we need to reverse the successors in order
13063 // to implement FCMP_UNE.
13064 if (User->getOpcode() == ISD::BR) {
13065 SDValue FalseBB = User->getOperand(1);
13067 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13068 assert(NewBR == User);
13071 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13072 Cond.getOperand(0), Cond.getOperand(1));
13073 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13074 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13075 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13076 Chain, Dest, CC, Cmp);
13077 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13087 // Look pass the truncate if the high bits are known zero.
13088 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13089 Cond = Cond.getOperand(0);
13091 // We know the result of AND is compared against zero. Try to match
13093 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13094 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13095 if (NewSetCC.getNode()) {
13096 CC = NewSetCC.getOperand(0);
13097 Cond = NewSetCC.getOperand(1);
13104 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13105 CC = DAG.getConstant(X86Cond, MVT::i8);
13106 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13108 Cond = ConvertCmpIfNecessary(Cond, DAG);
13109 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13110 Chain, Dest, CC, Cond);
13113 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13114 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13115 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13116 // that the guard pages used by the OS virtual memory manager are allocated in
13117 // correct sequence.
13119 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13120 SelectionDAG &DAG) const {
13121 MachineFunction &MF = DAG.getMachineFunction();
13122 bool SplitStack = MF.shouldSplitStack();
13123 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13129 SDNode* Node = Op.getNode();
13131 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13132 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13133 " not tell us which reg is the stack pointer!");
13134 EVT VT = Node->getValueType(0);
13135 SDValue Tmp1 = SDValue(Node, 0);
13136 SDValue Tmp2 = SDValue(Node, 1);
13137 SDValue Tmp3 = Node->getOperand(2);
13138 SDValue Chain = Tmp1.getOperand(0);
13140 // Chain the dynamic stack allocation so that it doesn't modify the stack
13141 // pointer when other instructions are using the stack.
13142 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13145 SDValue Size = Tmp2.getOperand(1);
13146 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13147 Chain = SP.getValue(1);
13148 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13149 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13150 unsigned StackAlign = TFI.getStackAlignment();
13151 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13152 if (Align > StackAlign)
13153 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13154 DAG.getConstant(-(uint64_t)Align, VT));
13155 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13157 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13158 DAG.getIntPtrConstant(0, true), SDValue(),
13161 SDValue Ops[2] = { Tmp1, Tmp2 };
13162 return DAG.getMergeValues(Ops, dl);
13166 SDValue Chain = Op.getOperand(0);
13167 SDValue Size = Op.getOperand(1);
13168 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13169 EVT VT = Op.getNode()->getValueType(0);
13171 bool Is64Bit = Subtarget->is64Bit();
13172 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13175 MachineRegisterInfo &MRI = MF.getRegInfo();
13178 // The 64 bit implementation of segmented stacks needs to clobber both r10
13179 // r11. This makes it impossible to use it along with nested parameters.
13180 const Function *F = MF.getFunction();
13182 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13184 if (I->hasNestAttr())
13185 report_fatal_error("Cannot use segmented stacks with functions that "
13186 "have nested arguments.");
13189 const TargetRegisterClass *AddrRegClass =
13190 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13191 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13192 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13193 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13194 DAG.getRegister(Vreg, SPTy));
13195 SDValue Ops1[2] = { Value, Chain };
13196 return DAG.getMergeValues(Ops1, dl);
13199 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13201 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13202 Flag = Chain.getValue(1);
13203 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13205 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13207 const X86RegisterInfo *RegInfo =
13208 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13209 unsigned SPReg = RegInfo->getStackRegister();
13210 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13211 Chain = SP.getValue(1);
13214 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13215 DAG.getConstant(-(uint64_t)Align, VT));
13216 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13219 SDValue Ops1[2] = { SP, Chain };
13220 return DAG.getMergeValues(Ops1, dl);
13224 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13225 MachineFunction &MF = DAG.getMachineFunction();
13226 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13228 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13231 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13232 // vastart just stores the address of the VarArgsFrameIndex slot into the
13233 // memory location argument.
13234 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13236 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13237 MachinePointerInfo(SV), false, false, 0);
13241 // gp_offset (0 - 6 * 8)
13242 // fp_offset (48 - 48 + 8 * 16)
13243 // overflow_arg_area (point to parameters coming in memory).
13245 SmallVector<SDValue, 8> MemOps;
13246 SDValue FIN = Op.getOperand(1);
13248 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13249 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13251 FIN, MachinePointerInfo(SV), false, false, 0);
13252 MemOps.push_back(Store);
13255 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13256 FIN, DAG.getIntPtrConstant(4));
13257 Store = DAG.getStore(Op.getOperand(0), DL,
13258 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13260 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13261 MemOps.push_back(Store);
13263 // Store ptr to overflow_arg_area
13264 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13265 FIN, DAG.getIntPtrConstant(4));
13266 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13268 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13269 MachinePointerInfo(SV, 8),
13271 MemOps.push_back(Store);
13273 // Store ptr to reg_save_area.
13274 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13275 FIN, DAG.getIntPtrConstant(8));
13276 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13278 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13279 MachinePointerInfo(SV, 16), false, false, 0);
13280 MemOps.push_back(Store);
13281 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13284 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13285 assert(Subtarget->is64Bit() &&
13286 "LowerVAARG only handles 64-bit va_arg!");
13287 assert((Subtarget->isTargetLinux() ||
13288 Subtarget->isTargetDarwin()) &&
13289 "Unhandled target in LowerVAARG");
13290 assert(Op.getNode()->getNumOperands() == 4);
13291 SDValue Chain = Op.getOperand(0);
13292 SDValue SrcPtr = Op.getOperand(1);
13293 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13294 unsigned Align = Op.getConstantOperandVal(3);
13297 EVT ArgVT = Op.getNode()->getValueType(0);
13298 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13299 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13302 // Decide which area this value should be read from.
13303 // TODO: Implement the AMD64 ABI in its entirety. This simple
13304 // selection mechanism works only for the basic types.
13305 if (ArgVT == MVT::f80) {
13306 llvm_unreachable("va_arg for f80 not yet implemented");
13307 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13308 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13309 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13310 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13312 llvm_unreachable("Unhandled argument type in LowerVAARG");
13315 if (ArgMode == 2) {
13316 // Sanity Check: Make sure using fp_offset makes sense.
13317 assert(!DAG.getTarget().Options.UseSoftFloat &&
13318 !(DAG.getMachineFunction()
13319 .getFunction()->getAttributes()
13320 .hasAttribute(AttributeSet::FunctionIndex,
13321 Attribute::NoImplicitFloat)) &&
13322 Subtarget->hasSSE1());
13325 // Insert VAARG_64 node into the DAG
13326 // VAARG_64 returns two values: Variable Argument Address, Chain
13327 SmallVector<SDValue, 11> InstOps;
13328 InstOps.push_back(Chain);
13329 InstOps.push_back(SrcPtr);
13330 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13331 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13332 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13333 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13334 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13335 VTs, InstOps, MVT::i64,
13336 MachinePointerInfo(SV),
13338 /*Volatile=*/false,
13340 /*WriteMem=*/true);
13341 Chain = VAARG.getValue(1);
13343 // Load the next argument and return it
13344 return DAG.getLoad(ArgVT, dl,
13347 MachinePointerInfo(),
13348 false, false, false, 0);
13351 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13352 SelectionDAG &DAG) {
13353 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13354 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13355 SDValue Chain = Op.getOperand(0);
13356 SDValue DstPtr = Op.getOperand(1);
13357 SDValue SrcPtr = Op.getOperand(2);
13358 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13359 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13362 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13363 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13365 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13368 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13369 // amount is a constant. Takes immediate version of shift as input.
13370 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13371 SDValue SrcOp, uint64_t ShiftAmt,
13372 SelectionDAG &DAG) {
13373 MVT ElementType = VT.getVectorElementType();
13375 // Fold this packed shift into its first operand if ShiftAmt is 0.
13379 // Check for ShiftAmt >= element width
13380 if (ShiftAmt >= ElementType.getSizeInBits()) {
13381 if (Opc == X86ISD::VSRAI)
13382 ShiftAmt = ElementType.getSizeInBits() - 1;
13384 return DAG.getConstant(0, VT);
13387 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13388 && "Unknown target vector shift-by-constant node");
13390 // Fold this packed vector shift into a build vector if SrcOp is a
13391 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13392 if (VT == SrcOp.getSimpleValueType() &&
13393 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13394 SmallVector<SDValue, 8> Elts;
13395 unsigned NumElts = SrcOp->getNumOperands();
13396 ConstantSDNode *ND;
13399 default: llvm_unreachable(nullptr);
13400 case X86ISD::VSHLI:
13401 for (unsigned i=0; i!=NumElts; ++i) {
13402 SDValue CurrentOp = SrcOp->getOperand(i);
13403 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13404 Elts.push_back(CurrentOp);
13407 ND = cast<ConstantSDNode>(CurrentOp);
13408 const APInt &C = ND->getAPIntValue();
13409 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13412 case X86ISD::VSRLI:
13413 for (unsigned i=0; i!=NumElts; ++i) {
13414 SDValue CurrentOp = SrcOp->getOperand(i);
13415 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13416 Elts.push_back(CurrentOp);
13419 ND = cast<ConstantSDNode>(CurrentOp);
13420 const APInt &C = ND->getAPIntValue();
13421 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13424 case X86ISD::VSRAI:
13425 for (unsigned i=0; i!=NumElts; ++i) {
13426 SDValue CurrentOp = SrcOp->getOperand(i);
13427 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13428 Elts.push_back(CurrentOp);
13431 ND = cast<ConstantSDNode>(CurrentOp);
13432 const APInt &C = ND->getAPIntValue();
13433 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13438 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13441 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13444 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13445 // may or may not be a constant. Takes immediate version of shift as input.
13446 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13447 SDValue SrcOp, SDValue ShAmt,
13448 SelectionDAG &DAG) {
13449 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13451 // Catch shift-by-constant.
13452 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13453 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13454 CShAmt->getZExtValue(), DAG);
13456 // Change opcode to non-immediate version
13458 default: llvm_unreachable("Unknown target vector shift node");
13459 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13460 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13461 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13464 // Need to build a vector containing shift amount
13465 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13468 ShOps[1] = DAG.getConstant(0, MVT::i32);
13469 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13470 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13472 // The return type has to be a 128-bit type with the same element
13473 // type as the input type.
13474 MVT EltVT = VT.getVectorElementType();
13475 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13477 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13478 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13481 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13483 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13485 default: return SDValue(); // Don't custom lower most intrinsics.
13486 // Comparison intrinsics.
13487 case Intrinsic::x86_sse_comieq_ss:
13488 case Intrinsic::x86_sse_comilt_ss:
13489 case Intrinsic::x86_sse_comile_ss:
13490 case Intrinsic::x86_sse_comigt_ss:
13491 case Intrinsic::x86_sse_comige_ss:
13492 case Intrinsic::x86_sse_comineq_ss:
13493 case Intrinsic::x86_sse_ucomieq_ss:
13494 case Intrinsic::x86_sse_ucomilt_ss:
13495 case Intrinsic::x86_sse_ucomile_ss:
13496 case Intrinsic::x86_sse_ucomigt_ss:
13497 case Intrinsic::x86_sse_ucomige_ss:
13498 case Intrinsic::x86_sse_ucomineq_ss:
13499 case Intrinsic::x86_sse2_comieq_sd:
13500 case Intrinsic::x86_sse2_comilt_sd:
13501 case Intrinsic::x86_sse2_comile_sd:
13502 case Intrinsic::x86_sse2_comigt_sd:
13503 case Intrinsic::x86_sse2_comige_sd:
13504 case Intrinsic::x86_sse2_comineq_sd:
13505 case Intrinsic::x86_sse2_ucomieq_sd:
13506 case Intrinsic::x86_sse2_ucomilt_sd:
13507 case Intrinsic::x86_sse2_ucomile_sd:
13508 case Intrinsic::x86_sse2_ucomigt_sd:
13509 case Intrinsic::x86_sse2_ucomige_sd:
13510 case Intrinsic::x86_sse2_ucomineq_sd: {
13514 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13515 case Intrinsic::x86_sse_comieq_ss:
13516 case Intrinsic::x86_sse2_comieq_sd:
13517 Opc = X86ISD::COMI;
13520 case Intrinsic::x86_sse_comilt_ss:
13521 case Intrinsic::x86_sse2_comilt_sd:
13522 Opc = X86ISD::COMI;
13525 case Intrinsic::x86_sse_comile_ss:
13526 case Intrinsic::x86_sse2_comile_sd:
13527 Opc = X86ISD::COMI;
13530 case Intrinsic::x86_sse_comigt_ss:
13531 case Intrinsic::x86_sse2_comigt_sd:
13532 Opc = X86ISD::COMI;
13535 case Intrinsic::x86_sse_comige_ss:
13536 case Intrinsic::x86_sse2_comige_sd:
13537 Opc = X86ISD::COMI;
13540 case Intrinsic::x86_sse_comineq_ss:
13541 case Intrinsic::x86_sse2_comineq_sd:
13542 Opc = X86ISD::COMI;
13545 case Intrinsic::x86_sse_ucomieq_ss:
13546 case Intrinsic::x86_sse2_ucomieq_sd:
13547 Opc = X86ISD::UCOMI;
13550 case Intrinsic::x86_sse_ucomilt_ss:
13551 case Intrinsic::x86_sse2_ucomilt_sd:
13552 Opc = X86ISD::UCOMI;
13555 case Intrinsic::x86_sse_ucomile_ss:
13556 case Intrinsic::x86_sse2_ucomile_sd:
13557 Opc = X86ISD::UCOMI;
13560 case Intrinsic::x86_sse_ucomigt_ss:
13561 case Intrinsic::x86_sse2_ucomigt_sd:
13562 Opc = X86ISD::UCOMI;
13565 case Intrinsic::x86_sse_ucomige_ss:
13566 case Intrinsic::x86_sse2_ucomige_sd:
13567 Opc = X86ISD::UCOMI;
13570 case Intrinsic::x86_sse_ucomineq_ss:
13571 case Intrinsic::x86_sse2_ucomineq_sd:
13572 Opc = X86ISD::UCOMI;
13577 SDValue LHS = Op.getOperand(1);
13578 SDValue RHS = Op.getOperand(2);
13579 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13580 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13581 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13582 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13583 DAG.getConstant(X86CC, MVT::i8), Cond);
13584 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13587 // Arithmetic intrinsics.
13588 case Intrinsic::x86_sse2_pmulu_dq:
13589 case Intrinsic::x86_avx2_pmulu_dq:
13590 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13591 Op.getOperand(1), Op.getOperand(2));
13593 case Intrinsic::x86_sse41_pmuldq:
13594 case Intrinsic::x86_avx2_pmul_dq:
13595 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13596 Op.getOperand(1), Op.getOperand(2));
13598 case Intrinsic::x86_sse2_pmulhu_w:
13599 case Intrinsic::x86_avx2_pmulhu_w:
13600 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13601 Op.getOperand(1), Op.getOperand(2));
13603 case Intrinsic::x86_sse2_pmulh_w:
13604 case Intrinsic::x86_avx2_pmulh_w:
13605 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13606 Op.getOperand(1), Op.getOperand(2));
13608 // SSE2/AVX2 sub with unsigned saturation intrinsics
13609 case Intrinsic::x86_sse2_psubus_b:
13610 case Intrinsic::x86_sse2_psubus_w:
13611 case Intrinsic::x86_avx2_psubus_b:
13612 case Intrinsic::x86_avx2_psubus_w:
13613 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13614 Op.getOperand(1), Op.getOperand(2));
13616 // SSE3/AVX horizontal add/sub intrinsics
13617 case Intrinsic::x86_sse3_hadd_ps:
13618 case Intrinsic::x86_sse3_hadd_pd:
13619 case Intrinsic::x86_avx_hadd_ps_256:
13620 case Intrinsic::x86_avx_hadd_pd_256:
13621 case Intrinsic::x86_sse3_hsub_ps:
13622 case Intrinsic::x86_sse3_hsub_pd:
13623 case Intrinsic::x86_avx_hsub_ps_256:
13624 case Intrinsic::x86_avx_hsub_pd_256:
13625 case Intrinsic::x86_ssse3_phadd_w_128:
13626 case Intrinsic::x86_ssse3_phadd_d_128:
13627 case Intrinsic::x86_avx2_phadd_w:
13628 case Intrinsic::x86_avx2_phadd_d:
13629 case Intrinsic::x86_ssse3_phsub_w_128:
13630 case Intrinsic::x86_ssse3_phsub_d_128:
13631 case Intrinsic::x86_avx2_phsub_w:
13632 case Intrinsic::x86_avx2_phsub_d: {
13635 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13636 case Intrinsic::x86_sse3_hadd_ps:
13637 case Intrinsic::x86_sse3_hadd_pd:
13638 case Intrinsic::x86_avx_hadd_ps_256:
13639 case Intrinsic::x86_avx_hadd_pd_256:
13640 Opcode = X86ISD::FHADD;
13642 case Intrinsic::x86_sse3_hsub_ps:
13643 case Intrinsic::x86_sse3_hsub_pd:
13644 case Intrinsic::x86_avx_hsub_ps_256:
13645 case Intrinsic::x86_avx_hsub_pd_256:
13646 Opcode = X86ISD::FHSUB;
13648 case Intrinsic::x86_ssse3_phadd_w_128:
13649 case Intrinsic::x86_ssse3_phadd_d_128:
13650 case Intrinsic::x86_avx2_phadd_w:
13651 case Intrinsic::x86_avx2_phadd_d:
13652 Opcode = X86ISD::HADD;
13654 case Intrinsic::x86_ssse3_phsub_w_128:
13655 case Intrinsic::x86_ssse3_phsub_d_128:
13656 case Intrinsic::x86_avx2_phsub_w:
13657 case Intrinsic::x86_avx2_phsub_d:
13658 Opcode = X86ISD::HSUB;
13661 return DAG.getNode(Opcode, dl, Op.getValueType(),
13662 Op.getOperand(1), Op.getOperand(2));
13665 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13666 case Intrinsic::x86_sse2_pmaxu_b:
13667 case Intrinsic::x86_sse41_pmaxuw:
13668 case Intrinsic::x86_sse41_pmaxud:
13669 case Intrinsic::x86_avx2_pmaxu_b:
13670 case Intrinsic::x86_avx2_pmaxu_w:
13671 case Intrinsic::x86_avx2_pmaxu_d:
13672 case Intrinsic::x86_sse2_pminu_b:
13673 case Intrinsic::x86_sse41_pminuw:
13674 case Intrinsic::x86_sse41_pminud:
13675 case Intrinsic::x86_avx2_pminu_b:
13676 case Intrinsic::x86_avx2_pminu_w:
13677 case Intrinsic::x86_avx2_pminu_d:
13678 case Intrinsic::x86_sse41_pmaxsb:
13679 case Intrinsic::x86_sse2_pmaxs_w:
13680 case Intrinsic::x86_sse41_pmaxsd:
13681 case Intrinsic::x86_avx2_pmaxs_b:
13682 case Intrinsic::x86_avx2_pmaxs_w:
13683 case Intrinsic::x86_avx2_pmaxs_d:
13684 case Intrinsic::x86_sse41_pminsb:
13685 case Intrinsic::x86_sse2_pmins_w:
13686 case Intrinsic::x86_sse41_pminsd:
13687 case Intrinsic::x86_avx2_pmins_b:
13688 case Intrinsic::x86_avx2_pmins_w:
13689 case Intrinsic::x86_avx2_pmins_d: {
13692 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13693 case Intrinsic::x86_sse2_pmaxu_b:
13694 case Intrinsic::x86_sse41_pmaxuw:
13695 case Intrinsic::x86_sse41_pmaxud:
13696 case Intrinsic::x86_avx2_pmaxu_b:
13697 case Intrinsic::x86_avx2_pmaxu_w:
13698 case Intrinsic::x86_avx2_pmaxu_d:
13699 Opcode = X86ISD::UMAX;
13701 case Intrinsic::x86_sse2_pminu_b:
13702 case Intrinsic::x86_sse41_pminuw:
13703 case Intrinsic::x86_sse41_pminud:
13704 case Intrinsic::x86_avx2_pminu_b:
13705 case Intrinsic::x86_avx2_pminu_w:
13706 case Intrinsic::x86_avx2_pminu_d:
13707 Opcode = X86ISD::UMIN;
13709 case Intrinsic::x86_sse41_pmaxsb:
13710 case Intrinsic::x86_sse2_pmaxs_w:
13711 case Intrinsic::x86_sse41_pmaxsd:
13712 case Intrinsic::x86_avx2_pmaxs_b:
13713 case Intrinsic::x86_avx2_pmaxs_w:
13714 case Intrinsic::x86_avx2_pmaxs_d:
13715 Opcode = X86ISD::SMAX;
13717 case Intrinsic::x86_sse41_pminsb:
13718 case Intrinsic::x86_sse2_pmins_w:
13719 case Intrinsic::x86_sse41_pminsd:
13720 case Intrinsic::x86_avx2_pmins_b:
13721 case Intrinsic::x86_avx2_pmins_w:
13722 case Intrinsic::x86_avx2_pmins_d:
13723 Opcode = X86ISD::SMIN;
13726 return DAG.getNode(Opcode, dl, Op.getValueType(),
13727 Op.getOperand(1), Op.getOperand(2));
13730 // SSE/SSE2/AVX floating point max/min intrinsics.
13731 case Intrinsic::x86_sse_max_ps:
13732 case Intrinsic::x86_sse2_max_pd:
13733 case Intrinsic::x86_avx_max_ps_256:
13734 case Intrinsic::x86_avx_max_pd_256:
13735 case Intrinsic::x86_sse_min_ps:
13736 case Intrinsic::x86_sse2_min_pd:
13737 case Intrinsic::x86_avx_min_ps_256:
13738 case Intrinsic::x86_avx_min_pd_256: {
13741 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13742 case Intrinsic::x86_sse_max_ps:
13743 case Intrinsic::x86_sse2_max_pd:
13744 case Intrinsic::x86_avx_max_ps_256:
13745 case Intrinsic::x86_avx_max_pd_256:
13746 Opcode = X86ISD::FMAX;
13748 case Intrinsic::x86_sse_min_ps:
13749 case Intrinsic::x86_sse2_min_pd:
13750 case Intrinsic::x86_avx_min_ps_256:
13751 case Intrinsic::x86_avx_min_pd_256:
13752 Opcode = X86ISD::FMIN;
13755 return DAG.getNode(Opcode, dl, Op.getValueType(),
13756 Op.getOperand(1), Op.getOperand(2));
13759 // AVX2 variable shift intrinsics
13760 case Intrinsic::x86_avx2_psllv_d:
13761 case Intrinsic::x86_avx2_psllv_q:
13762 case Intrinsic::x86_avx2_psllv_d_256:
13763 case Intrinsic::x86_avx2_psllv_q_256:
13764 case Intrinsic::x86_avx2_psrlv_d:
13765 case Intrinsic::x86_avx2_psrlv_q:
13766 case Intrinsic::x86_avx2_psrlv_d_256:
13767 case Intrinsic::x86_avx2_psrlv_q_256:
13768 case Intrinsic::x86_avx2_psrav_d:
13769 case Intrinsic::x86_avx2_psrav_d_256: {
13772 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13773 case Intrinsic::x86_avx2_psllv_d:
13774 case Intrinsic::x86_avx2_psllv_q:
13775 case Intrinsic::x86_avx2_psllv_d_256:
13776 case Intrinsic::x86_avx2_psllv_q_256:
13779 case Intrinsic::x86_avx2_psrlv_d:
13780 case Intrinsic::x86_avx2_psrlv_q:
13781 case Intrinsic::x86_avx2_psrlv_d_256:
13782 case Intrinsic::x86_avx2_psrlv_q_256:
13785 case Intrinsic::x86_avx2_psrav_d:
13786 case Intrinsic::x86_avx2_psrav_d_256:
13790 return DAG.getNode(Opcode, dl, Op.getValueType(),
13791 Op.getOperand(1), Op.getOperand(2));
13794 case Intrinsic::x86_sse2_packssdw_128:
13795 case Intrinsic::x86_sse2_packsswb_128:
13796 case Intrinsic::x86_avx2_packssdw:
13797 case Intrinsic::x86_avx2_packsswb:
13798 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13799 Op.getOperand(1), Op.getOperand(2));
13801 case Intrinsic::x86_sse2_packuswb_128:
13802 case Intrinsic::x86_sse41_packusdw:
13803 case Intrinsic::x86_avx2_packuswb:
13804 case Intrinsic::x86_avx2_packusdw:
13805 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13806 Op.getOperand(1), Op.getOperand(2));
13808 case Intrinsic::x86_ssse3_pshuf_b_128:
13809 case Intrinsic::x86_avx2_pshuf_b:
13810 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13811 Op.getOperand(1), Op.getOperand(2));
13813 case Intrinsic::x86_sse2_pshuf_d:
13814 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13815 Op.getOperand(1), Op.getOperand(2));
13817 case Intrinsic::x86_sse2_pshufl_w:
13818 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13819 Op.getOperand(1), Op.getOperand(2));
13821 case Intrinsic::x86_sse2_pshufh_w:
13822 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13823 Op.getOperand(1), Op.getOperand(2));
13825 case Intrinsic::x86_ssse3_psign_b_128:
13826 case Intrinsic::x86_ssse3_psign_w_128:
13827 case Intrinsic::x86_ssse3_psign_d_128:
13828 case Intrinsic::x86_avx2_psign_b:
13829 case Intrinsic::x86_avx2_psign_w:
13830 case Intrinsic::x86_avx2_psign_d:
13831 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13832 Op.getOperand(1), Op.getOperand(2));
13834 case Intrinsic::x86_sse41_insertps:
13835 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13836 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13838 case Intrinsic::x86_avx_vperm2f128_ps_256:
13839 case Intrinsic::x86_avx_vperm2f128_pd_256:
13840 case Intrinsic::x86_avx_vperm2f128_si_256:
13841 case Intrinsic::x86_avx2_vperm2i128:
13842 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13843 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13845 case Intrinsic::x86_avx2_permd:
13846 case Intrinsic::x86_avx2_permps:
13847 // Operands intentionally swapped. Mask is last operand to intrinsic,
13848 // but second operand for node/instruction.
13849 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13850 Op.getOperand(2), Op.getOperand(1));
13852 case Intrinsic::x86_sse_sqrt_ps:
13853 case Intrinsic::x86_sse2_sqrt_pd:
13854 case Intrinsic::x86_avx_sqrt_ps_256:
13855 case Intrinsic::x86_avx_sqrt_pd_256:
13856 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13858 // ptest and testp intrinsics. The intrinsic these come from are designed to
13859 // return an integer value, not just an instruction so lower it to the ptest
13860 // or testp pattern and a setcc for the result.
13861 case Intrinsic::x86_sse41_ptestz:
13862 case Intrinsic::x86_sse41_ptestc:
13863 case Intrinsic::x86_sse41_ptestnzc:
13864 case Intrinsic::x86_avx_ptestz_256:
13865 case Intrinsic::x86_avx_ptestc_256:
13866 case Intrinsic::x86_avx_ptestnzc_256:
13867 case Intrinsic::x86_avx_vtestz_ps:
13868 case Intrinsic::x86_avx_vtestc_ps:
13869 case Intrinsic::x86_avx_vtestnzc_ps:
13870 case Intrinsic::x86_avx_vtestz_pd:
13871 case Intrinsic::x86_avx_vtestc_pd:
13872 case Intrinsic::x86_avx_vtestnzc_pd:
13873 case Intrinsic::x86_avx_vtestz_ps_256:
13874 case Intrinsic::x86_avx_vtestc_ps_256:
13875 case Intrinsic::x86_avx_vtestnzc_ps_256:
13876 case Intrinsic::x86_avx_vtestz_pd_256:
13877 case Intrinsic::x86_avx_vtestc_pd_256:
13878 case Intrinsic::x86_avx_vtestnzc_pd_256: {
13879 bool IsTestPacked = false;
13882 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13883 case Intrinsic::x86_avx_vtestz_ps:
13884 case Intrinsic::x86_avx_vtestz_pd:
13885 case Intrinsic::x86_avx_vtestz_ps_256:
13886 case Intrinsic::x86_avx_vtestz_pd_256:
13887 IsTestPacked = true; // Fallthrough
13888 case Intrinsic::x86_sse41_ptestz:
13889 case Intrinsic::x86_avx_ptestz_256:
13891 X86CC = X86::COND_E;
13893 case Intrinsic::x86_avx_vtestc_ps:
13894 case Intrinsic::x86_avx_vtestc_pd:
13895 case Intrinsic::x86_avx_vtestc_ps_256:
13896 case Intrinsic::x86_avx_vtestc_pd_256:
13897 IsTestPacked = true; // Fallthrough
13898 case Intrinsic::x86_sse41_ptestc:
13899 case Intrinsic::x86_avx_ptestc_256:
13901 X86CC = X86::COND_B;
13903 case Intrinsic::x86_avx_vtestnzc_ps:
13904 case Intrinsic::x86_avx_vtestnzc_pd:
13905 case Intrinsic::x86_avx_vtestnzc_ps_256:
13906 case Intrinsic::x86_avx_vtestnzc_pd_256:
13907 IsTestPacked = true; // Fallthrough
13908 case Intrinsic::x86_sse41_ptestnzc:
13909 case Intrinsic::x86_avx_ptestnzc_256:
13911 X86CC = X86::COND_A;
13915 SDValue LHS = Op.getOperand(1);
13916 SDValue RHS = Op.getOperand(2);
13917 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13918 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13919 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13920 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13921 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13923 case Intrinsic::x86_avx512_kortestz_w:
13924 case Intrinsic::x86_avx512_kortestc_w: {
13925 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13926 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13927 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13928 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13929 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13930 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13931 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13934 // SSE/AVX shift intrinsics
13935 case Intrinsic::x86_sse2_psll_w:
13936 case Intrinsic::x86_sse2_psll_d:
13937 case Intrinsic::x86_sse2_psll_q:
13938 case Intrinsic::x86_avx2_psll_w:
13939 case Intrinsic::x86_avx2_psll_d:
13940 case Intrinsic::x86_avx2_psll_q:
13941 case Intrinsic::x86_sse2_psrl_w:
13942 case Intrinsic::x86_sse2_psrl_d:
13943 case Intrinsic::x86_sse2_psrl_q:
13944 case Intrinsic::x86_avx2_psrl_w:
13945 case Intrinsic::x86_avx2_psrl_d:
13946 case Intrinsic::x86_avx2_psrl_q:
13947 case Intrinsic::x86_sse2_psra_w:
13948 case Intrinsic::x86_sse2_psra_d:
13949 case Intrinsic::x86_avx2_psra_w:
13950 case Intrinsic::x86_avx2_psra_d: {
13953 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13954 case Intrinsic::x86_sse2_psll_w:
13955 case Intrinsic::x86_sse2_psll_d:
13956 case Intrinsic::x86_sse2_psll_q:
13957 case Intrinsic::x86_avx2_psll_w:
13958 case Intrinsic::x86_avx2_psll_d:
13959 case Intrinsic::x86_avx2_psll_q:
13960 Opcode = X86ISD::VSHL;
13962 case Intrinsic::x86_sse2_psrl_w:
13963 case Intrinsic::x86_sse2_psrl_d:
13964 case Intrinsic::x86_sse2_psrl_q:
13965 case Intrinsic::x86_avx2_psrl_w:
13966 case Intrinsic::x86_avx2_psrl_d:
13967 case Intrinsic::x86_avx2_psrl_q:
13968 Opcode = X86ISD::VSRL;
13970 case Intrinsic::x86_sse2_psra_w:
13971 case Intrinsic::x86_sse2_psra_d:
13972 case Intrinsic::x86_avx2_psra_w:
13973 case Intrinsic::x86_avx2_psra_d:
13974 Opcode = X86ISD::VSRA;
13977 return DAG.getNode(Opcode, dl, Op.getValueType(),
13978 Op.getOperand(1), Op.getOperand(2));
13981 // SSE/AVX immediate shift intrinsics
13982 case Intrinsic::x86_sse2_pslli_w:
13983 case Intrinsic::x86_sse2_pslli_d:
13984 case Intrinsic::x86_sse2_pslli_q:
13985 case Intrinsic::x86_avx2_pslli_w:
13986 case Intrinsic::x86_avx2_pslli_d:
13987 case Intrinsic::x86_avx2_pslli_q:
13988 case Intrinsic::x86_sse2_psrli_w:
13989 case Intrinsic::x86_sse2_psrli_d:
13990 case Intrinsic::x86_sse2_psrli_q:
13991 case Intrinsic::x86_avx2_psrli_w:
13992 case Intrinsic::x86_avx2_psrli_d:
13993 case Intrinsic::x86_avx2_psrli_q:
13994 case Intrinsic::x86_sse2_psrai_w:
13995 case Intrinsic::x86_sse2_psrai_d:
13996 case Intrinsic::x86_avx2_psrai_w:
13997 case Intrinsic::x86_avx2_psrai_d: {
14000 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14001 case Intrinsic::x86_sse2_pslli_w:
14002 case Intrinsic::x86_sse2_pslli_d:
14003 case Intrinsic::x86_sse2_pslli_q:
14004 case Intrinsic::x86_avx2_pslli_w:
14005 case Intrinsic::x86_avx2_pslli_d:
14006 case Intrinsic::x86_avx2_pslli_q:
14007 Opcode = X86ISD::VSHLI;
14009 case Intrinsic::x86_sse2_psrli_w:
14010 case Intrinsic::x86_sse2_psrli_d:
14011 case Intrinsic::x86_sse2_psrli_q:
14012 case Intrinsic::x86_avx2_psrli_w:
14013 case Intrinsic::x86_avx2_psrli_d:
14014 case Intrinsic::x86_avx2_psrli_q:
14015 Opcode = X86ISD::VSRLI;
14017 case Intrinsic::x86_sse2_psrai_w:
14018 case Intrinsic::x86_sse2_psrai_d:
14019 case Intrinsic::x86_avx2_psrai_w:
14020 case Intrinsic::x86_avx2_psrai_d:
14021 Opcode = X86ISD::VSRAI;
14024 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14025 Op.getOperand(1), Op.getOperand(2), DAG);
14028 case Intrinsic::x86_sse42_pcmpistria128:
14029 case Intrinsic::x86_sse42_pcmpestria128:
14030 case Intrinsic::x86_sse42_pcmpistric128:
14031 case Intrinsic::x86_sse42_pcmpestric128:
14032 case Intrinsic::x86_sse42_pcmpistrio128:
14033 case Intrinsic::x86_sse42_pcmpestrio128:
14034 case Intrinsic::x86_sse42_pcmpistris128:
14035 case Intrinsic::x86_sse42_pcmpestris128:
14036 case Intrinsic::x86_sse42_pcmpistriz128:
14037 case Intrinsic::x86_sse42_pcmpestriz128: {
14041 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14042 case Intrinsic::x86_sse42_pcmpistria128:
14043 Opcode = X86ISD::PCMPISTRI;
14044 X86CC = X86::COND_A;
14046 case Intrinsic::x86_sse42_pcmpestria128:
14047 Opcode = X86ISD::PCMPESTRI;
14048 X86CC = X86::COND_A;
14050 case Intrinsic::x86_sse42_pcmpistric128:
14051 Opcode = X86ISD::PCMPISTRI;
14052 X86CC = X86::COND_B;
14054 case Intrinsic::x86_sse42_pcmpestric128:
14055 Opcode = X86ISD::PCMPESTRI;
14056 X86CC = X86::COND_B;
14058 case Intrinsic::x86_sse42_pcmpistrio128:
14059 Opcode = X86ISD::PCMPISTRI;
14060 X86CC = X86::COND_O;
14062 case Intrinsic::x86_sse42_pcmpestrio128:
14063 Opcode = X86ISD::PCMPESTRI;
14064 X86CC = X86::COND_O;
14066 case Intrinsic::x86_sse42_pcmpistris128:
14067 Opcode = X86ISD::PCMPISTRI;
14068 X86CC = X86::COND_S;
14070 case Intrinsic::x86_sse42_pcmpestris128:
14071 Opcode = X86ISD::PCMPESTRI;
14072 X86CC = X86::COND_S;
14074 case Intrinsic::x86_sse42_pcmpistriz128:
14075 Opcode = X86ISD::PCMPISTRI;
14076 X86CC = X86::COND_E;
14078 case Intrinsic::x86_sse42_pcmpestriz128:
14079 Opcode = X86ISD::PCMPESTRI;
14080 X86CC = X86::COND_E;
14083 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14084 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14085 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14086 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14087 DAG.getConstant(X86CC, MVT::i8),
14088 SDValue(PCMP.getNode(), 1));
14089 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14092 case Intrinsic::x86_sse42_pcmpistri128:
14093 case Intrinsic::x86_sse42_pcmpestri128: {
14095 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14096 Opcode = X86ISD::PCMPISTRI;
14098 Opcode = X86ISD::PCMPESTRI;
14100 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14101 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14102 return DAG.getNode(Opcode, dl, VTs, NewOps);
14104 case Intrinsic::x86_fma_vfmadd_ps:
14105 case Intrinsic::x86_fma_vfmadd_pd:
14106 case Intrinsic::x86_fma_vfmsub_ps:
14107 case Intrinsic::x86_fma_vfmsub_pd:
14108 case Intrinsic::x86_fma_vfnmadd_ps:
14109 case Intrinsic::x86_fma_vfnmadd_pd:
14110 case Intrinsic::x86_fma_vfnmsub_ps:
14111 case Intrinsic::x86_fma_vfnmsub_pd:
14112 case Intrinsic::x86_fma_vfmaddsub_ps:
14113 case Intrinsic::x86_fma_vfmaddsub_pd:
14114 case Intrinsic::x86_fma_vfmsubadd_ps:
14115 case Intrinsic::x86_fma_vfmsubadd_pd:
14116 case Intrinsic::x86_fma_vfmadd_ps_256:
14117 case Intrinsic::x86_fma_vfmadd_pd_256:
14118 case Intrinsic::x86_fma_vfmsub_ps_256:
14119 case Intrinsic::x86_fma_vfmsub_pd_256:
14120 case Intrinsic::x86_fma_vfnmadd_ps_256:
14121 case Intrinsic::x86_fma_vfnmadd_pd_256:
14122 case Intrinsic::x86_fma_vfnmsub_ps_256:
14123 case Intrinsic::x86_fma_vfnmsub_pd_256:
14124 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14125 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14126 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14127 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14128 case Intrinsic::x86_fma_vfmadd_ps_512:
14129 case Intrinsic::x86_fma_vfmadd_pd_512:
14130 case Intrinsic::x86_fma_vfmsub_ps_512:
14131 case Intrinsic::x86_fma_vfmsub_pd_512:
14132 case Intrinsic::x86_fma_vfnmadd_ps_512:
14133 case Intrinsic::x86_fma_vfnmadd_pd_512:
14134 case Intrinsic::x86_fma_vfnmsub_ps_512:
14135 case Intrinsic::x86_fma_vfnmsub_pd_512:
14136 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14137 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14138 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14139 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14142 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14143 case Intrinsic::x86_fma_vfmadd_ps:
14144 case Intrinsic::x86_fma_vfmadd_pd:
14145 case Intrinsic::x86_fma_vfmadd_ps_256:
14146 case Intrinsic::x86_fma_vfmadd_pd_256:
14147 case Intrinsic::x86_fma_vfmadd_ps_512:
14148 case Intrinsic::x86_fma_vfmadd_pd_512:
14149 Opc = X86ISD::FMADD;
14151 case Intrinsic::x86_fma_vfmsub_ps:
14152 case Intrinsic::x86_fma_vfmsub_pd:
14153 case Intrinsic::x86_fma_vfmsub_ps_256:
14154 case Intrinsic::x86_fma_vfmsub_pd_256:
14155 case Intrinsic::x86_fma_vfmsub_ps_512:
14156 case Intrinsic::x86_fma_vfmsub_pd_512:
14157 Opc = X86ISD::FMSUB;
14159 case Intrinsic::x86_fma_vfnmadd_ps:
14160 case Intrinsic::x86_fma_vfnmadd_pd:
14161 case Intrinsic::x86_fma_vfnmadd_ps_256:
14162 case Intrinsic::x86_fma_vfnmadd_pd_256:
14163 case Intrinsic::x86_fma_vfnmadd_ps_512:
14164 case Intrinsic::x86_fma_vfnmadd_pd_512:
14165 Opc = X86ISD::FNMADD;
14167 case Intrinsic::x86_fma_vfnmsub_ps:
14168 case Intrinsic::x86_fma_vfnmsub_pd:
14169 case Intrinsic::x86_fma_vfnmsub_ps_256:
14170 case Intrinsic::x86_fma_vfnmsub_pd_256:
14171 case Intrinsic::x86_fma_vfnmsub_ps_512:
14172 case Intrinsic::x86_fma_vfnmsub_pd_512:
14173 Opc = X86ISD::FNMSUB;
14175 case Intrinsic::x86_fma_vfmaddsub_ps:
14176 case Intrinsic::x86_fma_vfmaddsub_pd:
14177 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14178 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14179 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14180 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14181 Opc = X86ISD::FMADDSUB;
14183 case Intrinsic::x86_fma_vfmsubadd_ps:
14184 case Intrinsic::x86_fma_vfmsubadd_pd:
14185 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14186 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14187 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14188 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14189 Opc = X86ISD::FMSUBADD;
14193 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14194 Op.getOperand(2), Op.getOperand(3));
14199 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14200 SDValue Src, SDValue Mask, SDValue Base,
14201 SDValue Index, SDValue ScaleOp, SDValue Chain,
14202 const X86Subtarget * Subtarget) {
14204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14205 assert(C && "Invalid scale type");
14206 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14207 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14208 Index.getSimpleValueType().getVectorNumElements());
14210 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14212 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14214 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14215 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14216 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14217 SDValue Segment = DAG.getRegister(0, MVT::i32);
14218 if (Src.getOpcode() == ISD::UNDEF)
14219 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14220 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14221 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14222 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14223 return DAG.getMergeValues(RetOps, dl);
14226 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14227 SDValue Src, SDValue Mask, SDValue Base,
14228 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14230 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14231 assert(C && "Invalid scale type");
14232 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14233 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14234 SDValue Segment = DAG.getRegister(0, MVT::i32);
14235 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14236 Index.getSimpleValueType().getVectorNumElements());
14238 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14240 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14242 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14243 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14244 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14245 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14246 return SDValue(Res, 1);
14249 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14250 SDValue Mask, SDValue Base, SDValue Index,
14251 SDValue ScaleOp, SDValue Chain) {
14253 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14254 assert(C && "Invalid scale type");
14255 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14256 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14257 SDValue Segment = DAG.getRegister(0, MVT::i32);
14259 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14261 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14263 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14265 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14266 //SDVTList VTs = DAG.getVTList(MVT::Other);
14267 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14268 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14269 return SDValue(Res, 0);
14272 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14273 // read performance monitor counters (x86_rdpmc).
14274 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14275 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14276 SmallVectorImpl<SDValue> &Results) {
14277 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14278 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14281 // The ECX register is used to select the index of the performance counter
14283 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14285 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14287 // Reads the content of a 64-bit performance counter and returns it in the
14288 // registers EDX:EAX.
14289 if (Subtarget->is64Bit()) {
14290 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14291 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14294 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14295 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14298 Chain = HI.getValue(1);
14300 if (Subtarget->is64Bit()) {
14301 // The EAX register is loaded with the low-order 32 bits. The EDX register
14302 // is loaded with the supported high-order bits of the counter.
14303 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14304 DAG.getConstant(32, MVT::i8));
14305 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14306 Results.push_back(Chain);
14310 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14311 SDValue Ops[] = { LO, HI };
14312 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14313 Results.push_back(Pair);
14314 Results.push_back(Chain);
14317 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14318 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14319 // also used to custom lower READCYCLECOUNTER nodes.
14320 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14321 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14322 SmallVectorImpl<SDValue> &Results) {
14323 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14324 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14327 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14328 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14329 // and the EAX register is loaded with the low-order 32 bits.
14330 if (Subtarget->is64Bit()) {
14331 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14332 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14335 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14336 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14339 SDValue Chain = HI.getValue(1);
14341 if (Opcode == X86ISD::RDTSCP_DAG) {
14342 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14344 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14345 // the ECX register. Add 'ecx' explicitly to the chain.
14346 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14348 // Explicitly store the content of ECX at the location passed in input
14349 // to the 'rdtscp' intrinsic.
14350 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14351 MachinePointerInfo(), false, false, 0);
14354 if (Subtarget->is64Bit()) {
14355 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14356 // the EAX register is loaded with the low-order 32 bits.
14357 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14358 DAG.getConstant(32, MVT::i8));
14359 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14360 Results.push_back(Chain);
14364 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14365 SDValue Ops[] = { LO, HI };
14366 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14367 Results.push_back(Pair);
14368 Results.push_back(Chain);
14371 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14372 SelectionDAG &DAG) {
14373 SmallVector<SDValue, 2> Results;
14375 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14377 return DAG.getMergeValues(Results, DL);
14380 enum IntrinsicType {
14381 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14384 struct IntrinsicData {
14385 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14386 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14387 IntrinsicType Type;
14392 std::map < unsigned, IntrinsicData> IntrMap;
14393 static void InitIntinsicsMap() {
14394 static bool Initialized = false;
14397 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14398 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14399 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14400 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14401 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14402 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14403 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14404 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14405 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14406 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14407 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14408 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14409 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14410 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14411 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14412 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14413 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14414 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14416 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14417 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14418 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14419 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14420 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14421 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14422 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14423 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14424 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14425 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14426 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14427 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14428 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14429 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14430 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14431 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14433 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14434 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14435 X86::VGATHERPF1QPSm)));
14436 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14437 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14438 X86::VGATHERPF1QPDm)));
14439 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14440 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14441 X86::VGATHERPF1DPDm)));
14442 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14443 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14444 X86::VGATHERPF1DPSm)));
14445 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14446 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14447 X86::VSCATTERPF1QPSm)));
14448 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14449 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14450 X86::VSCATTERPF1QPDm)));
14451 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14452 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14453 X86::VSCATTERPF1DPDm)));
14454 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14455 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14456 X86::VSCATTERPF1DPSm)));
14457 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14458 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14459 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14460 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14461 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14462 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14463 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14464 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14465 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14466 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14467 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14468 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14469 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14470 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14471 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14472 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14473 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14474 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14475 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14476 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14477 Initialized = true;
14480 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14481 SelectionDAG &DAG) {
14482 InitIntinsicsMap();
14483 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14484 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14485 if (itr == IntrMap.end())
14489 IntrinsicData Intr = itr->second;
14490 switch(Intr.Type) {
14493 // Emit the node with the right value type.
14494 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14495 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14497 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14498 // Otherwise return the value from Rand, which is always 0, casted to i32.
14499 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14500 DAG.getConstant(1, Op->getValueType(1)),
14501 DAG.getConstant(X86::COND_B, MVT::i32),
14502 SDValue(Result.getNode(), 1) };
14503 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14504 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14507 // Return { result, isValid, chain }.
14508 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14509 SDValue(Result.getNode(), 2));
14512 //gather(v1, mask, index, base, scale);
14513 SDValue Chain = Op.getOperand(0);
14514 SDValue Src = Op.getOperand(2);
14515 SDValue Base = Op.getOperand(3);
14516 SDValue Index = Op.getOperand(4);
14517 SDValue Mask = Op.getOperand(5);
14518 SDValue Scale = Op.getOperand(6);
14519 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14523 //scatter(base, mask, index, v1, scale);
14524 SDValue Chain = Op.getOperand(0);
14525 SDValue Base = Op.getOperand(2);
14526 SDValue Mask = Op.getOperand(3);
14527 SDValue Index = Op.getOperand(4);
14528 SDValue Src = Op.getOperand(5);
14529 SDValue Scale = Op.getOperand(6);
14530 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14533 SDValue Hint = Op.getOperand(6);
14535 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14536 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14537 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14538 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14539 SDValue Chain = Op.getOperand(0);
14540 SDValue Mask = Op.getOperand(2);
14541 SDValue Index = Op.getOperand(3);
14542 SDValue Base = Op.getOperand(4);
14543 SDValue Scale = Op.getOperand(5);
14544 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14546 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14548 SmallVector<SDValue, 2> Results;
14549 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14550 return DAG.getMergeValues(Results, dl);
14552 // Read Performance Monitoring Counters.
14554 SmallVector<SDValue, 2> Results;
14555 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14556 return DAG.getMergeValues(Results, dl);
14558 // XTEST intrinsics.
14560 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14561 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14562 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14563 DAG.getConstant(X86::COND_NE, MVT::i8),
14565 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14566 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14567 Ret, SDValue(InTrans.getNode(), 1));
14570 llvm_unreachable("Unknown Intrinsic Type");
14573 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14574 SelectionDAG &DAG) const {
14575 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14576 MFI->setReturnAddressIsTaken(true);
14578 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14581 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14583 EVT PtrVT = getPointerTy();
14586 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14587 const X86RegisterInfo *RegInfo =
14588 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14589 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14590 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14591 DAG.getNode(ISD::ADD, dl, PtrVT,
14592 FrameAddr, Offset),
14593 MachinePointerInfo(), false, false, false, 0);
14596 // Just load the return address.
14597 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14598 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14599 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14602 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14603 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14604 MFI->setFrameAddressIsTaken(true);
14606 EVT VT = Op.getValueType();
14607 SDLoc dl(Op); // FIXME probably not meaningful
14608 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14609 const X86RegisterInfo *RegInfo =
14610 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14611 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14612 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14613 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14614 "Invalid Frame Register!");
14615 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14617 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14618 MachinePointerInfo(),
14619 false, false, false, 0);
14623 // FIXME? Maybe this could be a TableGen attribute on some registers and
14624 // this table could be generated automatically from RegInfo.
14625 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14627 unsigned Reg = StringSwitch<unsigned>(RegName)
14628 .Case("esp", X86::ESP)
14629 .Case("rsp", X86::RSP)
14633 report_fatal_error("Invalid register name global variable");
14636 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14637 SelectionDAG &DAG) const {
14638 const X86RegisterInfo *RegInfo =
14639 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14640 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14643 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14644 SDValue Chain = Op.getOperand(0);
14645 SDValue Offset = Op.getOperand(1);
14646 SDValue Handler = Op.getOperand(2);
14649 EVT PtrVT = getPointerTy();
14650 const X86RegisterInfo *RegInfo =
14651 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14652 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14653 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14654 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14655 "Invalid Frame Register!");
14656 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14657 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14659 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14660 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14661 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14662 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14664 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14666 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14667 DAG.getRegister(StoreAddrReg, PtrVT));
14670 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14671 SelectionDAG &DAG) const {
14673 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14674 DAG.getVTList(MVT::i32, MVT::Other),
14675 Op.getOperand(0), Op.getOperand(1));
14678 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14679 SelectionDAG &DAG) const {
14681 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14682 Op.getOperand(0), Op.getOperand(1));
14685 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14686 return Op.getOperand(0);
14689 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14690 SelectionDAG &DAG) const {
14691 SDValue Root = Op.getOperand(0);
14692 SDValue Trmp = Op.getOperand(1); // trampoline
14693 SDValue FPtr = Op.getOperand(2); // nested function
14694 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14697 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14698 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14700 if (Subtarget->is64Bit()) {
14701 SDValue OutChains[6];
14703 // Large code-model.
14704 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14705 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14707 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14708 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14710 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14712 // Load the pointer to the nested function into R11.
14713 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14714 SDValue Addr = Trmp;
14715 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14716 Addr, MachinePointerInfo(TrmpAddr),
14719 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14720 DAG.getConstant(2, MVT::i64));
14721 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14722 MachinePointerInfo(TrmpAddr, 2),
14725 // Load the 'nest' parameter value into R10.
14726 // R10 is specified in X86CallingConv.td
14727 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14728 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14729 DAG.getConstant(10, MVT::i64));
14730 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14731 Addr, MachinePointerInfo(TrmpAddr, 10),
14734 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14735 DAG.getConstant(12, MVT::i64));
14736 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14737 MachinePointerInfo(TrmpAddr, 12),
14740 // Jump to the nested function.
14741 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14742 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14743 DAG.getConstant(20, MVT::i64));
14744 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14745 Addr, MachinePointerInfo(TrmpAddr, 20),
14748 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14749 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14750 DAG.getConstant(22, MVT::i64));
14751 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14752 MachinePointerInfo(TrmpAddr, 22),
14755 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14757 const Function *Func =
14758 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14759 CallingConv::ID CC = Func->getCallingConv();
14764 llvm_unreachable("Unsupported calling convention");
14765 case CallingConv::C:
14766 case CallingConv::X86_StdCall: {
14767 // Pass 'nest' parameter in ECX.
14768 // Must be kept in sync with X86CallingConv.td
14769 NestReg = X86::ECX;
14771 // Check that ECX wasn't needed by an 'inreg' parameter.
14772 FunctionType *FTy = Func->getFunctionType();
14773 const AttributeSet &Attrs = Func->getAttributes();
14775 if (!Attrs.isEmpty() && !Func->isVarArg()) {
14776 unsigned InRegCount = 0;
14779 for (FunctionType::param_iterator I = FTy->param_begin(),
14780 E = FTy->param_end(); I != E; ++I, ++Idx)
14781 if (Attrs.hasAttribute(Idx, Attribute::InReg))
14782 // FIXME: should only count parameters that are lowered to integers.
14783 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14785 if (InRegCount > 2) {
14786 report_fatal_error("Nest register in use - reduce number of inreg"
14792 case CallingConv::X86_FastCall:
14793 case CallingConv::X86_ThisCall:
14794 case CallingConv::Fast:
14795 // Pass 'nest' parameter in EAX.
14796 // Must be kept in sync with X86CallingConv.td
14797 NestReg = X86::EAX;
14801 SDValue OutChains[4];
14802 SDValue Addr, Disp;
14804 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14805 DAG.getConstant(10, MVT::i32));
14806 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14808 // This is storing the opcode for MOV32ri.
14809 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14810 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14811 OutChains[0] = DAG.getStore(Root, dl,
14812 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14813 Trmp, MachinePointerInfo(TrmpAddr),
14816 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14817 DAG.getConstant(1, MVT::i32));
14818 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14819 MachinePointerInfo(TrmpAddr, 1),
14822 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14823 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14824 DAG.getConstant(5, MVT::i32));
14825 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14826 MachinePointerInfo(TrmpAddr, 5),
14829 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14830 DAG.getConstant(6, MVT::i32));
14831 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14832 MachinePointerInfo(TrmpAddr, 6),
14835 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14839 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14840 SelectionDAG &DAG) const {
14842 The rounding mode is in bits 11:10 of FPSR, and has the following
14844 00 Round to nearest
14849 FLT_ROUNDS, on the other hand, expects the following:
14856 To perform the conversion, we do:
14857 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14860 MachineFunction &MF = DAG.getMachineFunction();
14861 const TargetMachine &TM = MF.getTarget();
14862 const TargetFrameLowering &TFI = *TM.getFrameLowering();
14863 unsigned StackAlignment = TFI.getStackAlignment();
14864 MVT VT = Op.getSimpleValueType();
14867 // Save FP Control Word to stack slot
14868 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14869 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14871 MachineMemOperand *MMO =
14872 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14873 MachineMemOperand::MOStore, 2, 2);
14875 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14876 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14877 DAG.getVTList(MVT::Other),
14878 Ops, MVT::i16, MMO);
14880 // Load FP Control Word from stack slot
14881 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14882 MachinePointerInfo(), false, false, false, 0);
14884 // Transform as necessary
14886 DAG.getNode(ISD::SRL, DL, MVT::i16,
14887 DAG.getNode(ISD::AND, DL, MVT::i16,
14888 CWD, DAG.getConstant(0x800, MVT::i16)),
14889 DAG.getConstant(11, MVT::i8));
14891 DAG.getNode(ISD::SRL, DL, MVT::i16,
14892 DAG.getNode(ISD::AND, DL, MVT::i16,
14893 CWD, DAG.getConstant(0x400, MVT::i16)),
14894 DAG.getConstant(9, MVT::i8));
14897 DAG.getNode(ISD::AND, DL, MVT::i16,
14898 DAG.getNode(ISD::ADD, DL, MVT::i16,
14899 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14900 DAG.getConstant(1, MVT::i16)),
14901 DAG.getConstant(3, MVT::i16));
14903 return DAG.getNode((VT.getSizeInBits() < 16 ?
14904 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14907 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14908 MVT VT = Op.getSimpleValueType();
14910 unsigned NumBits = VT.getSizeInBits();
14913 Op = Op.getOperand(0);
14914 if (VT == MVT::i8) {
14915 // Zero extend to i32 since there is not an i8 bsr.
14917 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14920 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14921 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14922 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14924 // If src is zero (i.e. bsr sets ZF), returns NumBits.
14927 DAG.getConstant(NumBits+NumBits-1, OpVT),
14928 DAG.getConstant(X86::COND_E, MVT::i8),
14931 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14933 // Finally xor with NumBits-1.
14934 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14937 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14941 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14942 MVT VT = Op.getSimpleValueType();
14944 unsigned NumBits = VT.getSizeInBits();
14947 Op = Op.getOperand(0);
14948 if (VT == MVT::i8) {
14949 // Zero extend to i32 since there is not an i8 bsr.
14951 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14954 // Issue a bsr (scan bits in reverse).
14955 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14956 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14958 // And xor with NumBits-1.
14959 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14962 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14966 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14967 MVT VT = Op.getSimpleValueType();
14968 unsigned NumBits = VT.getSizeInBits();
14970 Op = Op.getOperand(0);
14972 // Issue a bsf (scan bits forward) which also sets EFLAGS.
14973 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14974 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14976 // If src is zero (i.e. bsf sets ZF), returns NumBits.
14979 DAG.getConstant(NumBits, VT),
14980 DAG.getConstant(X86::COND_E, MVT::i8),
14983 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14986 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14987 // ones, and then concatenate the result back.
14988 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14989 MVT VT = Op.getSimpleValueType();
14991 assert(VT.is256BitVector() && VT.isInteger() &&
14992 "Unsupported value type for operation");
14994 unsigned NumElems = VT.getVectorNumElements();
14997 // Extract the LHS vectors
14998 SDValue LHS = Op.getOperand(0);
14999 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15000 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15002 // Extract the RHS vectors
15003 SDValue RHS = Op.getOperand(1);
15004 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15005 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15007 MVT EltVT = VT.getVectorElementType();
15008 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15010 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15011 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15012 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15015 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15016 assert(Op.getSimpleValueType().is256BitVector() &&
15017 Op.getSimpleValueType().isInteger() &&
15018 "Only handle AVX 256-bit vector integer operation");
15019 return Lower256IntArith(Op, DAG);
15022 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15023 assert(Op.getSimpleValueType().is256BitVector() &&
15024 Op.getSimpleValueType().isInteger() &&
15025 "Only handle AVX 256-bit vector integer operation");
15026 return Lower256IntArith(Op, DAG);
15029 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15030 SelectionDAG &DAG) {
15032 MVT VT = Op.getSimpleValueType();
15034 // Decompose 256-bit ops into smaller 128-bit ops.
15035 if (VT.is256BitVector() && !Subtarget->hasInt256())
15036 return Lower256IntArith(Op, DAG);
15038 SDValue A = Op.getOperand(0);
15039 SDValue B = Op.getOperand(1);
15041 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15042 if (VT == MVT::v4i32) {
15043 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15044 "Should not custom lower when pmuldq is available!");
15046 // Extract the odd parts.
15047 static const int UnpackMask[] = { 1, -1, 3, -1 };
15048 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15049 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15051 // Multiply the even parts.
15052 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15053 // Now multiply odd parts.
15054 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15056 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15057 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15059 // Merge the two vectors back together with a shuffle. This expands into 2
15061 static const int ShufMask[] = { 0, 4, 2, 6 };
15062 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15065 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15066 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15068 // Ahi = psrlqi(a, 32);
15069 // Bhi = psrlqi(b, 32);
15071 // AloBlo = pmuludq(a, b);
15072 // AloBhi = pmuludq(a, Bhi);
15073 // AhiBlo = pmuludq(Ahi, b);
15075 // AloBhi = psllqi(AloBhi, 32);
15076 // AhiBlo = psllqi(AhiBlo, 32);
15077 // return AloBlo + AloBhi + AhiBlo;
15079 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15080 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15082 // Bit cast to 32-bit vectors for MULUDQ
15083 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15084 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15085 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15086 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15087 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15088 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15090 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15091 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15092 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15094 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15095 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15097 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15098 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15101 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15102 assert(Subtarget->isTargetWin64() && "Unexpected target");
15103 EVT VT = Op.getValueType();
15104 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15105 "Unexpected return type for lowering");
15109 switch (Op->getOpcode()) {
15110 default: llvm_unreachable("Unexpected request for libcall!");
15111 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15112 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15113 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15114 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15115 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15116 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15120 SDValue InChain = DAG.getEntryNode();
15122 TargetLowering::ArgListTy Args;
15123 TargetLowering::ArgListEntry Entry;
15124 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15125 EVT ArgVT = Op->getOperand(i).getValueType();
15126 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15127 "Unexpected argument type for lowering");
15128 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15129 Entry.Node = StackPtr;
15130 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15132 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15133 Entry.Ty = PointerType::get(ArgTy,0);
15134 Entry.isSExt = false;
15135 Entry.isZExt = false;
15136 Args.push_back(Entry);
15139 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15142 TargetLowering::CallLoweringInfo CLI(DAG);
15143 CLI.setDebugLoc(dl).setChain(InChain)
15144 .setCallee(getLibcallCallingConv(LC),
15145 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15146 Callee, std::move(Args), 0)
15147 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15149 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15150 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15153 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15154 SelectionDAG &DAG) {
15155 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15156 EVT VT = Op0.getValueType();
15159 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15160 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15162 // Get the high parts.
15163 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
15164 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15165 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15167 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15169 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15170 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15172 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15173 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15174 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15175 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15176 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15178 // Shuffle it back into the right order.
15179 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15180 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15181 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15182 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15184 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15185 // unsigned multiply.
15186 if (IsSigned && !Subtarget->hasSSE41()) {
15188 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15189 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15190 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15191 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15192 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15194 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15195 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15198 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15201 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15202 const X86Subtarget *Subtarget) {
15203 MVT VT = Op.getSimpleValueType();
15205 SDValue R = Op.getOperand(0);
15206 SDValue Amt = Op.getOperand(1);
15208 // Optimize shl/srl/sra with constant shift amount.
15209 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15210 if (SDValue Splat = BVAmt->getConstantSplatValue()) {
15211 uint64_t ShiftAmt = Splat.getOpcode() == ISD::UNDEF
15213 : cast<ConstantSDNode>(Splat)->getZExtValue();
15215 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15216 (Subtarget->hasInt256() &&
15217 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15218 (Subtarget->hasAVX512() &&
15219 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15220 if (Op.getOpcode() == ISD::SHL)
15221 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15223 if (Op.getOpcode() == ISD::SRL)
15224 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15226 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15227 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15231 if (VT == MVT::v16i8) {
15232 if (Op.getOpcode() == ISD::SHL) {
15233 // Make a large shift.
15234 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15235 MVT::v8i16, R, ShiftAmt,
15237 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15238 // Zero out the rightmost bits.
15239 SmallVector<SDValue, 16> V(16,
15240 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15242 return DAG.getNode(ISD::AND, dl, VT, SHL,
15243 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15245 if (Op.getOpcode() == ISD::SRL) {
15246 // Make a large shift.
15247 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15248 MVT::v8i16, R, ShiftAmt,
15250 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15251 // Zero out the leftmost bits.
15252 SmallVector<SDValue, 16> V(16,
15253 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15255 return DAG.getNode(ISD::AND, dl, VT, SRL,
15256 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15258 if (Op.getOpcode() == ISD::SRA) {
15259 if (ShiftAmt == 7) {
15260 // R s>> 7 === R s< 0
15261 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15262 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15265 // R s>> a === ((R u>> a) ^ m) - m
15266 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15267 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15269 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15270 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15271 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15274 llvm_unreachable("Unknown shift opcode.");
15277 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15278 if (Op.getOpcode() == ISD::SHL) {
15279 // Make a large shift.
15280 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15281 MVT::v16i16, R, ShiftAmt,
15283 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15284 // Zero out the rightmost bits.
15285 SmallVector<SDValue, 32> V(32,
15286 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15288 return DAG.getNode(ISD::AND, dl, VT, SHL,
15289 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15291 if (Op.getOpcode() == ISD::SRL) {
15292 // Make a large shift.
15293 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15294 MVT::v16i16, R, ShiftAmt,
15296 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15297 // Zero out the leftmost bits.
15298 SmallVector<SDValue, 32> V(32,
15299 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15301 return DAG.getNode(ISD::AND, dl, VT, SRL,
15302 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15304 if (Op.getOpcode() == ISD::SRA) {
15305 if (ShiftAmt == 7) {
15306 // R s>> 7 === R s< 0
15307 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15308 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15311 // R s>> a === ((R u>> a) ^ m) - m
15312 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15313 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15315 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15316 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15317 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15320 llvm_unreachable("Unknown shift opcode.");
15325 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15326 if (!Subtarget->is64Bit() &&
15327 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15328 Amt.getOpcode() == ISD::BITCAST &&
15329 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15330 Amt = Amt.getOperand(0);
15331 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15332 VT.getVectorNumElements();
15333 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15334 uint64_t ShiftAmt = 0;
15335 for (unsigned i = 0; i != Ratio; ++i) {
15336 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15340 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15342 // Check remaining shift amounts.
15343 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15344 uint64_t ShAmt = 0;
15345 for (unsigned j = 0; j != Ratio; ++j) {
15346 ConstantSDNode *C =
15347 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15351 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15353 if (ShAmt != ShiftAmt)
15356 switch (Op.getOpcode()) {
15358 llvm_unreachable("Unknown shift opcode!");
15360 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15363 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15366 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15374 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15375 const X86Subtarget* Subtarget) {
15376 MVT VT = Op.getSimpleValueType();
15378 SDValue R = Op.getOperand(0);
15379 SDValue Amt = Op.getOperand(1);
15381 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15382 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15383 (Subtarget->hasInt256() &&
15384 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15385 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15386 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15388 EVT EltVT = VT.getVectorElementType();
15390 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15391 unsigned NumElts = VT.getVectorNumElements();
15393 for (i = 0; i != NumElts; ++i) {
15394 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15398 for (j = i; j != NumElts; ++j) {
15399 SDValue Arg = Amt.getOperand(j);
15400 if (Arg.getOpcode() == ISD::UNDEF) continue;
15401 if (Arg != Amt.getOperand(i))
15404 if (i != NumElts && j == NumElts)
15405 BaseShAmt = Amt.getOperand(i);
15407 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15408 Amt = Amt.getOperand(0);
15409 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15410 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15411 SDValue InVec = Amt.getOperand(0);
15412 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15413 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15415 for (; i != NumElts; ++i) {
15416 SDValue Arg = InVec.getOperand(i);
15417 if (Arg.getOpcode() == ISD::UNDEF) continue;
15421 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15422 if (ConstantSDNode *C =
15423 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15424 unsigned SplatIdx =
15425 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15426 if (C->getZExtValue() == SplatIdx)
15427 BaseShAmt = InVec.getOperand(1);
15430 if (!BaseShAmt.getNode())
15431 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15432 DAG.getIntPtrConstant(0));
15436 if (BaseShAmt.getNode()) {
15437 if (EltVT.bitsGT(MVT::i32))
15438 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15439 else if (EltVT.bitsLT(MVT::i32))
15440 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15442 switch (Op.getOpcode()) {
15444 llvm_unreachable("Unknown shift opcode!");
15446 switch (VT.SimpleTy) {
15447 default: return SDValue();
15456 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15459 switch (VT.SimpleTy) {
15460 default: return SDValue();
15467 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15470 switch (VT.SimpleTy) {
15471 default: return SDValue();
15480 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15486 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15487 if (!Subtarget->is64Bit() &&
15488 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15489 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15490 Amt.getOpcode() == ISD::BITCAST &&
15491 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15492 Amt = Amt.getOperand(0);
15493 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15494 VT.getVectorNumElements();
15495 std::vector<SDValue> Vals(Ratio);
15496 for (unsigned i = 0; i != Ratio; ++i)
15497 Vals[i] = Amt.getOperand(i);
15498 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15499 for (unsigned j = 0; j != Ratio; ++j)
15500 if (Vals[j] != Amt.getOperand(i + j))
15503 switch (Op.getOpcode()) {
15505 llvm_unreachable("Unknown shift opcode!");
15507 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15509 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15511 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15518 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15519 SelectionDAG &DAG) {
15520 MVT VT = Op.getSimpleValueType();
15522 SDValue R = Op.getOperand(0);
15523 SDValue Amt = Op.getOperand(1);
15526 assert(VT.isVector() && "Custom lowering only for vector shifts!");
15527 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15529 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15533 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15537 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15539 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15540 if (Subtarget->hasInt256()) {
15541 if (Op.getOpcode() == ISD::SRL &&
15542 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15543 VT == MVT::v4i64 || VT == MVT::v8i32))
15545 if (Op.getOpcode() == ISD::SHL &&
15546 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15547 VT == MVT::v4i64 || VT == MVT::v8i32))
15549 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15553 // If possible, lower this packed shift into a vector multiply instead of
15554 // expanding it into a sequence of scalar shifts.
15555 // Do this only if the vector shift count is a constant build_vector.
15556 if (Op.getOpcode() == ISD::SHL &&
15557 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15558 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15559 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15560 SmallVector<SDValue, 8> Elts;
15561 EVT SVT = VT.getScalarType();
15562 unsigned SVTBits = SVT.getSizeInBits();
15563 const APInt &One = APInt(SVTBits, 1);
15564 unsigned NumElems = VT.getVectorNumElements();
15566 for (unsigned i=0; i !=NumElems; ++i) {
15567 SDValue Op = Amt->getOperand(i);
15568 if (Op->getOpcode() == ISD::UNDEF) {
15569 Elts.push_back(Op);
15573 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15574 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15575 uint64_t ShAmt = C.getZExtValue();
15576 if (ShAmt >= SVTBits) {
15577 Elts.push_back(DAG.getUNDEF(SVT));
15580 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15582 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15583 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15586 // Lower SHL with variable shift amount.
15587 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15588 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15590 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15591 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15592 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15593 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15596 // If possible, lower this shift as a sequence of two shifts by
15597 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15599 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15601 // Could be rewritten as:
15602 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15604 // The advantage is that the two shifts from the example would be
15605 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15606 // the vector shift into four scalar shifts plus four pairs of vector
15608 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15609 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15610 unsigned TargetOpcode = X86ISD::MOVSS;
15611 bool CanBeSimplified;
15612 // The splat value for the first packed shift (the 'X' from the example).
15613 SDValue Amt1 = Amt->getOperand(0);
15614 // The splat value for the second packed shift (the 'Y' from the example).
15615 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15616 Amt->getOperand(2);
15618 // See if it is possible to replace this node with a sequence of
15619 // two shifts followed by a MOVSS/MOVSD
15620 if (VT == MVT::v4i32) {
15621 // Check if it is legal to use a MOVSS.
15622 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15623 Amt2 == Amt->getOperand(3);
15624 if (!CanBeSimplified) {
15625 // Otherwise, check if we can still simplify this node using a MOVSD.
15626 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15627 Amt->getOperand(2) == Amt->getOperand(3);
15628 TargetOpcode = X86ISD::MOVSD;
15629 Amt2 = Amt->getOperand(2);
15632 // Do similar checks for the case where the machine value type
15634 CanBeSimplified = Amt1 == Amt->getOperand(1);
15635 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15636 CanBeSimplified = Amt2 == Amt->getOperand(i);
15638 if (!CanBeSimplified) {
15639 TargetOpcode = X86ISD::MOVSD;
15640 CanBeSimplified = true;
15641 Amt2 = Amt->getOperand(4);
15642 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15643 CanBeSimplified = Amt1 == Amt->getOperand(i);
15644 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15645 CanBeSimplified = Amt2 == Amt->getOperand(j);
15649 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15650 isa<ConstantSDNode>(Amt2)) {
15651 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15652 EVT CastVT = MVT::v4i32;
15654 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15655 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15657 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15658 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15659 if (TargetOpcode == X86ISD::MOVSD)
15660 CastVT = MVT::v2i64;
15661 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15662 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15663 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15665 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15669 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15670 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15673 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15674 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15676 // Turn 'a' into a mask suitable for VSELECT
15677 SDValue VSelM = DAG.getConstant(0x80, VT);
15678 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15679 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15681 SDValue CM1 = DAG.getConstant(0x0f, VT);
15682 SDValue CM2 = DAG.getConstant(0x3f, VT);
15684 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15685 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15686 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15687 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15688 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15691 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15692 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15693 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15695 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15696 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15697 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15698 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15699 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15702 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15703 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15704 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15706 // return VSELECT(r, r+r, a);
15707 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15708 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15712 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15713 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15714 // solution better.
15715 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15716 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15718 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15719 R = DAG.getNode(ExtOpc, dl, NewVT, R);
15720 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15721 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15722 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15725 // Decompose 256-bit shifts into smaller 128-bit shifts.
15726 if (VT.is256BitVector()) {
15727 unsigned NumElems = VT.getVectorNumElements();
15728 MVT EltVT = VT.getVectorElementType();
15729 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15731 // Extract the two vectors
15732 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15733 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15735 // Recreate the shift amount vectors
15736 SDValue Amt1, Amt2;
15737 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15738 // Constant shift amount
15739 SmallVector<SDValue, 4> Amt1Csts;
15740 SmallVector<SDValue, 4> Amt2Csts;
15741 for (unsigned i = 0; i != NumElems/2; ++i)
15742 Amt1Csts.push_back(Amt->getOperand(i));
15743 for (unsigned i = NumElems/2; i != NumElems; ++i)
15744 Amt2Csts.push_back(Amt->getOperand(i));
15746 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15747 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15749 // Variable shift amount
15750 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15751 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15754 // Issue new vector shifts for the smaller types
15755 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15756 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15758 // Concatenate the result back
15759 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15765 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15766 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15767 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15768 // looks for this combo and may remove the "setcc" instruction if the "setcc"
15769 // has only one use.
15770 SDNode *N = Op.getNode();
15771 SDValue LHS = N->getOperand(0);
15772 SDValue RHS = N->getOperand(1);
15773 unsigned BaseOp = 0;
15776 switch (Op.getOpcode()) {
15777 default: llvm_unreachable("Unknown ovf instruction!");
15779 // A subtract of one will be selected as a INC. Note that INC doesn't
15780 // set CF, so we can't do this for UADDO.
15781 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15783 BaseOp = X86ISD::INC;
15784 Cond = X86::COND_O;
15787 BaseOp = X86ISD::ADD;
15788 Cond = X86::COND_O;
15791 BaseOp = X86ISD::ADD;
15792 Cond = X86::COND_B;
15795 // A subtract of one will be selected as a DEC. Note that DEC doesn't
15796 // set CF, so we can't do this for USUBO.
15797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15799 BaseOp = X86ISD::DEC;
15800 Cond = X86::COND_O;
15803 BaseOp = X86ISD::SUB;
15804 Cond = X86::COND_O;
15807 BaseOp = X86ISD::SUB;
15808 Cond = X86::COND_B;
15811 BaseOp = X86ISD::SMUL;
15812 Cond = X86::COND_O;
15814 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15815 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15817 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15820 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15821 DAG.getConstant(X86::COND_O, MVT::i32),
15822 SDValue(Sum.getNode(), 2));
15824 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15828 // Also sets EFLAGS.
15829 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15830 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15833 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15834 DAG.getConstant(Cond, MVT::i32),
15835 SDValue(Sum.getNode(), 1));
15837 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15840 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15841 SelectionDAG &DAG) const {
15843 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15844 MVT VT = Op.getSimpleValueType();
15846 if (!Subtarget->hasSSE2() || !VT.isVector())
15849 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15850 ExtraVT.getScalarType().getSizeInBits();
15852 switch (VT.SimpleTy) {
15853 default: return SDValue();
15856 if (!Subtarget->hasFp256())
15858 if (!Subtarget->hasInt256()) {
15859 // needs to be split
15860 unsigned NumElems = VT.getVectorNumElements();
15862 // Extract the LHS vectors
15863 SDValue LHS = Op.getOperand(0);
15864 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15865 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15867 MVT EltVT = VT.getVectorElementType();
15868 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15870 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15871 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15872 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15874 SDValue Extra = DAG.getValueType(ExtraVT);
15876 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15877 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15879 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15884 SDValue Op0 = Op.getOperand(0);
15885 SDValue Op00 = Op0.getOperand(0);
15887 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15888 if (Op0.getOpcode() == ISD::BITCAST &&
15889 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15890 // (sext (vzext x)) -> (vsext x)
15891 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15892 if (Tmp1.getNode()) {
15893 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15894 // This folding is only valid when the in-reg type is a vector of i8,
15896 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15897 ExtraEltVT == MVT::i32) {
15898 SDValue Tmp1Op0 = Tmp1.getOperand(0);
15899 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15900 "This optimization is invalid without a VZEXT.");
15901 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15907 // If the above didn't work, then just use Shift-Left + Shift-Right.
15908 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15910 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15916 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15917 SelectionDAG &DAG) {
15919 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15920 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15921 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15922 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15924 // The only fence that needs an instruction is a sequentially-consistent
15925 // cross-thread fence.
15926 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15927 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15928 // no-sse2). There isn't any reason to disable it if the target processor
15930 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15931 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15933 SDValue Chain = Op.getOperand(0);
15934 SDValue Zero = DAG.getConstant(0, MVT::i32);
15936 DAG.getRegister(X86::ESP, MVT::i32), // Base
15937 DAG.getTargetConstant(1, MVT::i8), // Scale
15938 DAG.getRegister(0, MVT::i32), // Index
15939 DAG.getTargetConstant(0, MVT::i32), // Disp
15940 DAG.getRegister(0, MVT::i32), // Segment.
15944 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15945 return SDValue(Res, 0);
15948 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15949 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15952 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15953 SelectionDAG &DAG) {
15954 MVT T = Op.getSimpleValueType();
15958 switch(T.SimpleTy) {
15959 default: llvm_unreachable("Invalid value type!");
15960 case MVT::i8: Reg = X86::AL; size = 1; break;
15961 case MVT::i16: Reg = X86::AX; size = 2; break;
15962 case MVT::i32: Reg = X86::EAX; size = 4; break;
15964 assert(Subtarget->is64Bit() && "Node not type legal!");
15965 Reg = X86::RAX; size = 8;
15968 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15969 Op.getOperand(2), SDValue());
15970 SDValue Ops[] = { cpIn.getValue(0),
15973 DAG.getTargetConstant(size, MVT::i8),
15974 cpIn.getValue(1) };
15975 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15976 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15977 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15981 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15982 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15983 MVT::i32, cpOut.getValue(2));
15984 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15985 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15987 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15988 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15989 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15993 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15994 SelectionDAG &DAG) {
15995 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15996 MVT DstVT = Op.getSimpleValueType();
15998 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15999 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16000 if (DstVT != MVT::f64)
16001 // This conversion needs to be expanded.
16004 SDValue InVec = Op->getOperand(0);
16006 unsigned NumElts = SrcVT.getVectorNumElements();
16007 EVT SVT = SrcVT.getVectorElementType();
16009 // Widen the vector in input in the case of MVT::v2i32.
16010 // Example: from MVT::v2i32 to MVT::v4i32.
16011 SmallVector<SDValue, 16> Elts;
16012 for (unsigned i = 0, e = NumElts; i != e; ++i)
16013 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16014 DAG.getIntPtrConstant(i)));
16016 // Explicitly mark the extra elements as Undef.
16017 SDValue Undef = DAG.getUNDEF(SVT);
16018 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16019 Elts.push_back(Undef);
16021 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16022 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16023 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16024 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16025 DAG.getIntPtrConstant(0));
16028 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16029 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16030 assert((DstVT == MVT::i64 ||
16031 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16032 "Unexpected custom BITCAST");
16033 // i64 <=> MMX conversions are Legal.
16034 if (SrcVT==MVT::i64 && DstVT.isVector())
16036 if (DstVT==MVT::i64 && SrcVT.isVector())
16038 // MMX <=> MMX conversions are Legal.
16039 if (SrcVT.isVector() && DstVT.isVector())
16041 // All other conversions need to be expanded.
16045 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16046 SDNode *Node = Op.getNode();
16048 EVT T = Node->getValueType(0);
16049 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16050 DAG.getConstant(0, T), Node->getOperand(2));
16051 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16052 cast<AtomicSDNode>(Node)->getMemoryVT(),
16053 Node->getOperand(0),
16054 Node->getOperand(1), negOp,
16055 cast<AtomicSDNode>(Node)->getMemOperand(),
16056 cast<AtomicSDNode>(Node)->getOrdering(),
16057 cast<AtomicSDNode>(Node)->getSynchScope());
16060 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16061 SDNode *Node = Op.getNode();
16063 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16065 // Convert seq_cst store -> xchg
16066 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16067 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16068 // (The only way to get a 16-byte store is cmpxchg16b)
16069 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16070 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16071 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16072 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16073 cast<AtomicSDNode>(Node)->getMemoryVT(),
16074 Node->getOperand(0),
16075 Node->getOperand(1), Node->getOperand(2),
16076 cast<AtomicSDNode>(Node)->getMemOperand(),
16077 cast<AtomicSDNode>(Node)->getOrdering(),
16078 cast<AtomicSDNode>(Node)->getSynchScope());
16079 return Swap.getValue(1);
16081 // Other atomic stores have a simple pattern.
16085 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16086 EVT VT = Op.getNode()->getSimpleValueType(0);
16088 // Let legalize expand this if it isn't a legal type yet.
16089 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16092 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16095 bool ExtraOp = false;
16096 switch (Op.getOpcode()) {
16097 default: llvm_unreachable("Invalid code");
16098 case ISD::ADDC: Opc = X86ISD::ADD; break;
16099 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16100 case ISD::SUBC: Opc = X86ISD::SUB; break;
16101 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16105 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16107 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16108 Op.getOperand(1), Op.getOperand(2));
16111 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16112 SelectionDAG &DAG) {
16113 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16115 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16116 // which returns the values as { float, float } (in XMM0) or
16117 // { double, double } (which is returned in XMM0, XMM1).
16119 SDValue Arg = Op.getOperand(0);
16120 EVT ArgVT = Arg.getValueType();
16121 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16123 TargetLowering::ArgListTy Args;
16124 TargetLowering::ArgListEntry Entry;
16128 Entry.isSExt = false;
16129 Entry.isZExt = false;
16130 Args.push_back(Entry);
16132 bool isF64 = ArgVT == MVT::f64;
16133 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16134 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16135 // the results are returned via SRet in memory.
16136 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16138 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16140 Type *RetTy = isF64
16141 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16142 : (Type*)VectorType::get(ArgTy, 4);
16144 TargetLowering::CallLoweringInfo CLI(DAG);
16145 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16146 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16148 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16151 // Returned in xmm0 and xmm1.
16152 return CallResult.first;
16154 // Returned in bits 0:31 and 32:64 xmm0.
16155 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16156 CallResult.first, DAG.getIntPtrConstant(0));
16157 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16158 CallResult.first, DAG.getIntPtrConstant(1));
16159 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16160 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16163 /// LowerOperation - Provide custom lowering hooks for some operations.
16165 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16166 switch (Op.getOpcode()) {
16167 default: llvm_unreachable("Should not custom lower this!");
16168 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16169 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16170 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16171 return LowerCMP_SWAP(Op, Subtarget, DAG);
16172 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16173 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16174 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16175 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16176 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16177 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16178 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16179 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16180 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16181 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16182 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16183 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16184 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16185 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16186 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16187 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16188 case ISD::SHL_PARTS:
16189 case ISD::SRA_PARTS:
16190 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16191 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16192 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16193 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16194 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16195 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16196 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16197 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16198 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16199 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16200 case ISD::FABS: return LowerFABS(Op, DAG);
16201 case ISD::FNEG: return LowerFNEG(Op, DAG);
16202 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16203 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16204 case ISD::SETCC: return LowerSETCC(Op, DAG);
16205 case ISD::SELECT: return LowerSELECT(Op, DAG);
16206 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16207 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16208 case ISD::VASTART: return LowerVASTART(Op, DAG);
16209 case ISD::VAARG: return LowerVAARG(Op, DAG);
16210 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16211 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16212 case ISD::INTRINSIC_VOID:
16213 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16214 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16215 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16216 case ISD::FRAME_TO_ARGS_OFFSET:
16217 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16218 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16219 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16220 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16221 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16222 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16223 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16224 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16225 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16226 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16227 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16228 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16229 case ISD::UMUL_LOHI:
16230 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16233 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16239 case ISD::UMULO: return LowerXALUO(Op, DAG);
16240 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16241 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16245 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16246 case ISD::ADD: return LowerADD(Op, DAG);
16247 case ISD::SUB: return LowerSUB(Op, DAG);
16248 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16252 static void ReplaceATOMIC_LOAD(SDNode *Node,
16253 SmallVectorImpl<SDValue> &Results,
16254 SelectionDAG &DAG) {
16256 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16258 // Convert wide load -> cmpxchg8b/cmpxchg16b
16259 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16260 // (The only way to get a 16-byte load is cmpxchg16b)
16261 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16262 SDValue Zero = DAG.getConstant(0, VT);
16263 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16265 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16266 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16267 cast<AtomicSDNode>(Node)->getMemOperand(),
16268 cast<AtomicSDNode>(Node)->getOrdering(),
16269 cast<AtomicSDNode>(Node)->getOrdering(),
16270 cast<AtomicSDNode>(Node)->getSynchScope());
16271 Results.push_back(Swap.getValue(0));
16272 Results.push_back(Swap.getValue(2));
16275 /// ReplaceNodeResults - Replace a node with an illegal result type
16276 /// with a new node built out of custom code.
16277 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16278 SmallVectorImpl<SDValue>&Results,
16279 SelectionDAG &DAG) const {
16281 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16282 switch (N->getOpcode()) {
16284 llvm_unreachable("Do not know how to custom type legalize this operation!");
16285 case ISD::SIGN_EXTEND_INREG:
16290 // We don't want to expand or promote these.
16297 case ISD::UDIVREM: {
16298 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16299 Results.push_back(V);
16302 case ISD::FP_TO_SINT:
16303 case ISD::FP_TO_UINT: {
16304 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16306 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16309 std::pair<SDValue,SDValue> Vals =
16310 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16311 SDValue FIST = Vals.first, StackSlot = Vals.second;
16312 if (FIST.getNode()) {
16313 EVT VT = N->getValueType(0);
16314 // Return a load from the stack slot.
16315 if (StackSlot.getNode())
16316 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16317 MachinePointerInfo(),
16318 false, false, false, 0));
16320 Results.push_back(FIST);
16324 case ISD::UINT_TO_FP: {
16325 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16326 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16327 N->getValueType(0) != MVT::v2f32)
16329 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16331 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16333 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16334 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16335 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16336 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16337 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16338 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16341 case ISD::FP_ROUND: {
16342 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16344 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16345 Results.push_back(V);
16348 case ISD::INTRINSIC_W_CHAIN: {
16349 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16351 default : llvm_unreachable("Do not know how to custom type "
16352 "legalize this intrinsic operation!");
16353 case Intrinsic::x86_rdtsc:
16354 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16356 case Intrinsic::x86_rdtscp:
16357 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16359 case Intrinsic::x86_rdpmc:
16360 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16363 case ISD::READCYCLECOUNTER: {
16364 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16367 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16368 EVT T = N->getValueType(0);
16369 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16370 bool Regs64bit = T == MVT::i128;
16371 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16372 SDValue cpInL, cpInH;
16373 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16374 DAG.getConstant(0, HalfT));
16375 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16376 DAG.getConstant(1, HalfT));
16377 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16378 Regs64bit ? X86::RAX : X86::EAX,
16380 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16381 Regs64bit ? X86::RDX : X86::EDX,
16382 cpInH, cpInL.getValue(1));
16383 SDValue swapInL, swapInH;
16384 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16385 DAG.getConstant(0, HalfT));
16386 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16387 DAG.getConstant(1, HalfT));
16388 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16389 Regs64bit ? X86::RBX : X86::EBX,
16390 swapInL, cpInH.getValue(1));
16391 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16392 Regs64bit ? X86::RCX : X86::ECX,
16393 swapInH, swapInL.getValue(1));
16394 SDValue Ops[] = { swapInH.getValue(0),
16396 swapInH.getValue(1) };
16397 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16398 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16399 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16400 X86ISD::LCMPXCHG8_DAG;
16401 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16402 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16403 Regs64bit ? X86::RAX : X86::EAX,
16404 HalfT, Result.getValue(1));
16405 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16406 Regs64bit ? X86::RDX : X86::EDX,
16407 HalfT, cpOutL.getValue(2));
16408 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16410 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16411 MVT::i32, cpOutH.getValue(2));
16413 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16414 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16415 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16417 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16418 Results.push_back(Success);
16419 Results.push_back(EFLAGS.getValue(1));
16422 case ISD::ATOMIC_SWAP:
16423 case ISD::ATOMIC_LOAD_ADD:
16424 case ISD::ATOMIC_LOAD_SUB:
16425 case ISD::ATOMIC_LOAD_AND:
16426 case ISD::ATOMIC_LOAD_OR:
16427 case ISD::ATOMIC_LOAD_XOR:
16428 case ISD::ATOMIC_LOAD_NAND:
16429 case ISD::ATOMIC_LOAD_MIN:
16430 case ISD::ATOMIC_LOAD_MAX:
16431 case ISD::ATOMIC_LOAD_UMIN:
16432 case ISD::ATOMIC_LOAD_UMAX:
16433 // Delegate to generic TypeLegalization. Situations we can really handle
16434 // should have already been dealt with by X86AtomicExpand.cpp.
16436 case ISD::ATOMIC_LOAD: {
16437 ReplaceATOMIC_LOAD(N, Results, DAG);
16440 case ISD::BITCAST: {
16441 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16442 EVT DstVT = N->getValueType(0);
16443 EVT SrcVT = N->getOperand(0)->getValueType(0);
16445 if (SrcVT != MVT::f64 ||
16446 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16449 unsigned NumElts = DstVT.getVectorNumElements();
16450 EVT SVT = DstVT.getVectorElementType();
16451 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16452 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16453 MVT::v2f64, N->getOperand(0));
16454 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16456 if (ExperimentalVectorWideningLegalization) {
16457 // If we are legalizing vectors by widening, we already have the desired
16458 // legal vector type, just return it.
16459 Results.push_back(ToVecInt);
16463 SmallVector<SDValue, 8> Elts;
16464 for (unsigned i = 0, e = NumElts; i != e; ++i)
16465 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16466 ToVecInt, DAG.getIntPtrConstant(i)));
16468 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16473 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16475 default: return nullptr;
16476 case X86ISD::BSF: return "X86ISD::BSF";
16477 case X86ISD::BSR: return "X86ISD::BSR";
16478 case X86ISD::SHLD: return "X86ISD::SHLD";
16479 case X86ISD::SHRD: return "X86ISD::SHRD";
16480 case X86ISD::FAND: return "X86ISD::FAND";
16481 case X86ISD::FANDN: return "X86ISD::FANDN";
16482 case X86ISD::FOR: return "X86ISD::FOR";
16483 case X86ISD::FXOR: return "X86ISD::FXOR";
16484 case X86ISD::FSRL: return "X86ISD::FSRL";
16485 case X86ISD::FILD: return "X86ISD::FILD";
16486 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16487 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16488 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16489 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16490 case X86ISD::FLD: return "X86ISD::FLD";
16491 case X86ISD::FST: return "X86ISD::FST";
16492 case X86ISD::CALL: return "X86ISD::CALL";
16493 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16494 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16495 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16496 case X86ISD::BT: return "X86ISD::BT";
16497 case X86ISD::CMP: return "X86ISD::CMP";
16498 case X86ISD::COMI: return "X86ISD::COMI";
16499 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16500 case X86ISD::CMPM: return "X86ISD::CMPM";
16501 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16502 case X86ISD::SETCC: return "X86ISD::SETCC";
16503 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16504 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16505 case X86ISD::CMOV: return "X86ISD::CMOV";
16506 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16507 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16508 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16509 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16510 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16511 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16512 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16513 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16514 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16515 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16516 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16517 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16518 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16519 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16520 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16521 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16522 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16523 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16524 case X86ISD::HADD: return "X86ISD::HADD";
16525 case X86ISD::HSUB: return "X86ISD::HSUB";
16526 case X86ISD::FHADD: return "X86ISD::FHADD";
16527 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16528 case X86ISD::UMAX: return "X86ISD::UMAX";
16529 case X86ISD::UMIN: return "X86ISD::UMIN";
16530 case X86ISD::SMAX: return "X86ISD::SMAX";
16531 case X86ISD::SMIN: return "X86ISD::SMIN";
16532 case X86ISD::FMAX: return "X86ISD::FMAX";
16533 case X86ISD::FMIN: return "X86ISD::FMIN";
16534 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16535 case X86ISD::FMINC: return "X86ISD::FMINC";
16536 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16537 case X86ISD::FRCP: return "X86ISD::FRCP";
16538 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16539 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16540 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16541 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16542 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16543 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16544 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16545 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16546 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16547 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16548 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16549 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16550 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16551 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16552 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16553 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16554 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16555 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16556 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16557 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16558 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16559 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16560 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16561 case X86ISD::VSHL: return "X86ISD::VSHL";
16562 case X86ISD::VSRL: return "X86ISD::VSRL";
16563 case X86ISD::VSRA: return "X86ISD::VSRA";
16564 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16565 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16566 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16567 case X86ISD::CMPP: return "X86ISD::CMPP";
16568 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16569 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16570 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16571 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16572 case X86ISD::ADD: return "X86ISD::ADD";
16573 case X86ISD::SUB: return "X86ISD::SUB";
16574 case X86ISD::ADC: return "X86ISD::ADC";
16575 case X86ISD::SBB: return "X86ISD::SBB";
16576 case X86ISD::SMUL: return "X86ISD::SMUL";
16577 case X86ISD::UMUL: return "X86ISD::UMUL";
16578 case X86ISD::INC: return "X86ISD::INC";
16579 case X86ISD::DEC: return "X86ISD::DEC";
16580 case X86ISD::OR: return "X86ISD::OR";
16581 case X86ISD::XOR: return "X86ISD::XOR";
16582 case X86ISD::AND: return "X86ISD::AND";
16583 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16584 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16585 case X86ISD::PTEST: return "X86ISD::PTEST";
16586 case X86ISD::TESTP: return "X86ISD::TESTP";
16587 case X86ISD::TESTM: return "X86ISD::TESTM";
16588 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16589 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16590 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16591 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16592 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16593 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16594 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16595 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16596 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16597 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16598 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16599 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16600 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16601 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16602 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16603 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16604 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16605 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16606 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16607 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16608 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16609 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16610 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16611 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16612 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16613 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16614 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16615 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16616 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16617 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16618 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16619 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16620 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16621 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16622 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16623 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16624 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16625 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16626 case X86ISD::SAHF: return "X86ISD::SAHF";
16627 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16628 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16629 case X86ISD::FMADD: return "X86ISD::FMADD";
16630 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16631 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16632 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16633 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16634 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16635 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16636 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16637 case X86ISD::XTEST: return "X86ISD::XTEST";
16641 // isLegalAddressingMode - Return true if the addressing mode represented
16642 // by AM is legal for this target, for a load/store of the specified type.
16643 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16645 // X86 supports extremely general addressing modes.
16646 CodeModel::Model M = getTargetMachine().getCodeModel();
16647 Reloc::Model R = getTargetMachine().getRelocationModel();
16649 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16650 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16655 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16657 // If a reference to this global requires an extra load, we can't fold it.
16658 if (isGlobalStubReference(GVFlags))
16661 // If BaseGV requires a register for the PIC base, we cannot also have a
16662 // BaseReg specified.
16663 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16666 // If lower 4G is not available, then we must use rip-relative addressing.
16667 if ((M != CodeModel::Small || R != Reloc::Static) &&
16668 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16672 switch (AM.Scale) {
16678 // These scales always work.
16683 // These scales are formed with basereg+scalereg. Only accept if there is
16688 default: // Other stuff never works.
16695 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16696 unsigned Bits = Ty->getScalarSizeInBits();
16698 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16699 // particularly cheaper than those without.
16703 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16704 // variable shifts just as cheap as scalar ones.
16705 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16708 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16709 // fully general vector.
16713 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16714 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16716 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16717 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16718 return NumBits1 > NumBits2;
16721 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16722 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16725 if (!isTypeLegal(EVT::getEVT(Ty1)))
16728 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16730 // Assuming the caller doesn't have a zeroext or signext return parameter,
16731 // truncation all the way down to i1 is valid.
16735 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16736 return isInt<32>(Imm);
16739 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16740 // Can also use sub to handle negated immediates.
16741 return isInt<32>(Imm);
16744 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16745 if (!VT1.isInteger() || !VT2.isInteger())
16747 unsigned NumBits1 = VT1.getSizeInBits();
16748 unsigned NumBits2 = VT2.getSizeInBits();
16749 return NumBits1 > NumBits2;
16752 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16753 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16754 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16757 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16758 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16759 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16762 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16763 EVT VT1 = Val.getValueType();
16764 if (isZExtFree(VT1, VT2))
16767 if (Val.getOpcode() != ISD::LOAD)
16770 if (!VT1.isSimple() || !VT1.isInteger() ||
16771 !VT2.isSimple() || !VT2.isInteger())
16774 switch (VT1.getSimpleVT().SimpleTy) {
16779 // X86 has 8, 16, and 32-bit zero-extending loads.
16787 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16788 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16791 VT = VT.getScalarType();
16793 if (!VT.isSimple())
16796 switch (VT.getSimpleVT().SimpleTy) {
16807 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16808 // i16 instructions are longer (0x66 prefix) and potentially slower.
16809 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16812 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16813 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16814 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16815 /// are assumed to be legal.
16817 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16819 if (!VT.isSimple())
16822 MVT SVT = VT.getSimpleVT();
16824 // Very little shuffling can be done for 64-bit vectors right now.
16825 if (VT.getSizeInBits() == 64)
16828 // If this is a single-input shuffle with no 128 bit lane crossings we can
16829 // lower it into pshufb.
16830 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16831 (SVT.is256BitVector() && Subtarget->hasInt256())) {
16832 bool isLegal = true;
16833 for (unsigned I = 0, E = M.size(); I != E; ++I) {
16834 if (M[I] >= (int)SVT.getVectorNumElements() ||
16835 ShuffleCrosses128bitLane(SVT, I, M[I])) {
16844 // FIXME: blends, shifts.
16845 return (SVT.getVectorNumElements() == 2 ||
16846 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16847 isMOVLMask(M, SVT) ||
16848 isSHUFPMask(M, SVT) ||
16849 isPSHUFDMask(M, SVT) ||
16850 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16851 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16852 isPALIGNRMask(M, SVT, Subtarget) ||
16853 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16854 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16855 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16856 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16857 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16861 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16863 if (!VT.isSimple())
16866 MVT SVT = VT.getSimpleVT();
16867 unsigned NumElts = SVT.getVectorNumElements();
16868 // FIXME: This collection of masks seems suspect.
16871 if (NumElts == 4 && SVT.is128BitVector()) {
16872 return (isMOVLMask(Mask, SVT) ||
16873 isCommutedMOVLMask(Mask, SVT, true) ||
16874 isSHUFPMask(Mask, SVT) ||
16875 isSHUFPMask(Mask, SVT, /* Commuted */ true));
16880 //===----------------------------------------------------------------------===//
16881 // X86 Scheduler Hooks
16882 //===----------------------------------------------------------------------===//
16884 /// Utility function to emit xbegin specifying the start of an RTM region.
16885 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16886 const TargetInstrInfo *TII) {
16887 DebugLoc DL = MI->getDebugLoc();
16889 const BasicBlock *BB = MBB->getBasicBlock();
16890 MachineFunction::iterator I = MBB;
16893 // For the v = xbegin(), we generate
16904 MachineBasicBlock *thisMBB = MBB;
16905 MachineFunction *MF = MBB->getParent();
16906 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16907 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16908 MF->insert(I, mainMBB);
16909 MF->insert(I, sinkMBB);
16911 // Transfer the remainder of BB and its successor edges to sinkMBB.
16912 sinkMBB->splice(sinkMBB->begin(), MBB,
16913 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16914 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16918 // # fallthrough to mainMBB
16919 // # abortion to sinkMBB
16920 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16921 thisMBB->addSuccessor(mainMBB);
16922 thisMBB->addSuccessor(sinkMBB);
16926 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16927 mainMBB->addSuccessor(sinkMBB);
16930 // EAX is live into the sinkMBB
16931 sinkMBB->addLiveIn(X86::EAX);
16932 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16933 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16936 MI->eraseFromParent();
16940 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16941 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16942 // in the .td file.
16943 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16944 const TargetInstrInfo *TII) {
16946 switch (MI->getOpcode()) {
16947 default: llvm_unreachable("illegal opcode!");
16948 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16949 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16950 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16951 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16952 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16953 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16954 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16955 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16958 DebugLoc dl = MI->getDebugLoc();
16959 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16961 unsigned NumArgs = MI->getNumOperands();
16962 for (unsigned i = 1; i < NumArgs; ++i) {
16963 MachineOperand &Op = MI->getOperand(i);
16964 if (!(Op.isReg() && Op.isImplicit()))
16965 MIB.addOperand(Op);
16967 if (MI->hasOneMemOperand())
16968 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16970 BuildMI(*BB, MI, dl,
16971 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16972 .addReg(X86::XMM0);
16974 MI->eraseFromParent();
16978 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16979 // defs in an instruction pattern
16980 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16981 const TargetInstrInfo *TII) {
16983 switch (MI->getOpcode()) {
16984 default: llvm_unreachable("illegal opcode!");
16985 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16986 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16987 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16988 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16989 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16990 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16991 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16992 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16995 DebugLoc dl = MI->getDebugLoc();
16996 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16998 unsigned NumArgs = MI->getNumOperands(); // remove the results
16999 for (unsigned i = 1; i < NumArgs; ++i) {
17000 MachineOperand &Op = MI->getOperand(i);
17001 if (!(Op.isReg() && Op.isImplicit()))
17002 MIB.addOperand(Op);
17004 if (MI->hasOneMemOperand())
17005 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17007 BuildMI(*BB, MI, dl,
17008 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17011 MI->eraseFromParent();
17015 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17016 const TargetInstrInfo *TII,
17017 const X86Subtarget* Subtarget) {
17018 DebugLoc dl = MI->getDebugLoc();
17020 // Address into RAX/EAX, other two args into ECX, EDX.
17021 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17022 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17023 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17024 for (int i = 0; i < X86::AddrNumOperands; ++i)
17025 MIB.addOperand(MI->getOperand(i));
17027 unsigned ValOps = X86::AddrNumOperands;
17028 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17029 .addReg(MI->getOperand(ValOps).getReg());
17030 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17031 .addReg(MI->getOperand(ValOps+1).getReg());
17033 // The instruction doesn't actually take any operands though.
17034 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17036 MI->eraseFromParent(); // The pseudo is gone now.
17040 MachineBasicBlock *
17041 X86TargetLowering::EmitVAARG64WithCustomInserter(
17043 MachineBasicBlock *MBB) const {
17044 // Emit va_arg instruction on X86-64.
17046 // Operands to this pseudo-instruction:
17047 // 0 ) Output : destination address (reg)
17048 // 1-5) Input : va_list address (addr, i64mem)
17049 // 6 ) ArgSize : Size (in bytes) of vararg type
17050 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17051 // 8 ) Align : Alignment of type
17052 // 9 ) EFLAGS (implicit-def)
17054 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17055 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17057 unsigned DestReg = MI->getOperand(0).getReg();
17058 MachineOperand &Base = MI->getOperand(1);
17059 MachineOperand &Scale = MI->getOperand(2);
17060 MachineOperand &Index = MI->getOperand(3);
17061 MachineOperand &Disp = MI->getOperand(4);
17062 MachineOperand &Segment = MI->getOperand(5);
17063 unsigned ArgSize = MI->getOperand(6).getImm();
17064 unsigned ArgMode = MI->getOperand(7).getImm();
17065 unsigned Align = MI->getOperand(8).getImm();
17067 // Memory Reference
17068 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17069 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17070 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17072 // Machine Information
17073 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17074 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17075 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17076 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17077 DebugLoc DL = MI->getDebugLoc();
17079 // struct va_list {
17082 // i64 overflow_area (address)
17083 // i64 reg_save_area (address)
17085 // sizeof(va_list) = 24
17086 // alignment(va_list) = 8
17088 unsigned TotalNumIntRegs = 6;
17089 unsigned TotalNumXMMRegs = 8;
17090 bool UseGPOffset = (ArgMode == 1);
17091 bool UseFPOffset = (ArgMode == 2);
17092 unsigned MaxOffset = TotalNumIntRegs * 8 +
17093 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17095 /* Align ArgSize to a multiple of 8 */
17096 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17097 bool NeedsAlign = (Align > 8);
17099 MachineBasicBlock *thisMBB = MBB;
17100 MachineBasicBlock *overflowMBB;
17101 MachineBasicBlock *offsetMBB;
17102 MachineBasicBlock *endMBB;
17104 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17105 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17106 unsigned OffsetReg = 0;
17108 if (!UseGPOffset && !UseFPOffset) {
17109 // If we only pull from the overflow region, we don't create a branch.
17110 // We don't need to alter control flow.
17111 OffsetDestReg = 0; // unused
17112 OverflowDestReg = DestReg;
17114 offsetMBB = nullptr;
17115 overflowMBB = thisMBB;
17118 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17119 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17120 // If not, pull from overflow_area. (branch to overflowMBB)
17125 // offsetMBB overflowMBB
17130 // Registers for the PHI in endMBB
17131 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17132 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17134 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17135 MachineFunction *MF = MBB->getParent();
17136 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17137 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17138 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17140 MachineFunction::iterator MBBIter = MBB;
17143 // Insert the new basic blocks
17144 MF->insert(MBBIter, offsetMBB);
17145 MF->insert(MBBIter, overflowMBB);
17146 MF->insert(MBBIter, endMBB);
17148 // Transfer the remainder of MBB and its successor edges to endMBB.
17149 endMBB->splice(endMBB->begin(), thisMBB,
17150 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17151 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17153 // Make offsetMBB and overflowMBB successors of thisMBB
17154 thisMBB->addSuccessor(offsetMBB);
17155 thisMBB->addSuccessor(overflowMBB);
17157 // endMBB is a successor of both offsetMBB and overflowMBB
17158 offsetMBB->addSuccessor(endMBB);
17159 overflowMBB->addSuccessor(endMBB);
17161 // Load the offset value into a register
17162 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17163 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17167 .addDisp(Disp, UseFPOffset ? 4 : 0)
17168 .addOperand(Segment)
17169 .setMemRefs(MMOBegin, MMOEnd);
17171 // Check if there is enough room left to pull this argument.
17172 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17174 .addImm(MaxOffset + 8 - ArgSizeA8);
17176 // Branch to "overflowMBB" if offset >= max
17177 // Fall through to "offsetMBB" otherwise
17178 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17179 .addMBB(overflowMBB);
17182 // In offsetMBB, emit code to use the reg_save_area.
17184 assert(OffsetReg != 0);
17186 // Read the reg_save_area address.
17187 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17188 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17193 .addOperand(Segment)
17194 .setMemRefs(MMOBegin, MMOEnd);
17196 // Zero-extend the offset
17197 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17198 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17201 .addImm(X86::sub_32bit);
17203 // Add the offset to the reg_save_area to get the final address.
17204 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17205 .addReg(OffsetReg64)
17206 .addReg(RegSaveReg);
17208 // Compute the offset for the next argument
17209 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17210 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17212 .addImm(UseFPOffset ? 16 : 8);
17214 // Store it back into the va_list.
17215 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17219 .addDisp(Disp, UseFPOffset ? 4 : 0)
17220 .addOperand(Segment)
17221 .addReg(NextOffsetReg)
17222 .setMemRefs(MMOBegin, MMOEnd);
17225 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17230 // Emit code to use overflow area
17233 // Load the overflow_area address into a register.
17234 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17235 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17240 .addOperand(Segment)
17241 .setMemRefs(MMOBegin, MMOEnd);
17243 // If we need to align it, do so. Otherwise, just copy the address
17244 // to OverflowDestReg.
17246 // Align the overflow address
17247 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17248 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17250 // aligned_addr = (addr + (align-1)) & ~(align-1)
17251 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17252 .addReg(OverflowAddrReg)
17255 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17257 .addImm(~(uint64_t)(Align-1));
17259 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17260 .addReg(OverflowAddrReg);
17263 // Compute the next overflow address after this argument.
17264 // (the overflow address should be kept 8-byte aligned)
17265 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17266 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17267 .addReg(OverflowDestReg)
17268 .addImm(ArgSizeA8);
17270 // Store the new overflow address.
17271 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17276 .addOperand(Segment)
17277 .addReg(NextAddrReg)
17278 .setMemRefs(MMOBegin, MMOEnd);
17280 // If we branched, emit the PHI to the front of endMBB.
17282 BuildMI(*endMBB, endMBB->begin(), DL,
17283 TII->get(X86::PHI), DestReg)
17284 .addReg(OffsetDestReg).addMBB(offsetMBB)
17285 .addReg(OverflowDestReg).addMBB(overflowMBB);
17288 // Erase the pseudo instruction
17289 MI->eraseFromParent();
17294 MachineBasicBlock *
17295 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17297 MachineBasicBlock *MBB) const {
17298 // Emit code to save XMM registers to the stack. The ABI says that the
17299 // number of registers to save is given in %al, so it's theoretically
17300 // possible to do an indirect jump trick to avoid saving all of them,
17301 // however this code takes a simpler approach and just executes all
17302 // of the stores if %al is non-zero. It's less code, and it's probably
17303 // easier on the hardware branch predictor, and stores aren't all that
17304 // expensive anyway.
17306 // Create the new basic blocks. One block contains all the XMM stores,
17307 // and one block is the final destination regardless of whether any
17308 // stores were performed.
17309 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17310 MachineFunction *F = MBB->getParent();
17311 MachineFunction::iterator MBBIter = MBB;
17313 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17314 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17315 F->insert(MBBIter, XMMSaveMBB);
17316 F->insert(MBBIter, EndMBB);
17318 // Transfer the remainder of MBB and its successor edges to EndMBB.
17319 EndMBB->splice(EndMBB->begin(), MBB,
17320 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17321 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17323 // The original block will now fall through to the XMM save block.
17324 MBB->addSuccessor(XMMSaveMBB);
17325 // The XMMSaveMBB will fall through to the end block.
17326 XMMSaveMBB->addSuccessor(EndMBB);
17328 // Now add the instructions.
17329 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17330 DebugLoc DL = MI->getDebugLoc();
17332 unsigned CountReg = MI->getOperand(0).getReg();
17333 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17334 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17336 if (!Subtarget->isTargetWin64()) {
17337 // If %al is 0, branch around the XMM save block.
17338 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17339 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17340 MBB->addSuccessor(EndMBB);
17343 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17344 // that was just emitted, but clearly shouldn't be "saved".
17345 assert((MI->getNumOperands() <= 3 ||
17346 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17347 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17348 && "Expected last argument to be EFLAGS");
17349 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17350 // In the XMM save block, save all the XMM argument registers.
17351 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17352 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17353 MachineMemOperand *MMO =
17354 F->getMachineMemOperand(
17355 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17356 MachineMemOperand::MOStore,
17357 /*Size=*/16, /*Align=*/16);
17358 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17359 .addFrameIndex(RegSaveFrameIndex)
17360 .addImm(/*Scale=*/1)
17361 .addReg(/*IndexReg=*/0)
17362 .addImm(/*Disp=*/Offset)
17363 .addReg(/*Segment=*/0)
17364 .addReg(MI->getOperand(i).getReg())
17365 .addMemOperand(MMO);
17368 MI->eraseFromParent(); // The pseudo instruction is gone now.
17373 // The EFLAGS operand of SelectItr might be missing a kill marker
17374 // because there were multiple uses of EFLAGS, and ISel didn't know
17375 // which to mark. Figure out whether SelectItr should have had a
17376 // kill marker, and set it if it should. Returns the correct kill
17378 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17379 MachineBasicBlock* BB,
17380 const TargetRegisterInfo* TRI) {
17381 // Scan forward through BB for a use/def of EFLAGS.
17382 MachineBasicBlock::iterator miI(std::next(SelectItr));
17383 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17384 const MachineInstr& mi = *miI;
17385 if (mi.readsRegister(X86::EFLAGS))
17387 if (mi.definesRegister(X86::EFLAGS))
17388 break; // Should have kill-flag - update below.
17391 // If we hit the end of the block, check whether EFLAGS is live into a
17393 if (miI == BB->end()) {
17394 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17395 sEnd = BB->succ_end();
17396 sItr != sEnd; ++sItr) {
17397 MachineBasicBlock* succ = *sItr;
17398 if (succ->isLiveIn(X86::EFLAGS))
17403 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17404 // out. SelectMI should have a kill flag on EFLAGS.
17405 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17409 MachineBasicBlock *
17410 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17411 MachineBasicBlock *BB) const {
17412 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17413 DebugLoc DL = MI->getDebugLoc();
17415 // To "insert" a SELECT_CC instruction, we actually have to insert the
17416 // diamond control-flow pattern. The incoming instruction knows the
17417 // destination vreg to set, the condition code register to branch on, the
17418 // true/false values to select between, and a branch opcode to use.
17419 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17420 MachineFunction::iterator It = BB;
17426 // cmpTY ccX, r1, r2
17428 // fallthrough --> copy0MBB
17429 MachineBasicBlock *thisMBB = BB;
17430 MachineFunction *F = BB->getParent();
17431 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17432 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17433 F->insert(It, copy0MBB);
17434 F->insert(It, sinkMBB);
17436 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17437 // live into the sink and copy blocks.
17438 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17439 if (!MI->killsRegister(X86::EFLAGS) &&
17440 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17441 copy0MBB->addLiveIn(X86::EFLAGS);
17442 sinkMBB->addLiveIn(X86::EFLAGS);
17445 // Transfer the remainder of BB and its successor edges to sinkMBB.
17446 sinkMBB->splice(sinkMBB->begin(), BB,
17447 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17448 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17450 // Add the true and fallthrough blocks as its successors.
17451 BB->addSuccessor(copy0MBB);
17452 BB->addSuccessor(sinkMBB);
17454 // Create the conditional branch instruction.
17456 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17457 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17460 // %FalseValue = ...
17461 // # fallthrough to sinkMBB
17462 copy0MBB->addSuccessor(sinkMBB);
17465 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17467 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17468 TII->get(X86::PHI), MI->getOperand(0).getReg())
17469 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17470 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17472 MI->eraseFromParent(); // The pseudo instruction is gone now.
17476 MachineBasicBlock *
17477 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17478 bool Is64Bit) const {
17479 MachineFunction *MF = BB->getParent();
17480 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17481 DebugLoc DL = MI->getDebugLoc();
17482 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17484 assert(MF->shouldSplitStack());
17486 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17487 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17490 // ... [Till the alloca]
17491 // If stacklet is not large enough, jump to mallocMBB
17494 // Allocate by subtracting from RSP
17495 // Jump to continueMBB
17498 // Allocate by call to runtime
17502 // [rest of original BB]
17505 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17506 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17507 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17509 MachineRegisterInfo &MRI = MF->getRegInfo();
17510 const TargetRegisterClass *AddrRegClass =
17511 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17513 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17514 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17515 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17516 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17517 sizeVReg = MI->getOperand(1).getReg(),
17518 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17520 MachineFunction::iterator MBBIter = BB;
17523 MF->insert(MBBIter, bumpMBB);
17524 MF->insert(MBBIter, mallocMBB);
17525 MF->insert(MBBIter, continueMBB);
17527 continueMBB->splice(continueMBB->begin(), BB,
17528 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17529 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17531 // Add code to the main basic block to check if the stack limit has been hit,
17532 // and if so, jump to mallocMBB otherwise to bumpMBB.
17533 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17534 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17535 .addReg(tmpSPVReg).addReg(sizeVReg);
17536 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17537 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17538 .addReg(SPLimitVReg);
17539 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17541 // bumpMBB simply decreases the stack pointer, since we know the current
17542 // stacklet has enough space.
17543 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17544 .addReg(SPLimitVReg);
17545 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17546 .addReg(SPLimitVReg);
17547 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17549 // Calls into a routine in libgcc to allocate more space from the heap.
17550 const uint32_t *RegMask =
17551 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17553 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17555 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17556 .addExternalSymbol("__morestack_allocate_stack_space")
17557 .addRegMask(RegMask)
17558 .addReg(X86::RDI, RegState::Implicit)
17559 .addReg(X86::RAX, RegState::ImplicitDefine);
17561 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17563 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17564 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17565 .addExternalSymbol("__morestack_allocate_stack_space")
17566 .addRegMask(RegMask)
17567 .addReg(X86::EAX, RegState::ImplicitDefine);
17571 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17574 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17575 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17576 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17578 // Set up the CFG correctly.
17579 BB->addSuccessor(bumpMBB);
17580 BB->addSuccessor(mallocMBB);
17581 mallocMBB->addSuccessor(continueMBB);
17582 bumpMBB->addSuccessor(continueMBB);
17584 // Take care of the PHI nodes.
17585 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17586 MI->getOperand(0).getReg())
17587 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17588 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17590 // Delete the original pseudo instruction.
17591 MI->eraseFromParent();
17594 return continueMBB;
17597 MachineBasicBlock *
17598 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17599 MachineBasicBlock *BB) const {
17600 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17601 DebugLoc DL = MI->getDebugLoc();
17603 assert(!Subtarget->isTargetMacho());
17605 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17606 // non-trivial part is impdef of ESP.
17608 if (Subtarget->isTargetWin64()) {
17609 if (Subtarget->isTargetCygMing()) {
17610 // ___chkstk(Mingw64):
17611 // Clobbers R10, R11, RAX and EFLAGS.
17613 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17614 .addExternalSymbol("___chkstk")
17615 .addReg(X86::RAX, RegState::Implicit)
17616 .addReg(X86::RSP, RegState::Implicit)
17617 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17618 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17619 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17621 // __chkstk(MSVCRT): does not update stack pointer.
17622 // Clobbers R10, R11 and EFLAGS.
17623 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17624 .addExternalSymbol("__chkstk")
17625 .addReg(X86::RAX, RegState::Implicit)
17626 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17627 // RAX has the offset to be subtracted from RSP.
17628 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17633 const char *StackProbeSymbol =
17634 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17636 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17637 .addExternalSymbol(StackProbeSymbol)
17638 .addReg(X86::EAX, RegState::Implicit)
17639 .addReg(X86::ESP, RegState::Implicit)
17640 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17641 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17642 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17645 MI->eraseFromParent(); // The pseudo instruction is gone now.
17649 MachineBasicBlock *
17650 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17651 MachineBasicBlock *BB) const {
17652 // This is pretty easy. We're taking the value that we received from
17653 // our load from the relocation, sticking it in either RDI (x86-64)
17654 // or EAX and doing an indirect call. The return value will then
17655 // be in the normal return register.
17656 MachineFunction *F = BB->getParent();
17657 const X86InstrInfo *TII
17658 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17659 DebugLoc DL = MI->getDebugLoc();
17661 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17662 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17664 // Get a register mask for the lowered call.
17665 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17666 // proper register mask.
17667 const uint32_t *RegMask =
17668 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17669 if (Subtarget->is64Bit()) {
17670 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17671 TII->get(X86::MOV64rm), X86::RDI)
17673 .addImm(0).addReg(0)
17674 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17675 MI->getOperand(3).getTargetFlags())
17677 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17678 addDirectMem(MIB, X86::RDI);
17679 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17680 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17681 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17682 TII->get(X86::MOV32rm), X86::EAX)
17684 .addImm(0).addReg(0)
17685 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17686 MI->getOperand(3).getTargetFlags())
17688 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17689 addDirectMem(MIB, X86::EAX);
17690 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17692 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17693 TII->get(X86::MOV32rm), X86::EAX)
17694 .addReg(TII->getGlobalBaseReg(F))
17695 .addImm(0).addReg(0)
17696 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17697 MI->getOperand(3).getTargetFlags())
17699 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17700 addDirectMem(MIB, X86::EAX);
17701 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17704 MI->eraseFromParent(); // The pseudo instruction is gone now.
17708 MachineBasicBlock *
17709 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17710 MachineBasicBlock *MBB) const {
17711 DebugLoc DL = MI->getDebugLoc();
17712 MachineFunction *MF = MBB->getParent();
17713 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17714 MachineRegisterInfo &MRI = MF->getRegInfo();
17716 const BasicBlock *BB = MBB->getBasicBlock();
17717 MachineFunction::iterator I = MBB;
17720 // Memory Reference
17721 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17722 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17725 unsigned MemOpndSlot = 0;
17727 unsigned CurOp = 0;
17729 DstReg = MI->getOperand(CurOp++).getReg();
17730 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17731 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17732 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17733 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17735 MemOpndSlot = CurOp;
17737 MVT PVT = getPointerTy();
17738 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17739 "Invalid Pointer Size!");
17741 // For v = setjmp(buf), we generate
17744 // buf[LabelOffset] = restoreMBB
17745 // SjLjSetup restoreMBB
17751 // v = phi(main, restore)
17756 MachineBasicBlock *thisMBB = MBB;
17757 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17758 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17759 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17760 MF->insert(I, mainMBB);
17761 MF->insert(I, sinkMBB);
17762 MF->push_back(restoreMBB);
17764 MachineInstrBuilder MIB;
17766 // Transfer the remainder of BB and its successor edges to sinkMBB.
17767 sinkMBB->splice(sinkMBB->begin(), MBB,
17768 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17769 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17772 unsigned PtrStoreOpc = 0;
17773 unsigned LabelReg = 0;
17774 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17775 Reloc::Model RM = MF->getTarget().getRelocationModel();
17776 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17777 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17779 // Prepare IP either in reg or imm.
17780 if (!UseImmLabel) {
17781 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17782 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17783 LabelReg = MRI.createVirtualRegister(PtrRC);
17784 if (Subtarget->is64Bit()) {
17785 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17789 .addMBB(restoreMBB)
17792 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17793 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17794 .addReg(XII->getGlobalBaseReg(MF))
17797 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17801 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17803 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17804 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17805 if (i == X86::AddrDisp)
17806 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17808 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17811 MIB.addReg(LabelReg);
17813 MIB.addMBB(restoreMBB);
17814 MIB.setMemRefs(MMOBegin, MMOEnd);
17816 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17817 .addMBB(restoreMBB);
17819 const X86RegisterInfo *RegInfo =
17820 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17821 MIB.addRegMask(RegInfo->getNoPreservedMask());
17822 thisMBB->addSuccessor(mainMBB);
17823 thisMBB->addSuccessor(restoreMBB);
17827 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17828 mainMBB->addSuccessor(sinkMBB);
17831 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17832 TII->get(X86::PHI), DstReg)
17833 .addReg(mainDstReg).addMBB(mainMBB)
17834 .addReg(restoreDstReg).addMBB(restoreMBB);
17837 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17838 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17839 restoreMBB->addSuccessor(sinkMBB);
17841 MI->eraseFromParent();
17845 MachineBasicBlock *
17846 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17847 MachineBasicBlock *MBB) const {
17848 DebugLoc DL = MI->getDebugLoc();
17849 MachineFunction *MF = MBB->getParent();
17850 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17851 MachineRegisterInfo &MRI = MF->getRegInfo();
17853 // Memory Reference
17854 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17855 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17857 MVT PVT = getPointerTy();
17858 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17859 "Invalid Pointer Size!");
17861 const TargetRegisterClass *RC =
17862 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17863 unsigned Tmp = MRI.createVirtualRegister(RC);
17864 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17865 const X86RegisterInfo *RegInfo =
17866 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17867 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17868 unsigned SP = RegInfo->getStackRegister();
17870 MachineInstrBuilder MIB;
17872 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17873 const int64_t SPOffset = 2 * PVT.getStoreSize();
17875 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17876 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17879 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17880 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17881 MIB.addOperand(MI->getOperand(i));
17882 MIB.setMemRefs(MMOBegin, MMOEnd);
17884 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17885 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17886 if (i == X86::AddrDisp)
17887 MIB.addDisp(MI->getOperand(i), LabelOffset);
17889 MIB.addOperand(MI->getOperand(i));
17891 MIB.setMemRefs(MMOBegin, MMOEnd);
17893 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17894 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17895 if (i == X86::AddrDisp)
17896 MIB.addDisp(MI->getOperand(i), SPOffset);
17898 MIB.addOperand(MI->getOperand(i));
17900 MIB.setMemRefs(MMOBegin, MMOEnd);
17902 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17904 MI->eraseFromParent();
17908 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17909 // accumulator loops. Writing back to the accumulator allows the coalescer
17910 // to remove extra copies in the loop.
17911 MachineBasicBlock *
17912 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17913 MachineBasicBlock *MBB) const {
17914 MachineOperand &AddendOp = MI->getOperand(3);
17916 // Bail out early if the addend isn't a register - we can't switch these.
17917 if (!AddendOp.isReg())
17920 MachineFunction &MF = *MBB->getParent();
17921 MachineRegisterInfo &MRI = MF.getRegInfo();
17923 // Check whether the addend is defined by a PHI:
17924 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17925 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17926 if (!AddendDef.isPHI())
17929 // Look for the following pattern:
17931 // %addend = phi [%entry, 0], [%loop, %result]
17933 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17937 // %addend = phi [%entry, 0], [%loop, %result]
17939 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17941 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17942 assert(AddendDef.getOperand(i).isReg());
17943 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17944 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17945 if (&PHISrcInst == MI) {
17946 // Found a matching instruction.
17947 unsigned NewFMAOpc = 0;
17948 switch (MI->getOpcode()) {
17949 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17950 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17951 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17952 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17953 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17954 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17955 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17956 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17957 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17958 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17959 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17960 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17961 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17962 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17963 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17964 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17965 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17966 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17967 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17968 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17969 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17970 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17971 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17972 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17973 default: llvm_unreachable("Unrecognized FMA variant.");
17976 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17977 MachineInstrBuilder MIB =
17978 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17979 .addOperand(MI->getOperand(0))
17980 .addOperand(MI->getOperand(3))
17981 .addOperand(MI->getOperand(2))
17982 .addOperand(MI->getOperand(1));
17983 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17984 MI->eraseFromParent();
17991 MachineBasicBlock *
17992 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17993 MachineBasicBlock *BB) const {
17994 switch (MI->getOpcode()) {
17995 default: llvm_unreachable("Unexpected instr type to insert");
17996 case X86::TAILJMPd64:
17997 case X86::TAILJMPr64:
17998 case X86::TAILJMPm64:
17999 llvm_unreachable("TAILJMP64 would not be touched here.");
18000 case X86::TCRETURNdi64:
18001 case X86::TCRETURNri64:
18002 case X86::TCRETURNmi64:
18004 case X86::WIN_ALLOCA:
18005 return EmitLoweredWinAlloca(MI, BB);
18006 case X86::SEG_ALLOCA_32:
18007 return EmitLoweredSegAlloca(MI, BB, false);
18008 case X86::SEG_ALLOCA_64:
18009 return EmitLoweredSegAlloca(MI, BB, true);
18010 case X86::TLSCall_32:
18011 case X86::TLSCall_64:
18012 return EmitLoweredTLSCall(MI, BB);
18013 case X86::CMOV_GR8:
18014 case X86::CMOV_FR32:
18015 case X86::CMOV_FR64:
18016 case X86::CMOV_V4F32:
18017 case X86::CMOV_V2F64:
18018 case X86::CMOV_V2I64:
18019 case X86::CMOV_V8F32:
18020 case X86::CMOV_V4F64:
18021 case X86::CMOV_V4I64:
18022 case X86::CMOV_V16F32:
18023 case X86::CMOV_V8F64:
18024 case X86::CMOV_V8I64:
18025 case X86::CMOV_GR16:
18026 case X86::CMOV_GR32:
18027 case X86::CMOV_RFP32:
18028 case X86::CMOV_RFP64:
18029 case X86::CMOV_RFP80:
18030 return EmitLoweredSelect(MI, BB);
18032 case X86::FP32_TO_INT16_IN_MEM:
18033 case X86::FP32_TO_INT32_IN_MEM:
18034 case X86::FP32_TO_INT64_IN_MEM:
18035 case X86::FP64_TO_INT16_IN_MEM:
18036 case X86::FP64_TO_INT32_IN_MEM:
18037 case X86::FP64_TO_INT64_IN_MEM:
18038 case X86::FP80_TO_INT16_IN_MEM:
18039 case X86::FP80_TO_INT32_IN_MEM:
18040 case X86::FP80_TO_INT64_IN_MEM: {
18041 MachineFunction *F = BB->getParent();
18042 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18043 DebugLoc DL = MI->getDebugLoc();
18045 // Change the floating point control register to use "round towards zero"
18046 // mode when truncating to an integer value.
18047 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18048 addFrameReference(BuildMI(*BB, MI, DL,
18049 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18051 // Load the old value of the high byte of the control word...
18053 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18054 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18057 // Set the high part to be round to zero...
18058 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18061 // Reload the modified control word now...
18062 addFrameReference(BuildMI(*BB, MI, DL,
18063 TII->get(X86::FLDCW16m)), CWFrameIdx);
18065 // Restore the memory image of control word to original value
18066 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18069 // Get the X86 opcode to use.
18071 switch (MI->getOpcode()) {
18072 default: llvm_unreachable("illegal opcode!");
18073 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18074 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18075 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18076 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18077 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18078 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18079 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18080 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18081 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18085 MachineOperand &Op = MI->getOperand(0);
18087 AM.BaseType = X86AddressMode::RegBase;
18088 AM.Base.Reg = Op.getReg();
18090 AM.BaseType = X86AddressMode::FrameIndexBase;
18091 AM.Base.FrameIndex = Op.getIndex();
18093 Op = MI->getOperand(1);
18095 AM.Scale = Op.getImm();
18096 Op = MI->getOperand(2);
18098 AM.IndexReg = Op.getImm();
18099 Op = MI->getOperand(3);
18100 if (Op.isGlobal()) {
18101 AM.GV = Op.getGlobal();
18103 AM.Disp = Op.getImm();
18105 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18106 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18108 // Reload the original control word now.
18109 addFrameReference(BuildMI(*BB, MI, DL,
18110 TII->get(X86::FLDCW16m)), CWFrameIdx);
18112 MI->eraseFromParent(); // The pseudo instruction is gone now.
18115 // String/text processing lowering.
18116 case X86::PCMPISTRM128REG:
18117 case X86::VPCMPISTRM128REG:
18118 case X86::PCMPISTRM128MEM:
18119 case X86::VPCMPISTRM128MEM:
18120 case X86::PCMPESTRM128REG:
18121 case X86::VPCMPESTRM128REG:
18122 case X86::PCMPESTRM128MEM:
18123 case X86::VPCMPESTRM128MEM:
18124 assert(Subtarget->hasSSE42() &&
18125 "Target must have SSE4.2 or AVX features enabled");
18126 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18128 // String/text processing lowering.
18129 case X86::PCMPISTRIREG:
18130 case X86::VPCMPISTRIREG:
18131 case X86::PCMPISTRIMEM:
18132 case X86::VPCMPISTRIMEM:
18133 case X86::PCMPESTRIREG:
18134 case X86::VPCMPESTRIREG:
18135 case X86::PCMPESTRIMEM:
18136 case X86::VPCMPESTRIMEM:
18137 assert(Subtarget->hasSSE42() &&
18138 "Target must have SSE4.2 or AVX features enabled");
18139 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18141 // Thread synchronization.
18143 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18147 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18149 case X86::VASTART_SAVE_XMM_REGS:
18150 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18152 case X86::VAARG_64:
18153 return EmitVAARG64WithCustomInserter(MI, BB);
18155 case X86::EH_SjLj_SetJmp32:
18156 case X86::EH_SjLj_SetJmp64:
18157 return emitEHSjLjSetJmp(MI, BB);
18159 case X86::EH_SjLj_LongJmp32:
18160 case X86::EH_SjLj_LongJmp64:
18161 return emitEHSjLjLongJmp(MI, BB);
18163 case TargetOpcode::STACKMAP:
18164 case TargetOpcode::PATCHPOINT:
18165 return emitPatchPoint(MI, BB);
18167 case X86::VFMADDPDr213r:
18168 case X86::VFMADDPSr213r:
18169 case X86::VFMADDSDr213r:
18170 case X86::VFMADDSSr213r:
18171 case X86::VFMSUBPDr213r:
18172 case X86::VFMSUBPSr213r:
18173 case X86::VFMSUBSDr213r:
18174 case X86::VFMSUBSSr213r:
18175 case X86::VFNMADDPDr213r:
18176 case X86::VFNMADDPSr213r:
18177 case X86::VFNMADDSDr213r:
18178 case X86::VFNMADDSSr213r:
18179 case X86::VFNMSUBPDr213r:
18180 case X86::VFNMSUBPSr213r:
18181 case X86::VFNMSUBSDr213r:
18182 case X86::VFNMSUBSSr213r:
18183 case X86::VFMADDPDr213rY:
18184 case X86::VFMADDPSr213rY:
18185 case X86::VFMSUBPDr213rY:
18186 case X86::VFMSUBPSr213rY:
18187 case X86::VFNMADDPDr213rY:
18188 case X86::VFNMADDPSr213rY:
18189 case X86::VFNMSUBPDr213rY:
18190 case X86::VFNMSUBPSr213rY:
18191 return emitFMA3Instr(MI, BB);
18195 //===----------------------------------------------------------------------===//
18196 // X86 Optimization Hooks
18197 //===----------------------------------------------------------------------===//
18199 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18202 const SelectionDAG &DAG,
18203 unsigned Depth) const {
18204 unsigned BitWidth = KnownZero.getBitWidth();
18205 unsigned Opc = Op.getOpcode();
18206 assert((Opc >= ISD::BUILTIN_OP_END ||
18207 Opc == ISD::INTRINSIC_WO_CHAIN ||
18208 Opc == ISD::INTRINSIC_W_CHAIN ||
18209 Opc == ISD::INTRINSIC_VOID) &&
18210 "Should use MaskedValueIsZero if you don't know whether Op"
18211 " is a target node!");
18213 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18227 // These nodes' second result is a boolean.
18228 if (Op.getResNo() == 0)
18231 case X86ISD::SETCC:
18232 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18234 case ISD::INTRINSIC_WO_CHAIN: {
18235 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18236 unsigned NumLoBits = 0;
18239 case Intrinsic::x86_sse_movmsk_ps:
18240 case Intrinsic::x86_avx_movmsk_ps_256:
18241 case Intrinsic::x86_sse2_movmsk_pd:
18242 case Intrinsic::x86_avx_movmsk_pd_256:
18243 case Intrinsic::x86_mmx_pmovmskb:
18244 case Intrinsic::x86_sse2_pmovmskb_128:
18245 case Intrinsic::x86_avx2_pmovmskb: {
18246 // High bits of movmskp{s|d}, pmovmskb are known zero.
18248 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18249 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18250 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18251 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18252 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18253 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18254 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18255 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18257 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18266 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18268 const SelectionDAG &,
18269 unsigned Depth) const {
18270 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18271 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18272 return Op.getValueType().getScalarType().getSizeInBits();
18278 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18279 /// node is a GlobalAddress + offset.
18280 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18281 const GlobalValue* &GA,
18282 int64_t &Offset) const {
18283 if (N->getOpcode() == X86ISD::Wrapper) {
18284 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18285 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18286 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18290 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18293 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18294 /// same as extracting the high 128-bit part of 256-bit vector and then
18295 /// inserting the result into the low part of a new 256-bit vector
18296 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18297 EVT VT = SVOp->getValueType(0);
18298 unsigned NumElems = VT.getVectorNumElements();
18300 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18301 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18302 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18303 SVOp->getMaskElt(j) >= 0)
18309 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18310 /// same as extracting the low 128-bit part of 256-bit vector and then
18311 /// inserting the result into the high part of a new 256-bit vector
18312 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18313 EVT VT = SVOp->getValueType(0);
18314 unsigned NumElems = VT.getVectorNumElements();
18316 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18317 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18318 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18319 SVOp->getMaskElt(j) >= 0)
18325 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18326 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18327 TargetLowering::DAGCombinerInfo &DCI,
18328 const X86Subtarget* Subtarget) {
18330 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18331 SDValue V1 = SVOp->getOperand(0);
18332 SDValue V2 = SVOp->getOperand(1);
18333 EVT VT = SVOp->getValueType(0);
18334 unsigned NumElems = VT.getVectorNumElements();
18336 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18337 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18341 // V UNDEF BUILD_VECTOR UNDEF
18343 // CONCAT_VECTOR CONCAT_VECTOR
18346 // RESULT: V + zero extended
18348 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18349 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18350 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18353 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18356 // To match the shuffle mask, the first half of the mask should
18357 // be exactly the first vector, and all the rest a splat with the
18358 // first element of the second one.
18359 for (unsigned i = 0; i != NumElems/2; ++i)
18360 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18361 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18364 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18365 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18366 if (Ld->hasNUsesOfValue(1, 0)) {
18367 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18368 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18370 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18372 Ld->getPointerInfo(),
18373 Ld->getAlignment(),
18374 false/*isVolatile*/, true/*ReadMem*/,
18375 false/*WriteMem*/);
18377 // Make sure the newly-created LOAD is in the same position as Ld in
18378 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18379 // and update uses of Ld's output chain to use the TokenFactor.
18380 if (Ld->hasAnyUseOfValue(1)) {
18381 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18382 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18383 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18384 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18385 SDValue(ResNode.getNode(), 1));
18388 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18392 // Emit a zeroed vector and insert the desired subvector on its
18394 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18395 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18396 return DCI.CombineTo(N, InsV);
18399 //===--------------------------------------------------------------------===//
18400 // Combine some shuffles into subvector extracts and inserts:
18403 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18404 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18405 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18406 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18407 return DCI.CombineTo(N, InsV);
18410 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18411 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18412 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18413 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18414 return DCI.CombineTo(N, InsV);
18420 /// \brief Get the PSHUF-style mask from PSHUF node.
18422 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18423 /// PSHUF-style masks that can be reused with such instructions.
18424 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18425 SmallVector<int, 4> Mask;
18427 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18431 switch (N.getOpcode()) {
18432 case X86ISD::PSHUFD:
18434 case X86ISD::PSHUFLW:
18437 case X86ISD::PSHUFHW:
18438 Mask.erase(Mask.begin(), Mask.begin() + 4);
18439 for (int &M : Mask)
18443 llvm_unreachable("No valid shuffle instruction found!");
18447 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18449 /// We walk up the chain and look for a combinable shuffle, skipping over
18450 /// shuffles that we could hoist this shuffle's transformation past without
18451 /// altering anything.
18452 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18454 TargetLowering::DAGCombinerInfo &DCI) {
18455 assert(N.getOpcode() == X86ISD::PSHUFD &&
18456 "Called with something other than an x86 128-bit half shuffle!");
18459 // Walk up a single-use chain looking for a combinable shuffle.
18460 SDValue V = N.getOperand(0);
18461 for (; V.hasOneUse(); V = V.getOperand(0)) {
18462 switch (V.getOpcode()) {
18464 return false; // Nothing combined!
18467 // Skip bitcasts as we always know the type for the target specific
18471 case X86ISD::PSHUFD:
18472 // Found another dword shuffle.
18475 case X86ISD::PSHUFLW:
18476 // Check that the low words (being shuffled) are the identity in the
18477 // dword shuffle, and the high words are self-contained.
18478 if (Mask[0] != 0 || Mask[1] != 1 ||
18479 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18484 case X86ISD::PSHUFHW:
18485 // Check that the high words (being shuffled) are the identity in the
18486 // dword shuffle, and the low words are self-contained.
18487 if (Mask[2] != 2 || Mask[3] != 3 ||
18488 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18493 // Break out of the loop if we break out of the switch.
18497 if (!V.hasOneUse())
18498 // We fell out of the loop without finding a viable combining instruction.
18501 // Record the old value to use in RAUW-ing.
18504 // Merge this node's mask and our incoming mask.
18505 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18506 for (int &M : Mask)
18508 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
18509 getV4X86ShuffleImm8ForMask(Mask, DAG));
18511 // It is possible that one of the combinable shuffles was completely absorbed
18512 // by the other, just replace it and revisit all users in that case.
18513 if (Old.getNode() == V.getNode()) {
18514 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18518 // Replace N with its operand as we're going to combine that shuffle away.
18519 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18521 // Replace the combinable shuffle with the combined one, updating all users
18522 // so that we re-evaluate the chain here.
18523 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18527 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18529 /// We walk up the chain, skipping shuffles of the other half and looking
18530 /// through shuffles which switch halves trying to find a shuffle of the same
18531 /// pair of dwords.
18532 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18534 TargetLowering::DAGCombinerInfo &DCI) {
18536 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18537 "Called with something other than an x86 128-bit half shuffle!");
18539 unsigned CombineOpcode = N.getOpcode();
18541 // Walk up a single-use chain looking for a combinable shuffle.
18542 SDValue V = N.getOperand(0);
18543 for (; V.hasOneUse(); V = V.getOperand(0)) {
18544 switch (V.getOpcode()) {
18546 return false; // Nothing combined!
18549 // Skip bitcasts as we always know the type for the target specific
18553 case X86ISD::PSHUFLW:
18554 case X86ISD::PSHUFHW:
18555 if (V.getOpcode() == CombineOpcode)
18558 // Other-half shuffles are no-ops.
18561 case X86ISD::PSHUFD: {
18562 // We can only handle pshufd if the half we are combining either stays in
18563 // its half, or switches to the other half. Bail if one of these isn't
18565 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18566 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18567 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18568 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18571 // Map the mask through the pshufd and keep walking up the chain.
18572 for (int i = 0; i < 4; ++i)
18573 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18575 // Switch halves if the pshufd does.
18577 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18581 // Break out of the loop if we break out of the switch.
18585 if (!V.hasOneUse())
18586 // We fell out of the loop without finding a viable combining instruction.
18589 // Record the old value to use in RAUW-ing.
18592 // Merge this node's mask and our incoming mask (adjusted to account for all
18593 // the pshufd instructions encountered).
18594 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18595 for (int &M : Mask)
18597 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18598 getV4X86ShuffleImm8ForMask(Mask, DAG));
18600 // Replace N with its operand as we're going to combine that shuffle away.
18601 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18603 // Replace the combinable shuffle with the combined one, updating all users
18604 // so that we re-evaluate the chain here.
18605 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18609 /// \brief Try to combine x86 target specific shuffles.
18610 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18611 TargetLowering::DAGCombinerInfo &DCI,
18612 const X86Subtarget *Subtarget) {
18614 MVT VT = N.getSimpleValueType();
18615 SmallVector<int, 4> Mask;
18617 switch (N.getOpcode()) {
18618 case X86ISD::PSHUFD:
18619 case X86ISD::PSHUFLW:
18620 case X86ISD::PSHUFHW:
18621 Mask = getPSHUFShuffleMask(N);
18622 assert(Mask.size() == 4);
18628 // Nuke no-op shuffles that show up after combining.
18629 if (isNoopShuffleMask(Mask))
18630 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18632 // Look for simplifications involving one or two shuffle instructions.
18633 SDValue V = N.getOperand(0);
18634 switch (N.getOpcode()) {
18637 case X86ISD::PSHUFLW:
18638 case X86ISD::PSHUFHW:
18639 assert(VT == MVT::v8i16);
18642 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18643 return SDValue(); // We combined away this shuffle, so we're done.
18645 // See if this reduces to a PSHUFD which is no more expensive and can
18646 // combine with more operations.
18647 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18648 areAdjacentMasksSequential(Mask)) {
18649 int DMask[] = {-1, -1, -1, -1};
18650 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18651 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18652 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18653 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18654 DCI.AddToWorklist(V.getNode());
18655 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18656 getV4X86ShuffleImm8ForMask(DMask, DAG));
18657 DCI.AddToWorklist(V.getNode());
18658 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18663 case X86ISD::PSHUFD:
18664 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18665 return SDValue(); // We combined away this shuffle.
18673 /// PerformShuffleCombine - Performs several different shuffle combines.
18674 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18675 TargetLowering::DAGCombinerInfo &DCI,
18676 const X86Subtarget *Subtarget) {
18678 SDValue N0 = N->getOperand(0);
18679 SDValue N1 = N->getOperand(1);
18680 EVT VT = N->getValueType(0);
18682 // Canonicalize shuffles that perform 'addsub' on packed float vectors
18683 // according to the rule:
18684 // (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18685 // (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18687 // Where 'Mask' is:
18688 // <0,5,2,7> -- for v4f32 and v4f64 shuffles;
18689 // <0,3> -- for v2f64 shuffles;
18690 // <0,9,2,11,4,13,6,15> -- for v8f32 shuffles.
18692 // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18693 // during ISel stage.
18694 if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18695 ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18696 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18697 N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18698 // Operands to the FADD and FSUB must be the same.
18699 ((N0->getOperand(0) == N1->getOperand(0) &&
18700 N0->getOperand(1) == N1->getOperand(1)) ||
18701 // FADD is commutable. See if by commuting the operands of the FADD
18702 // we would still be able to match the operands of the FSUB dag node.
18703 (N0->getOperand(1) == N1->getOperand(0) &&
18704 N0->getOperand(0) == N1->getOperand(1))) &&
18705 N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18706 N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18708 ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18709 unsigned NumElts = VT.getVectorNumElements();
18710 ArrayRef<int> Mask = SV->getMask();
18711 bool CanFold = true;
18713 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18714 CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18717 SDValue Op0 = N1->getOperand(0);
18718 SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18719 SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18720 SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18721 return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18725 // Don't create instructions with illegal types after legalize types has run.
18726 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18727 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18730 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18731 if (Subtarget->hasFp256() && VT.is256BitVector() &&
18732 N->getOpcode() == ISD::VECTOR_SHUFFLE)
18733 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18735 // During Type Legalization, when promoting illegal vector types,
18736 // the backend might introduce new shuffle dag nodes and bitcasts.
18738 // This code performs the following transformation:
18739 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18740 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18742 // We do this only if both the bitcast and the BINOP dag nodes have
18743 // one use. Also, perform this transformation only if the new binary
18744 // operation is legal. This is to avoid introducing dag nodes that
18745 // potentially need to be further expanded (or custom lowered) into a
18746 // less optimal sequence of dag nodes.
18747 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18748 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18749 N0.getOpcode() == ISD::BITCAST) {
18750 SDValue BC0 = N0.getOperand(0);
18751 EVT SVT = BC0.getValueType();
18752 unsigned Opcode = BC0.getOpcode();
18753 unsigned NumElts = VT.getVectorNumElements();
18755 if (BC0.hasOneUse() && SVT.isVector() &&
18756 SVT.getVectorNumElements() * 2 == NumElts &&
18757 TLI.isOperationLegal(Opcode, VT)) {
18758 bool CanFold = false;
18770 unsigned SVTNumElts = SVT.getVectorNumElements();
18771 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18772 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18773 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18774 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18775 CanFold = SVOp->getMaskElt(i) < 0;
18778 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18779 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18780 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18781 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18786 // Only handle 128 wide vector from here on.
18787 if (!VT.is128BitVector())
18790 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18791 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18792 // consecutive, non-overlapping, and in the right order.
18793 SmallVector<SDValue, 16> Elts;
18794 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18795 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18797 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18801 if (isTargetShuffle(N->getOpcode())) {
18803 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18804 if (Shuffle.getNode())
18811 /// PerformTruncateCombine - Converts truncate operation to
18812 /// a sequence of vector shuffle operations.
18813 /// It is possible when we truncate 256-bit vector to 128-bit vector
18814 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18815 TargetLowering::DAGCombinerInfo &DCI,
18816 const X86Subtarget *Subtarget) {
18820 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18821 /// specific shuffle of a load can be folded into a single element load.
18822 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18823 /// shuffles have been customed lowered so we need to handle those here.
18824 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18825 TargetLowering::DAGCombinerInfo &DCI) {
18826 if (DCI.isBeforeLegalizeOps())
18829 SDValue InVec = N->getOperand(0);
18830 SDValue EltNo = N->getOperand(1);
18832 if (!isa<ConstantSDNode>(EltNo))
18835 EVT VT = InVec.getValueType();
18837 bool HasShuffleIntoBitcast = false;
18838 if (InVec.getOpcode() == ISD::BITCAST) {
18839 // Don't duplicate a load with other uses.
18840 if (!InVec.hasOneUse())
18842 EVT BCVT = InVec.getOperand(0).getValueType();
18843 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18845 InVec = InVec.getOperand(0);
18846 HasShuffleIntoBitcast = true;
18849 if (!isTargetShuffle(InVec.getOpcode()))
18852 // Don't duplicate a load with other uses.
18853 if (!InVec.hasOneUse())
18856 SmallVector<int, 16> ShuffleMask;
18858 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18862 // Select the input vector, guarding against out of range extract vector.
18863 unsigned NumElems = VT.getVectorNumElements();
18864 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18865 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18866 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18867 : InVec.getOperand(1);
18869 // If inputs to shuffle are the same for both ops, then allow 2 uses
18870 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18872 if (LdNode.getOpcode() == ISD::BITCAST) {
18873 // Don't duplicate a load with other uses.
18874 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18877 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18878 LdNode = LdNode.getOperand(0);
18881 if (!ISD::isNormalLoad(LdNode.getNode()))
18884 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18886 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18889 if (HasShuffleIntoBitcast) {
18890 // If there's a bitcast before the shuffle, check if the load type and
18891 // alignment is valid.
18892 unsigned Align = LN0->getAlignment();
18893 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18894 unsigned NewAlign = TLI.getDataLayout()->
18895 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18897 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18901 // All checks match so transform back to vector_shuffle so that DAG combiner
18902 // can finish the job
18905 // Create shuffle node taking into account the case that its a unary shuffle
18906 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18907 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18908 InVec.getOperand(0), Shuffle,
18910 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18911 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18915 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18916 /// generation and convert it from being a bunch of shuffles and extracts
18917 /// to a simple store and scalar loads to extract the elements.
18918 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18919 TargetLowering::DAGCombinerInfo &DCI) {
18920 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18921 if (NewOp.getNode())
18924 SDValue InputVector = N->getOperand(0);
18926 // Detect whether we are trying to convert from mmx to i32 and the bitcast
18927 // from mmx to v2i32 has a single usage.
18928 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18929 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18930 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18931 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18932 N->getValueType(0),
18933 InputVector.getNode()->getOperand(0));
18935 // Only operate on vectors of 4 elements, where the alternative shuffling
18936 // gets to be more expensive.
18937 if (InputVector.getValueType() != MVT::v4i32)
18940 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18941 // single use which is a sign-extend or zero-extend, and all elements are
18943 SmallVector<SDNode *, 4> Uses;
18944 unsigned ExtractedElements = 0;
18945 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18946 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18947 if (UI.getUse().getResNo() != InputVector.getResNo())
18950 SDNode *Extract = *UI;
18951 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18954 if (Extract->getValueType(0) != MVT::i32)
18956 if (!Extract->hasOneUse())
18958 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18959 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18961 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18964 // Record which element was extracted.
18965 ExtractedElements |=
18966 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18968 Uses.push_back(Extract);
18971 // If not all the elements were used, this may not be worthwhile.
18972 if (ExtractedElements != 15)
18975 // Ok, we've now decided to do the transformation.
18976 SDLoc dl(InputVector);
18978 // Store the value to a temporary stack slot.
18979 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18980 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18981 MachinePointerInfo(), false, false, 0);
18983 // Replace each use (extract) with a load of the appropriate element.
18984 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18985 UE = Uses.end(); UI != UE; ++UI) {
18986 SDNode *Extract = *UI;
18988 // cOMpute the element's address.
18989 SDValue Idx = Extract->getOperand(1);
18991 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18992 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18993 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18994 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18996 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18997 StackPtr, OffsetVal);
18999 // Load the scalar.
19000 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19001 ScalarAddr, MachinePointerInfo(),
19002 false, false, false, 0);
19004 // Replace the exact with the load.
19005 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19008 // The replacement was made in place; don't return anything.
19012 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19013 static std::pair<unsigned, bool>
19014 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19015 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19016 if (!VT.isVector())
19017 return std::make_pair(0, false);
19019 bool NeedSplit = false;
19020 switch (VT.getSimpleVT().SimpleTy) {
19021 default: return std::make_pair(0, false);
19025 if (!Subtarget->hasAVX2())
19027 if (!Subtarget->hasAVX())
19028 return std::make_pair(0, false);
19033 if (!Subtarget->hasSSE2())
19034 return std::make_pair(0, false);
19037 // SSE2 has only a small subset of the operations.
19038 bool hasUnsigned = Subtarget->hasSSE41() ||
19039 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19040 bool hasSigned = Subtarget->hasSSE41() ||
19041 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19043 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19046 // Check for x CC y ? x : y.
19047 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19048 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19053 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19056 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19059 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19062 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19064 // Check for x CC y ? y : x -- a min/max with reversed arms.
19065 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19066 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19071 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19074 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19077 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19080 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19084 return std::make_pair(Opc, NeedSplit);
19088 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19089 const X86Subtarget *Subtarget) {
19091 SDValue Cond = N->getOperand(0);
19092 SDValue LHS = N->getOperand(1);
19093 SDValue RHS = N->getOperand(2);
19095 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19096 SDValue CondSrc = Cond->getOperand(0);
19097 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19098 Cond = CondSrc->getOperand(0);
19101 MVT VT = N->getSimpleValueType(0);
19102 MVT EltVT = VT.getVectorElementType();
19103 unsigned NumElems = VT.getVectorNumElements();
19104 // There is no blend with immediate in AVX-512.
19105 if (VT.is512BitVector())
19108 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19110 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19113 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19116 unsigned MaskValue = 0;
19117 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19120 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19121 for (unsigned i = 0; i < NumElems; ++i) {
19122 // Be sure we emit undef where we can.
19123 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19124 ShuffleMask[i] = -1;
19126 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19129 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19132 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19134 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19135 TargetLowering::DAGCombinerInfo &DCI,
19136 const X86Subtarget *Subtarget) {
19138 SDValue Cond = N->getOperand(0);
19139 // Get the LHS/RHS of the select.
19140 SDValue LHS = N->getOperand(1);
19141 SDValue RHS = N->getOperand(2);
19142 EVT VT = LHS.getValueType();
19143 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19145 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19146 // instructions match the semantics of the common C idiom x<y?x:y but not
19147 // x<=y?x:y, because of how they handle negative zero (which can be
19148 // ignored in unsafe-math mode).
19149 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19150 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19151 (Subtarget->hasSSE2() ||
19152 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19153 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19155 unsigned Opcode = 0;
19156 // Check for x CC y ? x : y.
19157 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19158 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19162 // Converting this to a min would handle NaNs incorrectly, and swapping
19163 // the operands would cause it to handle comparisons between positive
19164 // and negative zero incorrectly.
19165 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19166 if (!DAG.getTarget().Options.UnsafeFPMath &&
19167 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19169 std::swap(LHS, RHS);
19171 Opcode = X86ISD::FMIN;
19174 // Converting this to a min would handle comparisons between positive
19175 // and negative zero incorrectly.
19176 if (!DAG.getTarget().Options.UnsafeFPMath &&
19177 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19179 Opcode = X86ISD::FMIN;
19182 // Converting this to a min would handle both negative zeros and NaNs
19183 // incorrectly, but we can swap the operands to fix both.
19184 std::swap(LHS, RHS);
19188 Opcode = X86ISD::FMIN;
19192 // Converting this to a max would handle comparisons between positive
19193 // and negative zero incorrectly.
19194 if (!DAG.getTarget().Options.UnsafeFPMath &&
19195 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19197 Opcode = X86ISD::FMAX;
19200 // Converting this to a max would handle NaNs incorrectly, and swapping
19201 // the operands would cause it to handle comparisons between positive
19202 // and negative zero incorrectly.
19203 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19204 if (!DAG.getTarget().Options.UnsafeFPMath &&
19205 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19207 std::swap(LHS, RHS);
19209 Opcode = X86ISD::FMAX;
19212 // Converting this to a max would handle both negative zeros and NaNs
19213 // incorrectly, but we can swap the operands to fix both.
19214 std::swap(LHS, RHS);
19218 Opcode = X86ISD::FMAX;
19221 // Check for x CC y ? y : x -- a min/max with reversed arms.
19222 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19223 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19227 // Converting this to a min would handle comparisons between positive
19228 // and negative zero incorrectly, and swapping the operands would
19229 // cause it to handle NaNs incorrectly.
19230 if (!DAG.getTarget().Options.UnsafeFPMath &&
19231 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19232 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19234 std::swap(LHS, RHS);
19236 Opcode = X86ISD::FMIN;
19239 // Converting this to a min would handle NaNs incorrectly.
19240 if (!DAG.getTarget().Options.UnsafeFPMath &&
19241 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19243 Opcode = X86ISD::FMIN;
19246 // Converting this to a min would handle both negative zeros and NaNs
19247 // incorrectly, but we can swap the operands to fix both.
19248 std::swap(LHS, RHS);
19252 Opcode = X86ISD::FMIN;
19256 // Converting this to a max would handle NaNs incorrectly.
19257 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19259 Opcode = X86ISD::FMAX;
19262 // Converting this to a max would handle comparisons between positive
19263 // and negative zero incorrectly, and swapping the operands would
19264 // cause it to handle NaNs incorrectly.
19265 if (!DAG.getTarget().Options.UnsafeFPMath &&
19266 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19267 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19269 std::swap(LHS, RHS);
19271 Opcode = X86ISD::FMAX;
19274 // Converting this to a max would handle both negative zeros and NaNs
19275 // incorrectly, but we can swap the operands to fix both.
19276 std::swap(LHS, RHS);
19280 Opcode = X86ISD::FMAX;
19286 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19289 EVT CondVT = Cond.getValueType();
19290 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19291 CondVT.getVectorElementType() == MVT::i1) {
19292 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19293 // lowering on AVX-512. In this case we convert it to
19294 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19295 // The same situation for all 128 and 256-bit vectors of i8 and i16
19296 EVT OpVT = LHS.getValueType();
19297 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19298 (OpVT.getVectorElementType() == MVT::i8 ||
19299 OpVT.getVectorElementType() == MVT::i16)) {
19300 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19301 DCI.AddToWorklist(Cond.getNode());
19302 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19305 // If this is a select between two integer constants, try to do some
19307 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19308 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19309 // Don't do this for crazy integer types.
19310 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19311 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19312 // so that TrueC (the true value) is larger than FalseC.
19313 bool NeedsCondInvert = false;
19315 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19316 // Efficiently invertible.
19317 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19318 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19319 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19320 NeedsCondInvert = true;
19321 std::swap(TrueC, FalseC);
19324 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19325 if (FalseC->getAPIntValue() == 0 &&
19326 TrueC->getAPIntValue().isPowerOf2()) {
19327 if (NeedsCondInvert) // Invert the condition if needed.
19328 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19329 DAG.getConstant(1, Cond.getValueType()));
19331 // Zero extend the condition if needed.
19332 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19334 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19335 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19336 DAG.getConstant(ShAmt, MVT::i8));
19339 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19340 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19341 if (NeedsCondInvert) // Invert the condition if needed.
19342 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19343 DAG.getConstant(1, Cond.getValueType()));
19345 // Zero extend the condition if needed.
19346 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19347 FalseC->getValueType(0), Cond);
19348 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19349 SDValue(FalseC, 0));
19352 // Optimize cases that will turn into an LEA instruction. This requires
19353 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19354 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19355 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19356 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19358 bool isFastMultiplier = false;
19360 switch ((unsigned char)Diff) {
19362 case 1: // result = add base, cond
19363 case 2: // result = lea base( , cond*2)
19364 case 3: // result = lea base(cond, cond*2)
19365 case 4: // result = lea base( , cond*4)
19366 case 5: // result = lea base(cond, cond*4)
19367 case 8: // result = lea base( , cond*8)
19368 case 9: // result = lea base(cond, cond*8)
19369 isFastMultiplier = true;
19374 if (isFastMultiplier) {
19375 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19376 if (NeedsCondInvert) // Invert the condition if needed.
19377 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19378 DAG.getConstant(1, Cond.getValueType()));
19380 // Zero extend the condition if needed.
19381 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19383 // Scale the condition by the difference.
19385 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19386 DAG.getConstant(Diff, Cond.getValueType()));
19388 // Add the base if non-zero.
19389 if (FalseC->getAPIntValue() != 0)
19390 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19391 SDValue(FalseC, 0));
19398 // Canonicalize max and min:
19399 // (x > y) ? x : y -> (x >= y) ? x : y
19400 // (x < y) ? x : y -> (x <= y) ? x : y
19401 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19402 // the need for an extra compare
19403 // against zero. e.g.
19404 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19406 // testl %edi, %edi
19408 // cmovgl %edi, %eax
19412 // cmovsl %eax, %edi
19413 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19414 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19415 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19416 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19421 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19422 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19423 Cond.getOperand(0), Cond.getOperand(1), NewCC);
19424 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19429 // Early exit check
19430 if (!TLI.isTypeLegal(VT))
19433 // Match VSELECTs into subs with unsigned saturation.
19434 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19435 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19436 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19437 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19438 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19440 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19441 // left side invert the predicate to simplify logic below.
19443 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19445 CC = ISD::getSetCCInverse(CC, true);
19446 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19450 if (Other.getNode() && Other->getNumOperands() == 2 &&
19451 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19452 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19453 SDValue CondRHS = Cond->getOperand(1);
19455 // Look for a general sub with unsigned saturation first.
19456 // x >= y ? x-y : 0 --> subus x, y
19457 // x > y ? x-y : 0 --> subus x, y
19458 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19459 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19460 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19462 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS)) {
19463 SDValue OpRHSSplat = OpRHSBV->getConstantSplatValue();
19464 auto *OpRHSSplatConst = dyn_cast<ConstantSDNode>(OpRHSSplat);
19465 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS)) {
19466 // If the RHS is a constant we have to reverse the const
19467 // canonicalization.
19468 // x > C-1 ? x+-C : 0 --> subus x, C
19469 SDValue CondRHSSplat = CondRHSBV->getConstantSplatValue();
19470 auto *CondRHSSplatConst = dyn_cast<ConstantSDNode>(CondRHSSplat);
19471 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19472 CondRHSSplatConst && OpRHSSplatConst) {
19473 APInt A = OpRHSSplatConst->getAPIntValue();
19474 if (CondRHSSplatConst->getAPIntValue() == -A - 1)
19475 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
19476 DAG.getConstant(-A, VT));
19480 // Another special case: If C was a sign bit, the sub has been
19481 // canonicalized into a xor.
19482 // FIXME: Would it be better to use computeKnownBits to determine
19483 // whether it's safe to decanonicalize the xor?
19484 // x s< 0 ? x^C : 0 --> subus x, C
19485 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19486 ISD::isBuildVectorAllZeros(CondRHS.getNode()) && OpRHSSplatConst) {
19487 APInt A = OpRHSSplatConst->getAPIntValue();
19489 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19495 // Try to match a min/max vector operation.
19496 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19497 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19498 unsigned Opc = ret.first;
19499 bool NeedSplit = ret.second;
19501 if (Opc && NeedSplit) {
19502 unsigned NumElems = VT.getVectorNumElements();
19503 // Extract the LHS vectors
19504 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19505 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19507 // Extract the RHS vectors
19508 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19509 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19511 // Create min/max for each subvector
19512 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19513 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19515 // Merge the result
19516 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19518 return DAG.getNode(Opc, DL, VT, LHS, RHS);
19521 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19522 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19523 // Check if SETCC has already been promoted
19524 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19525 // Check that condition value type matches vselect operand type
19528 assert(Cond.getValueType().isVector() &&
19529 "vector select expects a vector selector!");
19531 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19532 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19534 if (!TValIsAllOnes && !FValIsAllZeros) {
19535 // Try invert the condition if true value is not all 1s and false value
19537 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19538 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19540 if (TValIsAllZeros || FValIsAllOnes) {
19541 SDValue CC = Cond.getOperand(2);
19542 ISD::CondCode NewCC =
19543 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19544 Cond.getOperand(0).getValueType().isInteger());
19545 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19546 std::swap(LHS, RHS);
19547 TValIsAllOnes = FValIsAllOnes;
19548 FValIsAllZeros = TValIsAllZeros;
19552 if (TValIsAllOnes || FValIsAllZeros) {
19555 if (TValIsAllOnes && FValIsAllZeros)
19557 else if (TValIsAllOnes)
19558 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19559 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19560 else if (FValIsAllZeros)
19561 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19562 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19564 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19568 // Try to fold this VSELECT into a MOVSS/MOVSD
19569 if (N->getOpcode() == ISD::VSELECT &&
19570 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19571 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19572 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19573 bool CanFold = false;
19574 unsigned NumElems = Cond.getNumOperands();
19578 if (isZero(Cond.getOperand(0))) {
19581 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19582 // fold (vselect <0,-1> -> (movsd A, B)
19583 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19584 CanFold = isAllOnes(Cond.getOperand(i));
19585 } else if (isAllOnes(Cond.getOperand(0))) {
19589 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19590 // fold (vselect <-1,0> -> (movsd B, A)
19591 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19592 CanFold = isZero(Cond.getOperand(i));
19596 if (VT == MVT::v4i32 || VT == MVT::v4f32)
19597 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19598 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19601 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19602 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19603 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19604 // (v2i64 (bitcast B)))))
19606 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19607 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19608 // (v2f64 (bitcast B)))))
19610 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19611 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19612 // (v2i64 (bitcast A)))))
19614 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19615 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19616 // (v2f64 (bitcast A)))))
19618 CanFold = (isZero(Cond.getOperand(0)) &&
19619 isZero(Cond.getOperand(1)) &&
19620 isAllOnes(Cond.getOperand(2)) &&
19621 isAllOnes(Cond.getOperand(3)));
19623 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19624 isAllOnes(Cond.getOperand(1)) &&
19625 isZero(Cond.getOperand(2)) &&
19626 isZero(Cond.getOperand(3))) {
19628 std::swap(LHS, RHS);
19632 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19633 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19634 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19635 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19637 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19643 // If we know that this node is legal then we know that it is going to be
19644 // matched by one of the SSE/AVX BLEND instructions. These instructions only
19645 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19646 // to simplify previous instructions.
19647 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19648 !DCI.isBeforeLegalize() &&
19649 // We explicitly check against v8i16 and v16i16 because, although
19650 // they're marked as Custom, they might only be legal when Cond is a
19651 // build_vector of constants. This will be taken care in a later
19653 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19654 VT != MVT::v8i16)) {
19655 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19657 // Don't optimize vector selects that map to mask-registers.
19661 // Check all uses of that condition operand to check whether it will be
19662 // consumed by non-BLEND instructions, which may depend on all bits are set
19664 for (SDNode::use_iterator I = Cond->use_begin(),
19665 E = Cond->use_end(); I != E; ++I)
19666 if (I->getOpcode() != ISD::VSELECT)
19667 // TODO: Add other opcodes eventually lowered into BLEND.
19670 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19671 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19673 APInt KnownZero, KnownOne;
19674 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19675 DCI.isBeforeLegalizeOps());
19676 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19677 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19678 DCI.CommitTargetLoweringOpt(TLO);
19681 // We should generate an X86ISD::BLENDI from a vselect if its argument
19682 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19683 // constants. This specific pattern gets generated when we split a
19684 // selector for a 512 bit vector in a machine without AVX512 (but with
19685 // 256-bit vectors), during legalization:
19687 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19689 // Iff we find this pattern and the build_vectors are built from
19690 // constants, we translate the vselect into a shuffle_vector that we
19691 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19692 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19693 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19694 if (Shuffle.getNode())
19701 // Check whether a boolean test is testing a boolean value generated by
19702 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19705 // Simplify the following patterns:
19706 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19707 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19708 // to (Op EFLAGS Cond)
19710 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19711 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19712 // to (Op EFLAGS !Cond)
19714 // where Op could be BRCOND or CMOV.
19716 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19717 // Quit if not CMP and SUB with its value result used.
19718 if (Cmp.getOpcode() != X86ISD::CMP &&
19719 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19722 // Quit if not used as a boolean value.
19723 if (CC != X86::COND_E && CC != X86::COND_NE)
19726 // Check CMP operands. One of them should be 0 or 1 and the other should be
19727 // an SetCC or extended from it.
19728 SDValue Op1 = Cmp.getOperand(0);
19729 SDValue Op2 = Cmp.getOperand(1);
19732 const ConstantSDNode* C = nullptr;
19733 bool needOppositeCond = (CC == X86::COND_E);
19734 bool checkAgainstTrue = false; // Is it a comparison against 1?
19736 if ((C = dyn_cast<ConstantSDNode>(Op1)))
19738 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19740 else // Quit if all operands are not constants.
19743 if (C->getZExtValue() == 1) {
19744 needOppositeCond = !needOppositeCond;
19745 checkAgainstTrue = true;
19746 } else if (C->getZExtValue() != 0)
19747 // Quit if the constant is neither 0 or 1.
19750 bool truncatedToBoolWithAnd = false;
19751 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19752 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19753 SetCC.getOpcode() == ISD::TRUNCATE ||
19754 SetCC.getOpcode() == ISD::AND) {
19755 if (SetCC.getOpcode() == ISD::AND) {
19757 ConstantSDNode *CS;
19758 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19759 CS->getZExtValue() == 1)
19761 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19762 CS->getZExtValue() == 1)
19766 SetCC = SetCC.getOperand(OpIdx);
19767 truncatedToBoolWithAnd = true;
19769 SetCC = SetCC.getOperand(0);
19772 switch (SetCC.getOpcode()) {
19773 case X86ISD::SETCC_CARRY:
19774 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19775 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19776 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19777 // truncated to i1 using 'and'.
19778 if (checkAgainstTrue && !truncatedToBoolWithAnd)
19780 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19781 "Invalid use of SETCC_CARRY!");
19783 case X86ISD::SETCC:
19784 // Set the condition code or opposite one if necessary.
19785 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19786 if (needOppositeCond)
19787 CC = X86::GetOppositeBranchCondition(CC);
19788 return SetCC.getOperand(1);
19789 case X86ISD::CMOV: {
19790 // Check whether false/true value has canonical one, i.e. 0 or 1.
19791 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19792 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19793 // Quit if true value is not a constant.
19796 // Quit if false value is not a constant.
19798 SDValue Op = SetCC.getOperand(0);
19799 // Skip 'zext' or 'trunc' node.
19800 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19801 Op.getOpcode() == ISD::TRUNCATE)
19802 Op = Op.getOperand(0);
19803 // A special case for rdrand/rdseed, where 0 is set if false cond is
19805 if ((Op.getOpcode() != X86ISD::RDRAND &&
19806 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19809 // Quit if false value is not the constant 0 or 1.
19810 bool FValIsFalse = true;
19811 if (FVal && FVal->getZExtValue() != 0) {
19812 if (FVal->getZExtValue() != 1)
19814 // If FVal is 1, opposite cond is needed.
19815 needOppositeCond = !needOppositeCond;
19816 FValIsFalse = false;
19818 // Quit if TVal is not the constant opposite of FVal.
19819 if (FValIsFalse && TVal->getZExtValue() != 1)
19821 if (!FValIsFalse && TVal->getZExtValue() != 0)
19823 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19824 if (needOppositeCond)
19825 CC = X86::GetOppositeBranchCondition(CC);
19826 return SetCC.getOperand(3);
19833 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19834 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19835 TargetLowering::DAGCombinerInfo &DCI,
19836 const X86Subtarget *Subtarget) {
19839 // If the flag operand isn't dead, don't touch this CMOV.
19840 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19843 SDValue FalseOp = N->getOperand(0);
19844 SDValue TrueOp = N->getOperand(1);
19845 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19846 SDValue Cond = N->getOperand(3);
19848 if (CC == X86::COND_E || CC == X86::COND_NE) {
19849 switch (Cond.getOpcode()) {
19853 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19854 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19855 return (CC == X86::COND_E) ? FalseOp : TrueOp;
19861 Flags = checkBoolTestSetCCCombine(Cond, CC);
19862 if (Flags.getNode() &&
19863 // Extra check as FCMOV only supports a subset of X86 cond.
19864 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19865 SDValue Ops[] = { FalseOp, TrueOp,
19866 DAG.getConstant(CC, MVT::i8), Flags };
19867 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19870 // If this is a select between two integer constants, try to do some
19871 // optimizations. Note that the operands are ordered the opposite of SELECT
19873 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19874 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19875 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19876 // larger than FalseC (the false value).
19877 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19878 CC = X86::GetOppositeBranchCondition(CC);
19879 std::swap(TrueC, FalseC);
19880 std::swap(TrueOp, FalseOp);
19883 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
19884 // This is efficient for any integer data type (including i8/i16) and
19886 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19887 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19888 DAG.getConstant(CC, MVT::i8), Cond);
19890 // Zero extend the condition if needed.
19891 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19893 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19894 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19895 DAG.getConstant(ShAmt, MVT::i8));
19896 if (N->getNumValues() == 2) // Dead flag value?
19897 return DCI.CombineTo(N, Cond, SDValue());
19901 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
19902 // for any integer data type, including i8/i16.
19903 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19904 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19905 DAG.getConstant(CC, MVT::i8), Cond);
19907 // Zero extend the condition if needed.
19908 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19909 FalseC->getValueType(0), Cond);
19910 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19911 SDValue(FalseC, 0));
19913 if (N->getNumValues() == 2) // Dead flag value?
19914 return DCI.CombineTo(N, Cond, SDValue());
19918 // Optimize cases that will turn into an LEA instruction. This requires
19919 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19920 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19921 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19922 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19924 bool isFastMultiplier = false;
19926 switch ((unsigned char)Diff) {
19928 case 1: // result = add base, cond
19929 case 2: // result = lea base( , cond*2)
19930 case 3: // result = lea base(cond, cond*2)
19931 case 4: // result = lea base( , cond*4)
19932 case 5: // result = lea base(cond, cond*4)
19933 case 8: // result = lea base( , cond*8)
19934 case 9: // result = lea base(cond, cond*8)
19935 isFastMultiplier = true;
19940 if (isFastMultiplier) {
19941 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19942 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19943 DAG.getConstant(CC, MVT::i8), Cond);
19944 // Zero extend the condition if needed.
19945 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19947 // Scale the condition by the difference.
19949 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19950 DAG.getConstant(Diff, Cond.getValueType()));
19952 // Add the base if non-zero.
19953 if (FalseC->getAPIntValue() != 0)
19954 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19955 SDValue(FalseC, 0));
19956 if (N->getNumValues() == 2) // Dead flag value?
19957 return DCI.CombineTo(N, Cond, SDValue());
19964 // Handle these cases:
19965 // (select (x != c), e, c) -> select (x != c), e, x),
19966 // (select (x == c), c, e) -> select (x == c), x, e)
19967 // where the c is an integer constant, and the "select" is the combination
19968 // of CMOV and CMP.
19970 // The rationale for this change is that the conditional-move from a constant
19971 // needs two instructions, however, conditional-move from a register needs
19972 // only one instruction.
19974 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19975 // some instruction-combining opportunities. This opt needs to be
19976 // postponed as late as possible.
19978 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19979 // the DCI.xxxx conditions are provided to postpone the optimization as
19980 // late as possible.
19982 ConstantSDNode *CmpAgainst = nullptr;
19983 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19984 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19985 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19987 if (CC == X86::COND_NE &&
19988 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19989 CC = X86::GetOppositeBranchCondition(CC);
19990 std::swap(TrueOp, FalseOp);
19993 if (CC == X86::COND_E &&
19994 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19995 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19996 DAG.getConstant(CC, MVT::i8), Cond };
19997 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20005 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20006 const X86Subtarget *Subtarget) {
20007 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20009 default: return SDValue();
20010 // SSE/AVX/AVX2 blend intrinsics.
20011 case Intrinsic::x86_avx2_pblendvb:
20012 case Intrinsic::x86_avx2_pblendw:
20013 case Intrinsic::x86_avx2_pblendd_128:
20014 case Intrinsic::x86_avx2_pblendd_256:
20015 // Don't try to simplify this intrinsic if we don't have AVX2.
20016 if (!Subtarget->hasAVX2())
20019 case Intrinsic::x86_avx_blend_pd_256:
20020 case Intrinsic::x86_avx_blend_ps_256:
20021 case Intrinsic::x86_avx_blendv_pd_256:
20022 case Intrinsic::x86_avx_blendv_ps_256:
20023 // Don't try to simplify this intrinsic if we don't have AVX.
20024 if (!Subtarget->hasAVX())
20027 case Intrinsic::x86_sse41_pblendw:
20028 case Intrinsic::x86_sse41_blendpd:
20029 case Intrinsic::x86_sse41_blendps:
20030 case Intrinsic::x86_sse41_blendvps:
20031 case Intrinsic::x86_sse41_blendvpd:
20032 case Intrinsic::x86_sse41_pblendvb: {
20033 SDValue Op0 = N->getOperand(1);
20034 SDValue Op1 = N->getOperand(2);
20035 SDValue Mask = N->getOperand(3);
20037 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20038 if (!Subtarget->hasSSE41())
20041 // fold (blend A, A, Mask) -> A
20044 // fold (blend A, B, allZeros) -> A
20045 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20047 // fold (blend A, B, allOnes) -> B
20048 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20051 // Simplify the case where the mask is a constant i32 value.
20052 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20053 if (C->isNullValue())
20055 if (C->isAllOnesValue())
20062 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20063 case Intrinsic::x86_sse2_psrai_w:
20064 case Intrinsic::x86_sse2_psrai_d:
20065 case Intrinsic::x86_avx2_psrai_w:
20066 case Intrinsic::x86_avx2_psrai_d:
20067 case Intrinsic::x86_sse2_psra_w:
20068 case Intrinsic::x86_sse2_psra_d:
20069 case Intrinsic::x86_avx2_psra_w:
20070 case Intrinsic::x86_avx2_psra_d: {
20071 SDValue Op0 = N->getOperand(1);
20072 SDValue Op1 = N->getOperand(2);
20073 EVT VT = Op0.getValueType();
20074 assert(VT.isVector() && "Expected a vector type!");
20076 if (isa<BuildVectorSDNode>(Op1))
20077 Op1 = Op1.getOperand(0);
20079 if (!isa<ConstantSDNode>(Op1))
20082 EVT SVT = VT.getVectorElementType();
20083 unsigned SVTBits = SVT.getSizeInBits();
20085 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20086 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20087 uint64_t ShAmt = C.getZExtValue();
20089 // Don't try to convert this shift into a ISD::SRA if the shift
20090 // count is bigger than or equal to the element size.
20091 if (ShAmt >= SVTBits)
20094 // Trivial case: if the shift count is zero, then fold this
20095 // into the first operand.
20099 // Replace this packed shift intrinsic with a target independent
20101 SDValue Splat = DAG.getConstant(C, VT);
20102 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20107 /// PerformMulCombine - Optimize a single multiply with constant into two
20108 /// in order to implement it with two cheaper instructions, e.g.
20109 /// LEA + SHL, LEA + LEA.
20110 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20111 TargetLowering::DAGCombinerInfo &DCI) {
20112 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20115 EVT VT = N->getValueType(0);
20116 if (VT != MVT::i64)
20119 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20122 uint64_t MulAmt = C->getZExtValue();
20123 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20126 uint64_t MulAmt1 = 0;
20127 uint64_t MulAmt2 = 0;
20128 if ((MulAmt % 9) == 0) {
20130 MulAmt2 = MulAmt / 9;
20131 } else if ((MulAmt % 5) == 0) {
20133 MulAmt2 = MulAmt / 5;
20134 } else if ((MulAmt % 3) == 0) {
20136 MulAmt2 = MulAmt / 3;
20139 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20142 if (isPowerOf2_64(MulAmt2) &&
20143 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20144 // If second multiplifer is pow2, issue it first. We want the multiply by
20145 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20147 std::swap(MulAmt1, MulAmt2);
20150 if (isPowerOf2_64(MulAmt1))
20151 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20152 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20154 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20155 DAG.getConstant(MulAmt1, VT));
20157 if (isPowerOf2_64(MulAmt2))
20158 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20159 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20161 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20162 DAG.getConstant(MulAmt2, VT));
20164 // Do not add new nodes to DAG combiner worklist.
20165 DCI.CombineTo(N, NewMul, false);
20170 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20171 SDValue N0 = N->getOperand(0);
20172 SDValue N1 = N->getOperand(1);
20173 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20174 EVT VT = N0.getValueType();
20176 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20177 // since the result of setcc_c is all zero's or all ones.
20178 if (VT.isInteger() && !VT.isVector() &&
20179 N1C && N0.getOpcode() == ISD::AND &&
20180 N0.getOperand(1).getOpcode() == ISD::Constant) {
20181 SDValue N00 = N0.getOperand(0);
20182 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20183 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20184 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20185 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20186 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20187 APInt ShAmt = N1C->getAPIntValue();
20188 Mask = Mask.shl(ShAmt);
20190 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20191 N00, DAG.getConstant(Mask, VT));
20195 // Hardware support for vector shifts is sparse which makes us scalarize the
20196 // vector operations in many cases. Also, on sandybridge ADD is faster than
20198 // (shl V, 1) -> add V,V
20199 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20200 if (SDValue N1Splat = N1BV->getConstantSplatValue()) {
20201 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20202 // We shift all of the values by one. In many cases we do not have
20203 // hardware support for this operation. This is better expressed as an ADD
20205 if (N1Splat.getOpcode() == ISD::Constant &&
20206 cast<ConstantSDNode>(N1Splat)->getZExtValue() == 1)
20207 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20213 /// \brief Returns a vector of 0s if the node in input is a vector logical
20214 /// shift by a constant amount which is known to be bigger than or equal
20215 /// to the vector element size in bits.
20216 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20217 const X86Subtarget *Subtarget) {
20218 EVT VT = N->getValueType(0);
20220 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20221 (!Subtarget->hasInt256() ||
20222 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20225 SDValue Amt = N->getOperand(1);
20227 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20228 if (SDValue AmtSplat = AmtBV->getConstantSplatValue())
20229 if (auto *AmtConst = dyn_cast<ConstantSDNode>(AmtSplat)) {
20230 APInt ShiftAmt = AmtConst->getAPIntValue();
20231 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20233 // SSE2/AVX2 logical shifts always return a vector of 0s
20234 // if the shift amount is bigger than or equal to
20235 // the element size. The constant shift amount will be
20236 // encoded as a 8-bit immediate.
20237 if (ShiftAmt.trunc(8).uge(MaxAmount))
20238 return getZeroVector(VT, Subtarget, DAG, DL);
20244 /// PerformShiftCombine - Combine shifts.
20245 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20246 TargetLowering::DAGCombinerInfo &DCI,
20247 const X86Subtarget *Subtarget) {
20248 if (N->getOpcode() == ISD::SHL) {
20249 SDValue V = PerformSHLCombine(N, DAG);
20250 if (V.getNode()) return V;
20253 if (N->getOpcode() != ISD::SRA) {
20254 // Try to fold this logical shift into a zero vector.
20255 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20256 if (V.getNode()) return V;
20262 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20263 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20264 // and friends. Likewise for OR -> CMPNEQSS.
20265 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20266 TargetLowering::DAGCombinerInfo &DCI,
20267 const X86Subtarget *Subtarget) {
20270 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20271 // we're requiring SSE2 for both.
20272 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20273 SDValue N0 = N->getOperand(0);
20274 SDValue N1 = N->getOperand(1);
20275 SDValue CMP0 = N0->getOperand(1);
20276 SDValue CMP1 = N1->getOperand(1);
20279 // The SETCCs should both refer to the same CMP.
20280 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20283 SDValue CMP00 = CMP0->getOperand(0);
20284 SDValue CMP01 = CMP0->getOperand(1);
20285 EVT VT = CMP00.getValueType();
20287 if (VT == MVT::f32 || VT == MVT::f64) {
20288 bool ExpectingFlags = false;
20289 // Check for any users that want flags:
20290 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20291 !ExpectingFlags && UI != UE; ++UI)
20292 switch (UI->getOpcode()) {
20297 ExpectingFlags = true;
20299 case ISD::CopyToReg:
20300 case ISD::SIGN_EXTEND:
20301 case ISD::ZERO_EXTEND:
20302 case ISD::ANY_EXTEND:
20306 if (!ExpectingFlags) {
20307 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20308 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20310 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20311 X86::CondCode tmp = cc0;
20316 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20317 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20318 // FIXME: need symbolic constants for these magic numbers.
20319 // See X86ATTInstPrinter.cpp:printSSECC().
20320 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20321 if (Subtarget->hasAVX512()) {
20322 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20323 CMP01, DAG.getConstant(x86cc, MVT::i8));
20324 if (N->getValueType(0) != MVT::i1)
20325 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20329 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20330 CMP00.getValueType(), CMP00, CMP01,
20331 DAG.getConstant(x86cc, MVT::i8));
20333 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20334 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20336 if (is64BitFP && !Subtarget->is64Bit()) {
20337 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20338 // 64-bit integer, since that's not a legal type. Since
20339 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20340 // bits, but can do this little dance to extract the lowest 32 bits
20341 // and work with those going forward.
20342 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20344 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20346 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20347 Vector32, DAG.getIntPtrConstant(0));
20351 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20352 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20353 DAG.getConstant(1, IntVT));
20354 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20355 return OneBitOfTruth;
20363 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20364 /// so it can be folded inside ANDNP.
20365 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20366 EVT VT = N->getValueType(0);
20368 // Match direct AllOnes for 128 and 256-bit vectors
20369 if (ISD::isBuildVectorAllOnes(N))
20372 // Look through a bit convert.
20373 if (N->getOpcode() == ISD::BITCAST)
20374 N = N->getOperand(0).getNode();
20376 // Sometimes the operand may come from a insert_subvector building a 256-bit
20378 if (VT.is256BitVector() &&
20379 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20380 SDValue V1 = N->getOperand(0);
20381 SDValue V2 = N->getOperand(1);
20383 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20384 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20385 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20386 ISD::isBuildVectorAllOnes(V2.getNode()))
20393 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20394 // register. In most cases we actually compare or select YMM-sized registers
20395 // and mixing the two types creates horrible code. This method optimizes
20396 // some of the transition sequences.
20397 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20398 TargetLowering::DAGCombinerInfo &DCI,
20399 const X86Subtarget *Subtarget) {
20400 EVT VT = N->getValueType(0);
20401 if (!VT.is256BitVector())
20404 assert((N->getOpcode() == ISD::ANY_EXTEND ||
20405 N->getOpcode() == ISD::ZERO_EXTEND ||
20406 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20408 SDValue Narrow = N->getOperand(0);
20409 EVT NarrowVT = Narrow->getValueType(0);
20410 if (!NarrowVT.is128BitVector())
20413 if (Narrow->getOpcode() != ISD::XOR &&
20414 Narrow->getOpcode() != ISD::AND &&
20415 Narrow->getOpcode() != ISD::OR)
20418 SDValue N0 = Narrow->getOperand(0);
20419 SDValue N1 = Narrow->getOperand(1);
20422 // The Left side has to be a trunc.
20423 if (N0.getOpcode() != ISD::TRUNCATE)
20426 // The type of the truncated inputs.
20427 EVT WideVT = N0->getOperand(0)->getValueType(0);
20431 // The right side has to be a 'trunc' or a constant vector.
20432 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20433 SDValue RHSConstSplat;
20434 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20435 RHSConstSplat = RHSBV->getConstantSplatValue();
20436 if (!RHSTrunc && !RHSConstSplat)
20439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20441 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20444 // Set N0 and N1 to hold the inputs to the new wide operation.
20445 N0 = N0->getOperand(0);
20446 if (RHSConstSplat) {
20447 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20449 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20450 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20451 } else if (RHSTrunc) {
20452 N1 = N1->getOperand(0);
20455 // Generate the wide operation.
20456 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20457 unsigned Opcode = N->getOpcode();
20459 case ISD::ANY_EXTEND:
20461 case ISD::ZERO_EXTEND: {
20462 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20463 APInt Mask = APInt::getAllOnesValue(InBits);
20464 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20465 return DAG.getNode(ISD::AND, DL, VT,
20466 Op, DAG.getConstant(Mask, VT));
20468 case ISD::SIGN_EXTEND:
20469 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20470 Op, DAG.getValueType(NarrowVT));
20472 llvm_unreachable("Unexpected opcode");
20476 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20477 TargetLowering::DAGCombinerInfo &DCI,
20478 const X86Subtarget *Subtarget) {
20479 EVT VT = N->getValueType(0);
20480 if (DCI.isBeforeLegalizeOps())
20483 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20487 // Create BEXTR instructions
20488 // BEXTR is ((X >> imm) & (2**size-1))
20489 if (VT == MVT::i32 || VT == MVT::i64) {
20490 SDValue N0 = N->getOperand(0);
20491 SDValue N1 = N->getOperand(1);
20494 // Check for BEXTR.
20495 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20496 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20497 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20498 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20499 if (MaskNode && ShiftNode) {
20500 uint64_t Mask = MaskNode->getZExtValue();
20501 uint64_t Shift = ShiftNode->getZExtValue();
20502 if (isMask_64(Mask)) {
20503 uint64_t MaskSize = CountPopulation_64(Mask);
20504 if (Shift + MaskSize <= VT.getSizeInBits())
20505 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20506 DAG.getConstant(Shift | (MaskSize << 8), VT));
20514 // Want to form ANDNP nodes:
20515 // 1) In the hopes of then easily combining them with OR and AND nodes
20516 // to form PBLEND/PSIGN.
20517 // 2) To match ANDN packed intrinsics
20518 if (VT != MVT::v2i64 && VT != MVT::v4i64)
20521 SDValue N0 = N->getOperand(0);
20522 SDValue N1 = N->getOperand(1);
20525 // Check LHS for vnot
20526 if (N0.getOpcode() == ISD::XOR &&
20527 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20528 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20529 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20531 // Check RHS for vnot
20532 if (N1.getOpcode() == ISD::XOR &&
20533 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20534 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20535 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20540 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20541 TargetLowering::DAGCombinerInfo &DCI,
20542 const X86Subtarget *Subtarget) {
20543 if (DCI.isBeforeLegalizeOps())
20546 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20550 SDValue N0 = N->getOperand(0);
20551 SDValue N1 = N->getOperand(1);
20552 EVT VT = N->getValueType(0);
20554 // look for psign/blend
20555 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20556 if (!Subtarget->hasSSSE3() ||
20557 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20560 // Canonicalize pandn to RHS
20561 if (N0.getOpcode() == X86ISD::ANDNP)
20563 // or (and (m, y), (pandn m, x))
20564 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20565 SDValue Mask = N1.getOperand(0);
20566 SDValue X = N1.getOperand(1);
20568 if (N0.getOperand(0) == Mask)
20569 Y = N0.getOperand(1);
20570 if (N0.getOperand(1) == Mask)
20571 Y = N0.getOperand(0);
20573 // Check to see if the mask appeared in both the AND and ANDNP and
20577 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20578 // Look through mask bitcast.
20579 if (Mask.getOpcode() == ISD::BITCAST)
20580 Mask = Mask.getOperand(0);
20581 if (X.getOpcode() == ISD::BITCAST)
20582 X = X.getOperand(0);
20583 if (Y.getOpcode() == ISD::BITCAST)
20584 Y = Y.getOperand(0);
20586 EVT MaskVT = Mask.getValueType();
20588 // Validate that the Mask operand is a vector sra node.
20589 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20590 // there is no psrai.b
20591 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20592 unsigned SraAmt = ~0;
20593 if (Mask.getOpcode() == ISD::SRA) {
20594 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20595 if (SDValue AmtSplat = AmtBV->getConstantSplatValue())
20596 if (auto *AmtConst = dyn_cast<ConstantSDNode>(AmtSplat))
20597 SraAmt = AmtConst->getZExtValue();
20598 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20599 SDValue SraC = Mask.getOperand(1);
20600 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
20602 if ((SraAmt + 1) != EltBits)
20607 // Now we know we at least have a plendvb with the mask val. See if
20608 // we can form a psignb/w/d.
20609 // psign = x.type == y.type == mask.type && y = sub(0, x);
20610 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20611 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20612 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20613 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20614 "Unsupported VT for PSIGN");
20615 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20616 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20618 // PBLENDVB only available on SSE 4.1
20619 if (!Subtarget->hasSSE41())
20622 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20624 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20625 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20626 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20627 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20628 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20632 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20635 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20636 MachineFunction &MF = DAG.getMachineFunction();
20637 bool OptForSize = MF.getFunction()->getAttributes().
20638 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20640 // SHLD/SHRD instructions have lower register pressure, but on some
20641 // platforms they have higher latency than the equivalent
20642 // series of shifts/or that would otherwise be generated.
20643 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20644 // have higher latencies and we are not optimizing for size.
20645 if (!OptForSize && Subtarget->isSHLDSlow())
20648 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20650 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20652 if (!N0.hasOneUse() || !N1.hasOneUse())
20655 SDValue ShAmt0 = N0.getOperand(1);
20656 if (ShAmt0.getValueType() != MVT::i8)
20658 SDValue ShAmt1 = N1.getOperand(1);
20659 if (ShAmt1.getValueType() != MVT::i8)
20661 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20662 ShAmt0 = ShAmt0.getOperand(0);
20663 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20664 ShAmt1 = ShAmt1.getOperand(0);
20667 unsigned Opc = X86ISD::SHLD;
20668 SDValue Op0 = N0.getOperand(0);
20669 SDValue Op1 = N1.getOperand(0);
20670 if (ShAmt0.getOpcode() == ISD::SUB) {
20671 Opc = X86ISD::SHRD;
20672 std::swap(Op0, Op1);
20673 std::swap(ShAmt0, ShAmt1);
20676 unsigned Bits = VT.getSizeInBits();
20677 if (ShAmt1.getOpcode() == ISD::SUB) {
20678 SDValue Sum = ShAmt1.getOperand(0);
20679 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20680 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20681 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20682 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20683 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20684 return DAG.getNode(Opc, DL, VT,
20686 DAG.getNode(ISD::TRUNCATE, DL,
20689 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20690 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20692 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20693 return DAG.getNode(Opc, DL, VT,
20694 N0.getOperand(0), N1.getOperand(0),
20695 DAG.getNode(ISD::TRUNCATE, DL,
20702 // Generate NEG and CMOV for integer abs.
20703 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20704 EVT VT = N->getValueType(0);
20706 // Since X86 does not have CMOV for 8-bit integer, we don't convert
20707 // 8-bit integer abs to NEG and CMOV.
20708 if (VT.isInteger() && VT.getSizeInBits() == 8)
20711 SDValue N0 = N->getOperand(0);
20712 SDValue N1 = N->getOperand(1);
20715 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20716 // and change it to SUB and CMOV.
20717 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20718 N0.getOpcode() == ISD::ADD &&
20719 N0.getOperand(1) == N1 &&
20720 N1.getOpcode() == ISD::SRA &&
20721 N1.getOperand(0) == N0.getOperand(0))
20722 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20723 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20724 // Generate SUB & CMOV.
20725 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20726 DAG.getConstant(0, VT), N0.getOperand(0));
20728 SDValue Ops[] = { N0.getOperand(0), Neg,
20729 DAG.getConstant(X86::COND_GE, MVT::i8),
20730 SDValue(Neg.getNode(), 1) };
20731 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20736 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20737 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20738 TargetLowering::DAGCombinerInfo &DCI,
20739 const X86Subtarget *Subtarget) {
20740 if (DCI.isBeforeLegalizeOps())
20743 if (Subtarget->hasCMov()) {
20744 SDValue RV = performIntegerAbsCombine(N, DAG);
20752 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20753 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20754 TargetLowering::DAGCombinerInfo &DCI,
20755 const X86Subtarget *Subtarget) {
20756 LoadSDNode *Ld = cast<LoadSDNode>(N);
20757 EVT RegVT = Ld->getValueType(0);
20758 EVT MemVT = Ld->getMemoryVT();
20760 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20761 unsigned RegSz = RegVT.getSizeInBits();
20763 // On Sandybridge unaligned 256bit loads are inefficient.
20764 ISD::LoadExtType Ext = Ld->getExtensionType();
20765 unsigned Alignment = Ld->getAlignment();
20766 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20767 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20768 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20769 unsigned NumElems = RegVT.getVectorNumElements();
20773 SDValue Ptr = Ld->getBasePtr();
20774 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20776 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20778 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20779 Ld->getPointerInfo(), Ld->isVolatile(),
20780 Ld->isNonTemporal(), Ld->isInvariant(),
20782 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20783 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20784 Ld->getPointerInfo(), Ld->isVolatile(),
20785 Ld->isNonTemporal(), Ld->isInvariant(),
20786 std::min(16U, Alignment));
20787 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20789 Load2.getValue(1));
20791 SDValue NewVec = DAG.getUNDEF(RegVT);
20792 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20793 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20794 return DCI.CombineTo(N, NewVec, TF, true);
20797 // If this is a vector EXT Load then attempt to optimize it using a
20798 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20799 // expansion is still better than scalar code.
20800 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20801 // emit a shuffle and a arithmetic shift.
20802 // TODO: It is possible to support ZExt by zeroing the undef values
20803 // during the shuffle phase or after the shuffle.
20804 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20805 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20806 assert(MemVT != RegVT && "Cannot extend to the same type");
20807 assert(MemVT.isVector() && "Must load a vector from memory");
20809 unsigned NumElems = RegVT.getVectorNumElements();
20810 unsigned MemSz = MemVT.getSizeInBits();
20811 assert(RegSz > MemSz && "Register size must be greater than the mem size");
20813 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20816 // All sizes must be a power of two.
20817 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20820 // Attempt to load the original value using scalar loads.
20821 // Find the largest scalar type that divides the total loaded size.
20822 MVT SclrLoadTy = MVT::i8;
20823 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20824 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20825 MVT Tp = (MVT::SimpleValueType)tp;
20826 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20831 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20832 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20834 SclrLoadTy = MVT::f64;
20836 // Calculate the number of scalar loads that we need to perform
20837 // in order to load our vector from memory.
20838 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20839 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20842 unsigned loadRegZize = RegSz;
20843 if (Ext == ISD::SEXTLOAD && RegSz == 256)
20846 // Represent our vector as a sequence of elements which are the
20847 // largest scalar that we can load.
20848 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20849 loadRegZize/SclrLoadTy.getSizeInBits());
20851 // Represent the data using the same element type that is stored in
20852 // memory. In practice, we ''widen'' MemVT.
20854 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20855 loadRegZize/MemVT.getScalarType().getSizeInBits());
20857 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20858 "Invalid vector type");
20860 // We can't shuffle using an illegal type.
20861 if (!TLI.isTypeLegal(WideVecVT))
20864 SmallVector<SDValue, 8> Chains;
20865 SDValue Ptr = Ld->getBasePtr();
20866 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20867 TLI.getPointerTy());
20868 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20870 for (unsigned i = 0; i < NumLoads; ++i) {
20871 // Perform a single load.
20872 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20873 Ptr, Ld->getPointerInfo(),
20874 Ld->isVolatile(), Ld->isNonTemporal(),
20875 Ld->isInvariant(), Ld->getAlignment());
20876 Chains.push_back(ScalarLoad.getValue(1));
20877 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20878 // another round of DAGCombining.
20880 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20882 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20883 ScalarLoad, DAG.getIntPtrConstant(i));
20885 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20888 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20890 // Bitcast the loaded value to a vector of the original element type, in
20891 // the size of the target vector type.
20892 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20893 unsigned SizeRatio = RegSz/MemSz;
20895 if (Ext == ISD::SEXTLOAD) {
20896 // If we have SSE4.1 we can directly emit a VSEXT node.
20897 if (Subtarget->hasSSE41()) {
20898 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20899 return DCI.CombineTo(N, Sext, TF, true);
20902 // Otherwise we'll shuffle the small elements in the high bits of the
20903 // larger type and perform an arithmetic shift. If the shift is not legal
20904 // it's better to scalarize.
20905 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20908 // Redistribute the loaded elements into the different locations.
20909 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20910 for (unsigned i = 0; i != NumElems; ++i)
20911 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20913 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20914 DAG.getUNDEF(WideVecVT),
20917 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20919 // Build the arithmetic shift.
20920 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20921 MemVT.getVectorElementType().getSizeInBits();
20922 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20923 DAG.getConstant(Amt, RegVT));
20925 return DCI.CombineTo(N, Shuff, TF, true);
20928 // Redistribute the loaded elements into the different locations.
20929 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20930 for (unsigned i = 0; i != NumElems; ++i)
20931 ShuffleVec[i*SizeRatio] = i;
20933 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20934 DAG.getUNDEF(WideVecVT),
20937 // Bitcast to the requested type.
20938 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20939 // Replace the original load with the new sequence
20940 // and return the new chain.
20941 return DCI.CombineTo(N, Shuff, TF, true);
20947 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20948 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20949 const X86Subtarget *Subtarget) {
20950 StoreSDNode *St = cast<StoreSDNode>(N);
20951 EVT VT = St->getValue().getValueType();
20952 EVT StVT = St->getMemoryVT();
20954 SDValue StoredVal = St->getOperand(1);
20955 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20957 // If we are saving a concatenation of two XMM registers, perform two stores.
20958 // On Sandy Bridge, 256-bit memory operations are executed by two
20959 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20960 // memory operation.
20961 unsigned Alignment = St->getAlignment();
20962 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20963 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20964 StVT == VT && !IsAligned) {
20965 unsigned NumElems = VT.getVectorNumElements();
20969 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20970 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20972 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20973 SDValue Ptr0 = St->getBasePtr();
20974 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20976 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20977 St->getPointerInfo(), St->isVolatile(),
20978 St->isNonTemporal(), Alignment);
20979 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20980 St->getPointerInfo(), St->isVolatile(),
20981 St->isNonTemporal(),
20982 std::min(16U, Alignment));
20983 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20986 // Optimize trunc store (of multiple scalars) to shuffle and store.
20987 // First, pack all of the elements in one place. Next, store to memory
20988 // in fewer chunks.
20989 if (St->isTruncatingStore() && VT.isVector()) {
20990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20991 unsigned NumElems = VT.getVectorNumElements();
20992 assert(StVT != VT && "Cannot truncate to the same type");
20993 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20994 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20996 // From, To sizes and ElemCount must be pow of two
20997 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20998 // We are going to use the original vector elt for storing.
20999 // Accumulated smaller vector elements must be a multiple of the store size.
21000 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21002 unsigned SizeRatio = FromSz / ToSz;
21004 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21006 // Create a type on which we perform the shuffle
21007 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21008 StVT.getScalarType(), NumElems*SizeRatio);
21010 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21012 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21013 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21014 for (unsigned i = 0; i != NumElems; ++i)
21015 ShuffleVec[i] = i * SizeRatio;
21017 // Can't shuffle using an illegal type.
21018 if (!TLI.isTypeLegal(WideVecVT))
21021 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21022 DAG.getUNDEF(WideVecVT),
21024 // At this point all of the data is stored at the bottom of the
21025 // register. We now need to save it to mem.
21027 // Find the largest store unit
21028 MVT StoreType = MVT::i8;
21029 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21030 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21031 MVT Tp = (MVT::SimpleValueType)tp;
21032 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21036 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21037 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21038 (64 <= NumElems * ToSz))
21039 StoreType = MVT::f64;
21041 // Bitcast the original vector into a vector of store-size units
21042 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21043 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21044 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21045 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21046 SmallVector<SDValue, 8> Chains;
21047 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21048 TLI.getPointerTy());
21049 SDValue Ptr = St->getBasePtr();
21051 // Perform one or more big stores into memory.
21052 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21053 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21054 StoreType, ShuffWide,
21055 DAG.getIntPtrConstant(i));
21056 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21057 St->getPointerInfo(), St->isVolatile(),
21058 St->isNonTemporal(), St->getAlignment());
21059 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21060 Chains.push_back(Ch);
21063 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21066 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21067 // the FP state in cases where an emms may be missing.
21068 // A preferable solution to the general problem is to figure out the right
21069 // places to insert EMMS. This qualifies as a quick hack.
21071 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21072 if (VT.getSizeInBits() != 64)
21075 const Function *F = DAG.getMachineFunction().getFunction();
21076 bool NoImplicitFloatOps = F->getAttributes().
21077 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21078 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21079 && Subtarget->hasSSE2();
21080 if ((VT.isVector() ||
21081 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21082 isa<LoadSDNode>(St->getValue()) &&
21083 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21084 St->getChain().hasOneUse() && !St->isVolatile()) {
21085 SDNode* LdVal = St->getValue().getNode();
21086 LoadSDNode *Ld = nullptr;
21087 int TokenFactorIndex = -1;
21088 SmallVector<SDValue, 8> Ops;
21089 SDNode* ChainVal = St->getChain().getNode();
21090 // Must be a store of a load. We currently handle two cases: the load
21091 // is a direct child, and it's under an intervening TokenFactor. It is
21092 // possible to dig deeper under nested TokenFactors.
21093 if (ChainVal == LdVal)
21094 Ld = cast<LoadSDNode>(St->getChain());
21095 else if (St->getValue().hasOneUse() &&
21096 ChainVal->getOpcode() == ISD::TokenFactor) {
21097 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21098 if (ChainVal->getOperand(i).getNode() == LdVal) {
21099 TokenFactorIndex = i;
21100 Ld = cast<LoadSDNode>(St->getValue());
21102 Ops.push_back(ChainVal->getOperand(i));
21106 if (!Ld || !ISD::isNormalLoad(Ld))
21109 // If this is not the MMX case, i.e. we are just turning i64 load/store
21110 // into f64 load/store, avoid the transformation if there are multiple
21111 // uses of the loaded value.
21112 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21117 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21118 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21120 if (Subtarget->is64Bit() || F64IsLegal) {
21121 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21122 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21123 Ld->getPointerInfo(), Ld->isVolatile(),
21124 Ld->isNonTemporal(), Ld->isInvariant(),
21125 Ld->getAlignment());
21126 SDValue NewChain = NewLd.getValue(1);
21127 if (TokenFactorIndex != -1) {
21128 Ops.push_back(NewChain);
21129 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21131 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21132 St->getPointerInfo(),
21133 St->isVolatile(), St->isNonTemporal(),
21134 St->getAlignment());
21137 // Otherwise, lower to two pairs of 32-bit loads / stores.
21138 SDValue LoAddr = Ld->getBasePtr();
21139 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21140 DAG.getConstant(4, MVT::i32));
21142 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21143 Ld->getPointerInfo(),
21144 Ld->isVolatile(), Ld->isNonTemporal(),
21145 Ld->isInvariant(), Ld->getAlignment());
21146 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21147 Ld->getPointerInfo().getWithOffset(4),
21148 Ld->isVolatile(), Ld->isNonTemporal(),
21150 MinAlign(Ld->getAlignment(), 4));
21152 SDValue NewChain = LoLd.getValue(1);
21153 if (TokenFactorIndex != -1) {
21154 Ops.push_back(LoLd);
21155 Ops.push_back(HiLd);
21156 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21159 LoAddr = St->getBasePtr();
21160 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21161 DAG.getConstant(4, MVT::i32));
21163 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21164 St->getPointerInfo(),
21165 St->isVolatile(), St->isNonTemporal(),
21166 St->getAlignment());
21167 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21168 St->getPointerInfo().getWithOffset(4),
21170 St->isNonTemporal(),
21171 MinAlign(St->getAlignment(), 4));
21172 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21177 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21178 /// and return the operands for the horizontal operation in LHS and RHS. A
21179 /// horizontal operation performs the binary operation on successive elements
21180 /// of its first operand, then on successive elements of its second operand,
21181 /// returning the resulting values in a vector. For example, if
21182 /// A = < float a0, float a1, float a2, float a3 >
21184 /// B = < float b0, float b1, float b2, float b3 >
21185 /// then the result of doing a horizontal operation on A and B is
21186 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21187 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21188 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21189 /// set to A, RHS to B, and the routine returns 'true'.
21190 /// Note that the binary operation should have the property that if one of the
21191 /// operands is UNDEF then the result is UNDEF.
21192 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21193 // Look for the following pattern: if
21194 // A = < float a0, float a1, float a2, float a3 >
21195 // B = < float b0, float b1, float b2, float b3 >
21197 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21198 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21199 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21200 // which is A horizontal-op B.
21202 // At least one of the operands should be a vector shuffle.
21203 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21204 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21207 MVT VT = LHS.getSimpleValueType();
21209 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21210 "Unsupported vector type for horizontal add/sub");
21212 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21213 // operate independently on 128-bit lanes.
21214 unsigned NumElts = VT.getVectorNumElements();
21215 unsigned NumLanes = VT.getSizeInBits()/128;
21216 unsigned NumLaneElts = NumElts / NumLanes;
21217 assert((NumLaneElts % 2 == 0) &&
21218 "Vector type should have an even number of elements in each lane");
21219 unsigned HalfLaneElts = NumLaneElts/2;
21221 // View LHS in the form
21222 // LHS = VECTOR_SHUFFLE A, B, LMask
21223 // If LHS is not a shuffle then pretend it is the shuffle
21224 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21225 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21228 SmallVector<int, 16> LMask(NumElts);
21229 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21230 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21231 A = LHS.getOperand(0);
21232 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21233 B = LHS.getOperand(1);
21234 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21235 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21237 if (LHS.getOpcode() != ISD::UNDEF)
21239 for (unsigned i = 0; i != NumElts; ++i)
21243 // Likewise, view RHS in the form
21244 // RHS = VECTOR_SHUFFLE C, D, RMask
21246 SmallVector<int, 16> RMask(NumElts);
21247 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21248 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21249 C = RHS.getOperand(0);
21250 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21251 D = RHS.getOperand(1);
21252 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21253 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21255 if (RHS.getOpcode() != ISD::UNDEF)
21257 for (unsigned i = 0; i != NumElts; ++i)
21261 // Check that the shuffles are both shuffling the same vectors.
21262 if (!(A == C && B == D) && !(A == D && B == C))
21265 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21266 if (!A.getNode() && !B.getNode())
21269 // If A and B occur in reverse order in RHS, then "swap" them (which means
21270 // rewriting the mask).
21272 CommuteVectorShuffleMask(RMask, NumElts);
21274 // At this point LHS and RHS are equivalent to
21275 // LHS = VECTOR_SHUFFLE A, B, LMask
21276 // RHS = VECTOR_SHUFFLE A, B, RMask
21277 // Check that the masks correspond to performing a horizontal operation.
21278 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21279 for (unsigned i = 0; i != NumLaneElts; ++i) {
21280 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21282 // Ignore any UNDEF components.
21283 if (LIdx < 0 || RIdx < 0 ||
21284 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21285 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21288 // Check that successive elements are being operated on. If not, this is
21289 // not a horizontal operation.
21290 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21291 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21292 if (!(LIdx == Index && RIdx == Index + 1) &&
21293 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21298 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21299 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21303 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21304 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21305 const X86Subtarget *Subtarget) {
21306 EVT VT = N->getValueType(0);
21307 SDValue LHS = N->getOperand(0);
21308 SDValue RHS = N->getOperand(1);
21310 // Try to synthesize horizontal adds from adds of shuffles.
21311 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21312 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21313 isHorizontalBinOp(LHS, RHS, true))
21314 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21318 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21319 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21320 const X86Subtarget *Subtarget) {
21321 EVT VT = N->getValueType(0);
21322 SDValue LHS = N->getOperand(0);
21323 SDValue RHS = N->getOperand(1);
21325 // Try to synthesize horizontal subs from subs of shuffles.
21326 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21327 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21328 isHorizontalBinOp(LHS, RHS, false))
21329 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21333 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21334 /// X86ISD::FXOR nodes.
21335 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21336 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21337 // F[X]OR(0.0, x) -> x
21338 // F[X]OR(x, 0.0) -> x
21339 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21340 if (C->getValueAPF().isPosZero())
21341 return N->getOperand(1);
21342 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21343 if (C->getValueAPF().isPosZero())
21344 return N->getOperand(0);
21348 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21349 /// X86ISD::FMAX nodes.
21350 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21351 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21353 // Only perform optimizations if UnsafeMath is used.
21354 if (!DAG.getTarget().Options.UnsafeFPMath)
21357 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21358 // into FMINC and FMAXC, which are Commutative operations.
21359 unsigned NewOp = 0;
21360 switch (N->getOpcode()) {
21361 default: llvm_unreachable("unknown opcode");
21362 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21363 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21366 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21367 N->getOperand(0), N->getOperand(1));
21370 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21371 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21372 // FAND(0.0, x) -> 0.0
21373 // FAND(x, 0.0) -> 0.0
21374 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21375 if (C->getValueAPF().isPosZero())
21376 return N->getOperand(0);
21377 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21378 if (C->getValueAPF().isPosZero())
21379 return N->getOperand(1);
21383 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21384 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21385 // FANDN(x, 0.0) -> 0.0
21386 // FANDN(0.0, x) -> x
21387 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21388 if (C->getValueAPF().isPosZero())
21389 return N->getOperand(1);
21390 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21391 if (C->getValueAPF().isPosZero())
21392 return N->getOperand(1);
21396 static SDValue PerformBTCombine(SDNode *N,
21398 TargetLowering::DAGCombinerInfo &DCI) {
21399 // BT ignores high bits in the bit index operand.
21400 SDValue Op1 = N->getOperand(1);
21401 if (Op1.hasOneUse()) {
21402 unsigned BitWidth = Op1.getValueSizeInBits();
21403 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21404 APInt KnownZero, KnownOne;
21405 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21406 !DCI.isBeforeLegalizeOps());
21407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21408 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21409 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21410 DCI.CommitTargetLoweringOpt(TLO);
21415 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21416 SDValue Op = N->getOperand(0);
21417 if (Op.getOpcode() == ISD::BITCAST)
21418 Op = Op.getOperand(0);
21419 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21420 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21421 VT.getVectorElementType().getSizeInBits() ==
21422 OpVT.getVectorElementType().getSizeInBits()) {
21423 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21428 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21429 const X86Subtarget *Subtarget) {
21430 EVT VT = N->getValueType(0);
21431 if (!VT.isVector())
21434 SDValue N0 = N->getOperand(0);
21435 SDValue N1 = N->getOperand(1);
21436 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21439 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21440 // both SSE and AVX2 since there is no sign-extended shift right
21441 // operation on a vector with 64-bit elements.
21442 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21443 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21444 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21445 N0.getOpcode() == ISD::SIGN_EXTEND)) {
21446 SDValue N00 = N0.getOperand(0);
21448 // EXTLOAD has a better solution on AVX2,
21449 // it may be replaced with X86ISD::VSEXT node.
21450 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21451 if (!ISD::isNormalLoad(N00.getNode()))
21454 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21455 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21457 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21463 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21464 TargetLowering::DAGCombinerInfo &DCI,
21465 const X86Subtarget *Subtarget) {
21466 if (!DCI.isBeforeLegalizeOps())
21469 if (!Subtarget->hasFp256())
21472 EVT VT = N->getValueType(0);
21473 if (VT.isVector() && VT.getSizeInBits() == 256) {
21474 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21482 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21483 const X86Subtarget* Subtarget) {
21485 EVT VT = N->getValueType(0);
21487 // Let legalize expand this if it isn't a legal type yet.
21488 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21491 EVT ScalarVT = VT.getScalarType();
21492 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21493 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21496 SDValue A = N->getOperand(0);
21497 SDValue B = N->getOperand(1);
21498 SDValue C = N->getOperand(2);
21500 bool NegA = (A.getOpcode() == ISD::FNEG);
21501 bool NegB = (B.getOpcode() == ISD::FNEG);
21502 bool NegC = (C.getOpcode() == ISD::FNEG);
21504 // Negative multiplication when NegA xor NegB
21505 bool NegMul = (NegA != NegB);
21507 A = A.getOperand(0);
21509 B = B.getOperand(0);
21511 C = C.getOperand(0);
21515 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21517 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21519 return DAG.getNode(Opcode, dl, VT, A, B, C);
21522 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21523 TargetLowering::DAGCombinerInfo &DCI,
21524 const X86Subtarget *Subtarget) {
21525 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
21526 // (and (i32 x86isd::setcc_carry), 1)
21527 // This eliminates the zext. This transformation is necessary because
21528 // ISD::SETCC is always legalized to i8.
21530 SDValue N0 = N->getOperand(0);
21531 EVT VT = N->getValueType(0);
21533 if (N0.getOpcode() == ISD::AND &&
21535 N0.getOperand(0).hasOneUse()) {
21536 SDValue N00 = N0.getOperand(0);
21537 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21539 if (!C || C->getZExtValue() != 1)
21541 return DAG.getNode(ISD::AND, dl, VT,
21542 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21543 N00.getOperand(0), N00.getOperand(1)),
21544 DAG.getConstant(1, VT));
21548 if (N0.getOpcode() == ISD::TRUNCATE &&
21550 N0.getOperand(0).hasOneUse()) {
21551 SDValue N00 = N0.getOperand(0);
21552 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21553 return DAG.getNode(ISD::AND, dl, VT,
21554 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21555 N00.getOperand(0), N00.getOperand(1)),
21556 DAG.getConstant(1, VT));
21559 if (VT.is256BitVector()) {
21560 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21568 // Optimize x == -y --> x+y == 0
21569 // x != -y --> x+y != 0
21570 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21571 const X86Subtarget* Subtarget) {
21572 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21573 SDValue LHS = N->getOperand(0);
21574 SDValue RHS = N->getOperand(1);
21575 EVT VT = N->getValueType(0);
21578 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21579 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21580 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21581 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21582 LHS.getValueType(), RHS, LHS.getOperand(1));
21583 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21584 addV, DAG.getConstant(0, addV.getValueType()), CC);
21586 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21587 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21588 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21589 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21590 RHS.getValueType(), LHS, RHS.getOperand(1));
21591 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21592 addV, DAG.getConstant(0, addV.getValueType()), CC);
21595 if (VT.getScalarType() == MVT::i1) {
21596 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21597 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21598 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21599 if (!IsSEXT0 && !IsVZero0)
21601 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21602 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21603 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21605 if (!IsSEXT1 && !IsVZero1)
21608 if (IsSEXT0 && IsVZero1) {
21609 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21610 if (CC == ISD::SETEQ)
21611 return DAG.getNOT(DL, LHS.getOperand(0), VT);
21612 return LHS.getOperand(0);
21614 if (IsSEXT1 && IsVZero0) {
21615 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21616 if (CC == ISD::SETEQ)
21617 return DAG.getNOT(DL, RHS.getOperand(0), VT);
21618 return RHS.getOperand(0);
21625 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21626 const X86Subtarget *Subtarget) {
21628 MVT VT = N->getOperand(1)->getSimpleValueType(0);
21629 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21630 "X86insertps is only defined for v4x32");
21632 SDValue Ld = N->getOperand(1);
21633 if (MayFoldLoad(Ld)) {
21634 // Extract the countS bits from the immediate so we can get the proper
21635 // address when narrowing the vector load to a specific element.
21636 // When the second source op is a memory address, interps doesn't use
21637 // countS and just gets an f32 from that address.
21638 unsigned DestIndex =
21639 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21640 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21644 // Create this as a scalar to vector to match the instruction pattern.
21645 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21646 // countS bits are ignored when loading from memory on insertps, which
21647 // means we don't need to explicitly set them to 0.
21648 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21649 LoadScalarToVector, N->getOperand(2));
21652 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21653 // as "sbb reg,reg", since it can be extended without zext and produces
21654 // an all-ones bit which is more useful than 0/1 in some cases.
21655 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21658 return DAG.getNode(ISD::AND, DL, VT,
21659 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21660 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21661 DAG.getConstant(1, VT));
21662 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21663 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21664 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21665 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21668 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21669 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21670 TargetLowering::DAGCombinerInfo &DCI,
21671 const X86Subtarget *Subtarget) {
21673 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21674 SDValue EFLAGS = N->getOperand(1);
21676 if (CC == X86::COND_A) {
21677 // Try to convert COND_A into COND_B in an attempt to facilitate
21678 // materializing "setb reg".
21680 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21681 // cannot take an immediate as its first operand.
21683 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21684 EFLAGS.getValueType().isInteger() &&
21685 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21686 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21687 EFLAGS.getNode()->getVTList(),
21688 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21689 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21690 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21694 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21695 // a zext and produces an all-ones bit which is more useful than 0/1 in some
21697 if (CC == X86::COND_B)
21698 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21702 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21703 if (Flags.getNode()) {
21704 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21705 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21711 // Optimize branch condition evaluation.
21713 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21714 TargetLowering::DAGCombinerInfo &DCI,
21715 const X86Subtarget *Subtarget) {
21717 SDValue Chain = N->getOperand(0);
21718 SDValue Dest = N->getOperand(1);
21719 SDValue EFLAGS = N->getOperand(3);
21720 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21724 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21725 if (Flags.getNode()) {
21726 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21727 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21734 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21735 const X86TargetLowering *XTLI) {
21736 SDValue Op0 = N->getOperand(0);
21737 EVT InVT = Op0->getValueType(0);
21739 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21740 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21742 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21743 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21744 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21747 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21748 // a 32-bit target where SSE doesn't support i64->FP operations.
21749 if (Op0.getOpcode() == ISD::LOAD) {
21750 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21751 EVT VT = Ld->getValueType(0);
21752 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21753 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21754 !XTLI->getSubtarget()->is64Bit() &&
21756 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21757 Ld->getChain(), Op0, DAG);
21758 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21765 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21766 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21767 X86TargetLowering::DAGCombinerInfo &DCI) {
21768 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21769 // the result is either zero or one (depending on the input carry bit).
21770 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21771 if (X86::isZeroNode(N->getOperand(0)) &&
21772 X86::isZeroNode(N->getOperand(1)) &&
21773 // We don't have a good way to replace an EFLAGS use, so only do this when
21775 SDValue(N, 1).use_empty()) {
21777 EVT VT = N->getValueType(0);
21778 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21779 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21780 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21781 DAG.getConstant(X86::COND_B,MVT::i8),
21783 DAG.getConstant(1, VT));
21784 return DCI.CombineTo(N, Res1, CarryOut);
21790 // fold (add Y, (sete X, 0)) -> adc 0, Y
21791 // (add Y, (setne X, 0)) -> sbb -1, Y
21792 // (sub (sete X, 0), Y) -> sbb 0, Y
21793 // (sub (setne X, 0), Y) -> adc -1, Y
21794 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21797 // Look through ZExts.
21798 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21799 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21802 SDValue SetCC = Ext.getOperand(0);
21803 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21806 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21807 if (CC != X86::COND_E && CC != X86::COND_NE)
21810 SDValue Cmp = SetCC.getOperand(1);
21811 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21812 !X86::isZeroNode(Cmp.getOperand(1)) ||
21813 !Cmp.getOperand(0).getValueType().isInteger())
21816 SDValue CmpOp0 = Cmp.getOperand(0);
21817 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21818 DAG.getConstant(1, CmpOp0.getValueType()));
21820 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21821 if (CC == X86::COND_NE)
21822 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21823 DL, OtherVal.getValueType(), OtherVal,
21824 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21825 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21826 DL, OtherVal.getValueType(), OtherVal,
21827 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21830 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21831 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21832 const X86Subtarget *Subtarget) {
21833 EVT VT = N->getValueType(0);
21834 SDValue Op0 = N->getOperand(0);
21835 SDValue Op1 = N->getOperand(1);
21837 // Try to synthesize horizontal adds from adds of shuffles.
21838 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21839 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21840 isHorizontalBinOp(Op0, Op1, true))
21841 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21843 return OptimizeConditionalInDecrement(N, DAG);
21846 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21847 const X86Subtarget *Subtarget) {
21848 SDValue Op0 = N->getOperand(0);
21849 SDValue Op1 = N->getOperand(1);
21851 // X86 can't encode an immediate LHS of a sub. See if we can push the
21852 // negation into a preceding instruction.
21853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21854 // If the RHS of the sub is a XOR with one use and a constant, invert the
21855 // immediate. Then add one to the LHS of the sub so we can turn
21856 // X-Y -> X+~Y+1, saving one register.
21857 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21858 isa<ConstantSDNode>(Op1.getOperand(1))) {
21859 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21860 EVT VT = Op0.getValueType();
21861 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21863 DAG.getConstant(~XorC, VT));
21864 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21865 DAG.getConstant(C->getAPIntValue()+1, VT));
21869 // Try to synthesize horizontal adds from adds of shuffles.
21870 EVT VT = N->getValueType(0);
21871 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21872 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21873 isHorizontalBinOp(Op0, Op1, true))
21874 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21876 return OptimizeConditionalInDecrement(N, DAG);
21879 /// performVZEXTCombine - Performs build vector combines
21880 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21881 TargetLowering::DAGCombinerInfo &DCI,
21882 const X86Subtarget *Subtarget) {
21883 // (vzext (bitcast (vzext (x)) -> (vzext x)
21884 SDValue In = N->getOperand(0);
21885 while (In.getOpcode() == ISD::BITCAST)
21886 In = In.getOperand(0);
21888 if (In.getOpcode() != X86ISD::VZEXT)
21891 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21895 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21896 DAGCombinerInfo &DCI) const {
21897 SelectionDAG &DAG = DCI.DAG;
21898 switch (N->getOpcode()) {
21900 case ISD::EXTRACT_VECTOR_ELT:
21901 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21903 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21904 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21905 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
21906 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
21907 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
21908 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
21911 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
21912 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
21913 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
21914 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
21915 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
21916 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
21917 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
21918 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
21919 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
21921 case X86ISD::FOR: return PerformFORCombine(N, DAG);
21923 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
21924 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
21925 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
21926 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
21927 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
21928 case ISD::ANY_EXTEND:
21929 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
21930 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
21931 case ISD::SIGN_EXTEND_INREG:
21932 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21933 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21934 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
21935 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21936 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21937 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
21938 case X86ISD::SHUFP: // Handle all target specific shuffles
21939 case X86ISD::PALIGNR:
21940 case X86ISD::UNPCKH:
21941 case X86ISD::UNPCKL:
21942 case X86ISD::MOVHLPS:
21943 case X86ISD::MOVLHPS:
21944 case X86ISD::PSHUFD:
21945 case X86ISD::PSHUFHW:
21946 case X86ISD::PSHUFLW:
21947 case X86ISD::MOVSS:
21948 case X86ISD::MOVSD:
21949 case X86ISD::VPERMILP:
21950 case X86ISD::VPERM2X128:
21951 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21952 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
21953 case ISD::INTRINSIC_WO_CHAIN:
21954 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21955 case X86ISD::INSERTPS:
21956 return PerformINSERTPSCombine(N, DAG, Subtarget);
21957 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21963 /// isTypeDesirableForOp - Return true if the target has native support for
21964 /// the specified value type and it is 'desirable' to use the type for the
21965 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21966 /// instruction encodings are longer and some i16 instructions are slow.
21967 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21968 if (!isTypeLegal(VT))
21970 if (VT != MVT::i16)
21977 case ISD::SIGN_EXTEND:
21978 case ISD::ZERO_EXTEND:
21979 case ISD::ANY_EXTEND:
21992 /// IsDesirableToPromoteOp - This method query the target whether it is
21993 /// beneficial for dag combiner to promote the specified node. If true, it
21994 /// should return the desired promotion type by reference.
21995 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21996 EVT VT = Op.getValueType();
21997 if (VT != MVT::i16)
22000 bool Promote = false;
22001 bool Commute = false;
22002 switch (Op.getOpcode()) {
22005 LoadSDNode *LD = cast<LoadSDNode>(Op);
22006 // If the non-extending load has a single use and it's not live out, then it
22007 // might be folded.
22008 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22009 Op.hasOneUse()*/) {
22010 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22011 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22012 // The only case where we'd want to promote LOAD (rather then it being
22013 // promoted as an operand is when it's only use is liveout.
22014 if (UI->getOpcode() != ISD::CopyToReg)
22021 case ISD::SIGN_EXTEND:
22022 case ISD::ZERO_EXTEND:
22023 case ISD::ANY_EXTEND:
22028 SDValue N0 = Op.getOperand(0);
22029 // Look out for (store (shl (load), x)).
22030 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22043 SDValue N0 = Op.getOperand(0);
22044 SDValue N1 = Op.getOperand(1);
22045 if (!Commute && MayFoldLoad(N1))
22047 // Avoid disabling potential load folding opportunities.
22048 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22050 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22060 //===----------------------------------------------------------------------===//
22061 // X86 Inline Assembly Support
22062 //===----------------------------------------------------------------------===//
22065 // Helper to match a string separated by whitespace.
22066 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22067 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22069 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22070 StringRef piece(*args[i]);
22071 if (!s.startswith(piece)) // Check if the piece matches.
22074 s = s.substr(piece.size());
22075 StringRef::size_type pos = s.find_first_not_of(" \t");
22076 if (pos == 0) // We matched a prefix.
22084 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22087 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22089 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22090 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22091 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22092 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22094 if (AsmPieces.size() == 3)
22096 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22103 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22104 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22106 std::string AsmStr = IA->getAsmString();
22108 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22109 if (!Ty || Ty->getBitWidth() % 16 != 0)
22112 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22113 SmallVector<StringRef, 4> AsmPieces;
22114 SplitString(AsmStr, AsmPieces, ";\n");
22116 switch (AsmPieces.size()) {
22117 default: return false;
22119 // FIXME: this should verify that we are targeting a 486 or better. If not,
22120 // we will turn this bswap into something that will be lowered to logical
22121 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22122 // lower so don't worry about this.
22124 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22125 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22126 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22127 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22128 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22129 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22130 // No need to check constraints, nothing other than the equivalent of
22131 // "=r,0" would be valid here.
22132 return IntrinsicLowering::LowerToByteSwap(CI);
22135 // rorw $$8, ${0:w} --> llvm.bswap.i16
22136 if (CI->getType()->isIntegerTy(16) &&
22137 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22138 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22139 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22141 const std::string &ConstraintsStr = IA->getConstraintString();
22142 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22143 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22144 if (clobbersFlagRegisters(AsmPieces))
22145 return IntrinsicLowering::LowerToByteSwap(CI);
22149 if (CI->getType()->isIntegerTy(32) &&
22150 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22151 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22152 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22153 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22155 const std::string &ConstraintsStr = IA->getConstraintString();
22156 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22157 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22158 if (clobbersFlagRegisters(AsmPieces))
22159 return IntrinsicLowering::LowerToByteSwap(CI);
22162 if (CI->getType()->isIntegerTy(64)) {
22163 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22164 if (Constraints.size() >= 2 &&
22165 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22166 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22167 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22168 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22169 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22170 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22171 return IntrinsicLowering::LowerToByteSwap(CI);
22179 /// getConstraintType - Given a constraint letter, return the type of
22180 /// constraint it is for this target.
22181 X86TargetLowering::ConstraintType
22182 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22183 if (Constraint.size() == 1) {
22184 switch (Constraint[0]) {
22195 return C_RegisterClass;
22219 return TargetLowering::getConstraintType(Constraint);
22222 /// Examine constraint type and operand type and determine a weight value.
22223 /// This object must already have been set up with the operand type
22224 /// and the current alternative constraint selected.
22225 TargetLowering::ConstraintWeight
22226 X86TargetLowering::getSingleConstraintMatchWeight(
22227 AsmOperandInfo &info, const char *constraint) const {
22228 ConstraintWeight weight = CW_Invalid;
22229 Value *CallOperandVal = info.CallOperandVal;
22230 // If we don't have a value, we can't do a match,
22231 // but allow it at the lowest weight.
22232 if (!CallOperandVal)
22234 Type *type = CallOperandVal->getType();
22235 // Look at the constraint type.
22236 switch (*constraint) {
22238 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22249 if (CallOperandVal->getType()->isIntegerTy())
22250 weight = CW_SpecificReg;
22255 if (type->isFloatingPointTy())
22256 weight = CW_SpecificReg;
22259 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22260 weight = CW_SpecificReg;
22264 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22265 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22266 weight = CW_Register;
22269 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22270 if (C->getZExtValue() <= 31)
22271 weight = CW_Constant;
22275 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22276 if (C->getZExtValue() <= 63)
22277 weight = CW_Constant;
22281 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22282 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22283 weight = CW_Constant;
22287 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22288 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22289 weight = CW_Constant;
22293 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22294 if (C->getZExtValue() <= 3)
22295 weight = CW_Constant;
22299 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22300 if (C->getZExtValue() <= 0xff)
22301 weight = CW_Constant;
22306 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22307 weight = CW_Constant;
22311 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22312 if ((C->getSExtValue() >= -0x80000000LL) &&
22313 (C->getSExtValue() <= 0x7fffffffLL))
22314 weight = CW_Constant;
22318 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22319 if (C->getZExtValue() <= 0xffffffff)
22320 weight = CW_Constant;
22327 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22328 /// with another that has more specific requirements based on the type of the
22329 /// corresponding operand.
22330 const char *X86TargetLowering::
22331 LowerXConstraint(EVT ConstraintVT) const {
22332 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22333 // 'f' like normal targets.
22334 if (ConstraintVT.isFloatingPoint()) {
22335 if (Subtarget->hasSSE2())
22337 if (Subtarget->hasSSE1())
22341 return TargetLowering::LowerXConstraint(ConstraintVT);
22344 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22345 /// vector. If it is invalid, don't add anything to Ops.
22346 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22347 std::string &Constraint,
22348 std::vector<SDValue>&Ops,
22349 SelectionDAG &DAG) const {
22352 // Only support length 1 constraints for now.
22353 if (Constraint.length() > 1) return;
22355 char ConstraintLetter = Constraint[0];
22356 switch (ConstraintLetter) {
22359 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22360 if (C->getZExtValue() <= 31) {
22361 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22367 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22368 if (C->getZExtValue() <= 63) {
22369 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22375 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22376 if (isInt<8>(C->getSExtValue())) {
22377 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22384 if (C->getZExtValue() <= 255) {
22385 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22391 // 32-bit signed value
22392 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22393 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22394 C->getSExtValue())) {
22395 // Widen to 64 bits here to get it sign extended.
22396 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22399 // FIXME gcc accepts some relocatable values here too, but only in certain
22400 // memory models; it's complicated.
22405 // 32-bit unsigned value
22406 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22407 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22408 C->getZExtValue())) {
22409 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22413 // FIXME gcc accepts some relocatable values here too, but only in certain
22414 // memory models; it's complicated.
22418 // Literal immediates are always ok.
22419 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22420 // Widen to 64 bits here to get it sign extended.
22421 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22425 // In any sort of PIC mode addresses need to be computed at runtime by
22426 // adding in a register or some sort of table lookup. These can't
22427 // be used as immediates.
22428 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22431 // If we are in non-pic codegen mode, we allow the address of a global (with
22432 // an optional displacement) to be used with 'i'.
22433 GlobalAddressSDNode *GA = nullptr;
22434 int64_t Offset = 0;
22436 // Match either (GA), (GA+C), (GA+C1+C2), etc.
22438 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22439 Offset += GA->getOffset();
22441 } else if (Op.getOpcode() == ISD::ADD) {
22442 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22443 Offset += C->getZExtValue();
22444 Op = Op.getOperand(0);
22447 } else if (Op.getOpcode() == ISD::SUB) {
22448 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22449 Offset += -C->getZExtValue();
22450 Op = Op.getOperand(0);
22455 // Otherwise, this isn't something we can handle, reject it.
22459 const GlobalValue *GV = GA->getGlobal();
22460 // If we require an extra load to get this address, as in PIC mode, we
22461 // can't accept it.
22462 if (isGlobalStubReference(
22463 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22466 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22467 GA->getValueType(0), Offset);
22472 if (Result.getNode()) {
22473 Ops.push_back(Result);
22476 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22479 std::pair<unsigned, const TargetRegisterClass*>
22480 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22482 // First, see if this is a constraint that directly corresponds to an LLVM
22484 if (Constraint.size() == 1) {
22485 // GCC Constraint Letters
22486 switch (Constraint[0]) {
22488 // TODO: Slight differences here in allocation order and leaving
22489 // RIP in the class. Do they matter any more here than they do
22490 // in the normal allocation?
22491 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22492 if (Subtarget->is64Bit()) {
22493 if (VT == MVT::i32 || VT == MVT::f32)
22494 return std::make_pair(0U, &X86::GR32RegClass);
22495 if (VT == MVT::i16)
22496 return std::make_pair(0U, &X86::GR16RegClass);
22497 if (VT == MVT::i8 || VT == MVT::i1)
22498 return std::make_pair(0U, &X86::GR8RegClass);
22499 if (VT == MVT::i64 || VT == MVT::f64)
22500 return std::make_pair(0U, &X86::GR64RegClass);
22503 // 32-bit fallthrough
22504 case 'Q': // Q_REGS
22505 if (VT == MVT::i32 || VT == MVT::f32)
22506 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22507 if (VT == MVT::i16)
22508 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22509 if (VT == MVT::i8 || VT == MVT::i1)
22510 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22511 if (VT == MVT::i64)
22512 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22514 case 'r': // GENERAL_REGS
22515 case 'l': // INDEX_REGS
22516 if (VT == MVT::i8 || VT == MVT::i1)
22517 return std::make_pair(0U, &X86::GR8RegClass);
22518 if (VT == MVT::i16)
22519 return std::make_pair(0U, &X86::GR16RegClass);
22520 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22521 return std::make_pair(0U, &X86::GR32RegClass);
22522 return std::make_pair(0U, &X86::GR64RegClass);
22523 case 'R': // LEGACY_REGS
22524 if (VT == MVT::i8 || VT == MVT::i1)
22525 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22526 if (VT == MVT::i16)
22527 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22528 if (VT == MVT::i32 || !Subtarget->is64Bit())
22529 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22530 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22531 case 'f': // FP Stack registers.
22532 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22533 // value to the correct fpstack register class.
22534 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22535 return std::make_pair(0U, &X86::RFP32RegClass);
22536 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22537 return std::make_pair(0U, &X86::RFP64RegClass);
22538 return std::make_pair(0U, &X86::RFP80RegClass);
22539 case 'y': // MMX_REGS if MMX allowed.
22540 if (!Subtarget->hasMMX()) break;
22541 return std::make_pair(0U, &X86::VR64RegClass);
22542 case 'Y': // SSE_REGS if SSE2 allowed
22543 if (!Subtarget->hasSSE2()) break;
22545 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22546 if (!Subtarget->hasSSE1()) break;
22548 switch (VT.SimpleTy) {
22550 // Scalar SSE types.
22553 return std::make_pair(0U, &X86::FR32RegClass);
22556 return std::make_pair(0U, &X86::FR64RegClass);
22564 return std::make_pair(0U, &X86::VR128RegClass);
22572 return std::make_pair(0U, &X86::VR256RegClass);
22577 return std::make_pair(0U, &X86::VR512RegClass);
22583 // Use the default implementation in TargetLowering to convert the register
22584 // constraint into a member of a register class.
22585 std::pair<unsigned, const TargetRegisterClass*> Res;
22586 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22588 // Not found as a standard register?
22590 // Map st(0) -> st(7) -> ST0
22591 if (Constraint.size() == 7 && Constraint[0] == '{' &&
22592 tolower(Constraint[1]) == 's' &&
22593 tolower(Constraint[2]) == 't' &&
22594 Constraint[3] == '(' &&
22595 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22596 Constraint[5] == ')' &&
22597 Constraint[6] == '}') {
22599 Res.first = X86::ST0+Constraint[4]-'0';
22600 Res.second = &X86::RFP80RegClass;
22604 // GCC allows "st(0)" to be called just plain "st".
22605 if (StringRef("{st}").equals_lower(Constraint)) {
22606 Res.first = X86::ST0;
22607 Res.second = &X86::RFP80RegClass;
22612 if (StringRef("{flags}").equals_lower(Constraint)) {
22613 Res.first = X86::EFLAGS;
22614 Res.second = &X86::CCRRegClass;
22618 // 'A' means EAX + EDX.
22619 if (Constraint == "A") {
22620 Res.first = X86::EAX;
22621 Res.second = &X86::GR32_ADRegClass;
22627 // Otherwise, check to see if this is a register class of the wrong value
22628 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22629 // turn into {ax},{dx}.
22630 if (Res.second->hasType(VT))
22631 return Res; // Correct type already, nothing to do.
22633 // All of the single-register GCC register classes map their values onto
22634 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
22635 // really want an 8-bit or 32-bit register, map to the appropriate register
22636 // class and return the appropriate register.
22637 if (Res.second == &X86::GR16RegClass) {
22638 if (VT == MVT::i8 || VT == MVT::i1) {
22639 unsigned DestReg = 0;
22640 switch (Res.first) {
22642 case X86::AX: DestReg = X86::AL; break;
22643 case X86::DX: DestReg = X86::DL; break;
22644 case X86::CX: DestReg = X86::CL; break;
22645 case X86::BX: DestReg = X86::BL; break;
22648 Res.first = DestReg;
22649 Res.second = &X86::GR8RegClass;
22651 } else if (VT == MVT::i32 || VT == MVT::f32) {
22652 unsigned DestReg = 0;
22653 switch (Res.first) {
22655 case X86::AX: DestReg = X86::EAX; break;
22656 case X86::DX: DestReg = X86::EDX; break;
22657 case X86::CX: DestReg = X86::ECX; break;
22658 case X86::BX: DestReg = X86::EBX; break;
22659 case X86::SI: DestReg = X86::ESI; break;
22660 case X86::DI: DestReg = X86::EDI; break;
22661 case X86::BP: DestReg = X86::EBP; break;
22662 case X86::SP: DestReg = X86::ESP; break;
22665 Res.first = DestReg;
22666 Res.second = &X86::GR32RegClass;
22668 } else if (VT == MVT::i64 || VT == MVT::f64) {
22669 unsigned DestReg = 0;
22670 switch (Res.first) {
22672 case X86::AX: DestReg = X86::RAX; break;
22673 case X86::DX: DestReg = X86::RDX; break;
22674 case X86::CX: DestReg = X86::RCX; break;
22675 case X86::BX: DestReg = X86::RBX; break;
22676 case X86::SI: DestReg = X86::RSI; break;
22677 case X86::DI: DestReg = X86::RDI; break;
22678 case X86::BP: DestReg = X86::RBP; break;
22679 case X86::SP: DestReg = X86::RSP; break;
22682 Res.first = DestReg;
22683 Res.second = &X86::GR64RegClass;
22686 } else if (Res.second == &X86::FR32RegClass ||
22687 Res.second == &X86::FR64RegClass ||
22688 Res.second == &X86::VR128RegClass ||
22689 Res.second == &X86::VR256RegClass ||
22690 Res.second == &X86::FR32XRegClass ||
22691 Res.second == &X86::FR64XRegClass ||
22692 Res.second == &X86::VR128XRegClass ||
22693 Res.second == &X86::VR256XRegClass ||
22694 Res.second == &X86::VR512RegClass) {
22695 // Handle references to XMM physical registers that got mapped into the
22696 // wrong class. This can happen with constraints like {xmm0} where the
22697 // target independent register mapper will just pick the first match it can
22698 // find, ignoring the required type.
22700 if (VT == MVT::f32 || VT == MVT::i32)
22701 Res.second = &X86::FR32RegClass;
22702 else if (VT == MVT::f64 || VT == MVT::i64)
22703 Res.second = &X86::FR64RegClass;
22704 else if (X86::VR128RegClass.hasType(VT))
22705 Res.second = &X86::VR128RegClass;
22706 else if (X86::VR256RegClass.hasType(VT))
22707 Res.second = &X86::VR256RegClass;
22708 else if (X86::VR512RegClass.hasType(VT))
22709 Res.second = &X86::VR512RegClass;
22715 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22717 // Scaling factors are not free at all.
22718 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22719 // will take 2 allocations in the out of order engine instead of 1
22720 // for plain addressing mode, i.e. inst (reg1).
22722 // vaddps (%rsi,%drx), %ymm0, %ymm1
22723 // Requires two allocations (one for the load, one for the computation)
22725 // vaddps (%rsi), %ymm0, %ymm1
22726 // Requires just 1 allocation, i.e., freeing allocations for other operations
22727 // and having less micro operations to execute.
22729 // For some X86 architectures, this is even worse because for instance for
22730 // stores, the complex addressing mode forces the instruction to use the
22731 // "load" ports instead of the dedicated "store" port.
22732 // E.g., on Haswell:
22733 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22734 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
22735 if (isLegalAddressingMode(AM, Ty))
22736 // Scale represents reg2 * scale, thus account for 1
22737 // as soon as we use a second register.
22738 return AM.Scale != 0;
22742 bool X86TargetLowering::isTargetFTOL() const {
22743 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();